package com.gh.gamecenter.home.custom.viewholder

import com.gh.gamecenter.common.exposure.ExposureSource
import com.gh.gamecenter.core.runOnIoThread
import com.gh.gamecenter.databinding.RecyclerRecommendCardCustomBinding
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.home.custom.CustomPageViewModel
import com.gh.gamecenter.home.custom.createExposureEvent
import com.gh.gamecenter.home.custom.eventlistener.CommonContentCollectionEventHelper
import com.gh.gamecenter.home.custom.model.CustomCommonContentCollectionItem
import com.gh.gamecenter.home.custom.model.CustomPageData.RecommendCard
import com.gh.gamecenter.home.custom.model.CustomPageItem
import com.gh.gamecenter.home.custom.ui.RecommendCardUi

/**
 * 通用内容合集-推荐卡片
 */
class CustomRecommendCardViewHolder(
    viewModel: CustomPageViewModel,
    val binding: RecyclerRecommendCardCustomBinding
) : BaseCustomViewHolder(viewModel, binding.root) {

    private val recommendCardUi = RecommendCardUi(binding, object : RecommendCardUi.OnRecommendCardEventListener {
        override fun onItemClick(childPosition: Int, card: RecommendCard) {
            childEventHelper.navigateToLinkPage(card.link, "内容卡片", card.exposureEvent)
        }

        override fun onAllClick() {
            childEventHelper.navigateToCommonCollectionDetailPage(_item.link)
        }
    })

    override val childEventHelper by lazy {
        CommonContentCollectionEventHelper(viewModel)
    }

    override fun bindView(item: CustomPageItem) {
        super.bindView(item)
        if (item is CustomCommonContentCollectionItem) {
            runOnIoThread(isLightWeightTask = true) {
                fillExposureInfo(item.data.recommendCards)
            }
            recommendCardUi.bind(item.data.topRightText, item.data.name, item.data.subtitle, item.data.recommendCards)
        }
    }

    private fun fillExposureInfo(dataList: List<RecommendCard>) {
        for ((index, card) in dataList.withIndex()) {
            val item = _item as CustomCommonContentCollectionItem
            val gameEntity = if (card.linkType == "game") {
                GameEntity(id = card.linkId, name = card.linkText)
            } else {
                GameEntity()
            }
            card.exposureEvent = createExposureEvent(
                gameEntity.also {
                    it.sequence = index
                    it.outerSequence = _item.position
                },
                listOf(
                    ExposureSource(
                        "通用内容合集",
                        "${item.data.name}+${item.data.layoutChinese}+${item.data.id}"
                    )
                ),
                pageConfigure.exposureSourceList,
                index,
                _item.componentPosition,
                createTrackData(item)
            )
        }
    }
}