package com.gh.gamecenter.home.recommend

import android.widget.GridView
import com.gh.gamecenter.common.base.BaseRecyclerViewHolder
import com.gh.gamecenter.common.utils.dip2px
import com.gh.gamecenter.databinding.ItemHomeRecommendListBinding
import com.gh.gamecenter.entity.HomeRecommend
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.feature.exposure.ExposureEvent
import com.gh.gamecenter.feature.exposure.ExposureSource
import com.gh.gamecenter.home.HomeItemData

/**
 * 首页-推荐-banner 下面的 一排按钮
 */

class HomeRecommendItemViewHolder(val binding: ItemHomeRecommendListBinding) :
    BaseRecyclerViewHolder<Any>(binding.root) {

    private fun initGrid(spanCount: Int): HomeRecommendItemGridAdapter {
        val itemGridAdapter = HomeRecommendItemGridAdapter()
        binding.recommendGv.stretchMode = GridView.STRETCH_SPACING
        binding.recommendGv.numColumns = spanCount
        binding.recommendGv.columnWidth = 60F.dip2px()
        binding.recommendGv.adapter = itemGridAdapter
        return itemGridAdapter
    }

    /**
     * 数据处理
     * 当后台“日常管理（新）-首页推荐入口（新）/多渠道多版本-首页推荐入口”配置的可显示的内容≥10个时，前端需要支持展示两行首页推荐入口
     * 1， 如果  6≤推荐入口数量＜10 ，前端均仅显示一行推荐入口的内容
     * 2， 如果 推荐入口数量＜5 ，还是保留原有的规则平铺展示
     */
    private fun mapData(itemData: HomeItemData, basicExposureSource: List<ExposureSource>): List<HomeRecommend> {
        val list = itemData.recommends ?: emptyList()
        list.forEachIndexed { index, homeRecommend ->
            val exposureEvent = ExposureEvent.createEventWithSourceConcat(
                gameEntity = GameEntity().also { it.sequence = index },
                basicSource = basicExposureSource,
                source = listOf(ExposureSource("推荐入口", homeRecommend.name))
            )
            exposureEvent.payload.controlType = "推荐入口"
            exposureEvent.payload.controlName = homeRecommend.name
            exposureEvent.payload.controlLinkName = homeRecommend.linkText
            exposureEvent.payload.controlLinkType = homeRecommend.linkType
            itemData.exposureEventList?.add(exposureEvent)
        }
        val column = (list.size / MAX_SPAN_COUNT) // 显示几行
        val count = if (column == 0) {
            list.count()
        } else {
            column * MAX_SPAN_COUNT
        }
        return list.take(minOf(10, count))
    }

    fun bindRecommend(itemData: HomeItemData, basicExposureSource: List<ExposureSource>) {
        val recommends = mapData(itemData, basicExposureSource)
        val size = recommends.size
        if (size == 0) return
        val spanCount = minOf(size, MAX_SPAN_COUNT)
        val adapter = initGrid(spanCount)
        adapter.mDataList = recommends
        adapter.notifyDataSetChanged()
    }

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