package com.gh.gamecenter.home.custom.ui

import android.widget.GridView
import com.gh.gamecenter.common.entity.LinkEntity
import com.gh.gamecenter.common.utils.dip2px
import com.gh.gamecenter.databinding.ItemHomeRecommendListCustomBinding
import com.gh.gamecenter.entity.HomeRecommend
import com.gh.gamecenter.feature.exposure.ExposureEvent
import com.gh.gamecenter.home.custom.adapter.CustomHomeRecommendItemGridAdapter
import com.gh.gamecenter.home.custom.viewholder.CustomHomeRecommendItemViewHolder

/**
 * ui-通用内容合集-金刚区
 */
class CommonContentRecommendUi(
    val binding: ItemHomeRecommendListCustomBinding,
    private val listener: OnRecommendListener
) {

    private val adapter by lazy {
        CustomHomeRecommendItemGridAdapter(object : CustomHomeRecommendItemGridAdapter.OnEventListener {
            override fun navigateToLinkPage(link: LinkEntity, text: String, exposureEvent: ExposureEvent?) {
                listener.navigateToLinkPage(link, text, exposureEvent)
            }
        })
    }

    /**
     * 数据处理
     * 当后台“日常管理（新）-首页推荐入口（新）/多渠道多版本-首页推荐入口”配置的可显示的内容≥10个时，前端需要支持展示两行首页推荐入口
     * 1， 如果  6≤推荐入口数量＜10 ，前端均仅显示一行推荐入口的内容
     * 2， 如果 推荐入口数量＜5 ，还是保留原有的规则平铺展示
     */
    private fun mapData(recommends: List<HomeRecommend>): List<HomeRecommend> {
        val column = (recommends.size / MAX_SPAN_COUNT) // 显示几行
        val count = if (column == 0) {
            recommends.count()
        } else {
            column * MAX_SPAN_COUNT
        }
        return recommends.take(minOf(10, count))
    }

    fun bind(recommends: List<HomeRecommend>, exposureList: List<ExposureEvent>?) {
        val filteredList = mapData(recommends)
        val size = recommends.size
        if (size == 0) return
        val spanCount = minOf(size, CustomHomeRecommendItemViewHolder.MAX_SPAN_COUNT)
        if (binding.recommendGv.adapter == null) {
            binding.recommendGv.stretchMode = GridView.STRETCH_SPACING
            binding.recommendGv.numColumns = spanCount
            binding.recommendGv.columnWidth = 60F.dip2px()
        } else {
            val oldSpanCount = binding.recommendGv.numColumns
            if (oldSpanCount != spanCount) {
                binding.recommendGv.numColumns = spanCount
            }
        }
        binding.recommendGv.adapter = adapter
        adapter.submitList(filteredList, spanCount, exposureList)
    }

    companion object {
        //图标最多列数
        private const val MAX_SPAN_COUNT = 5
    }

    interface OnRecommendListener {

        fun navigateToLinkPage(link: LinkEntity, text: String, exposureEvent: ExposureEvent?)
    }
}