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

import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.gh.common.util.AdHelper
import com.gh.gamecenter.common.exposure.ExposureSource
import com.gh.gamecenter.core.runOnIoThread
import com.gh.gamecenter.databinding.GameVerticalSlideItemCustomBinding
import com.gh.gamecenter.game.vertical.SpanCountPagerSnapHelper
import com.gh.gamecenter.home.custom.CustomPageViewModel
import com.gh.gamecenter.home.custom.IGameChangedNotifier
import com.gh.gamecenter.home.custom.adapter.CustomGameRefreshVerticalAdapter
import com.gh.gamecenter.home.custom.createExposureEvent
import com.gh.gamecenter.home.custom.eventlistener.GameSubjectCollectionEventHelper
import com.gh.gamecenter.home.custom.model.CustomPageData
import com.gh.gamecenter.home.custom.model.CustomPageItem
import com.gh.gamecenter.home.custom.model.CustomSubjectCollectionItem

/**
 * 专题合集：轮换刷新:滑动列表
 * 游戏单合集：轮换刷新-竖排列表
 */
class CustomGameCollectionRefreshVerticalSlideViewHolder(
    viewModel: CustomPageViewModel,
    val binding: GameVerticalSlideItemCustomBinding,
) :
    BaseCustomViewHolder(viewModel, binding.root) {

    private var spanCount = 3
    private var snapHelper: SpanCountPagerSnapHelper? = null

    private var _subjectEntity: CustomPageData.LinkColumnCollection.CustomSubjectEntity? = null

    override val childEventHelper by lazy(LazyThreadSafetyMode.NONE) {
        GameSubjectCollectionEventHelper(viewModel)
    }

    private val adapter by lazy {
        CustomGameRefreshVerticalAdapter(
            itemView.context, pageConfigure.transparentBackground,
            childEventHelper
        )
    }

    override val gameChangedNotifier: IGameChangedNotifier
        get() = adapter

    init {
        binding.recyclerView.isNestedScrollingEnabled = false
        binding.recyclerView.itemAnimator = null
    }

    override fun bindView(item: CustomPageItem) {
        super.bindView(item)
        if (item is CustomSubjectCollectionItem) {
            setSubjectCollectionTitle(
                item,
                binding.layoutTitle,
                childEventHelper,
                true,
                TITLE_TYPE_SMALL
            )

            val subjectEntity = item.showSubject ?: return
            if (subjectEntity.id == _subjectEntity?.id) {
                adapter.notifyItemRangeChanged(0, adapter.itemCount)
                return
            } else {
                _subjectEntity = subjectEntity
            }

            val games = subjectEntity.games
            spanCount = if (games.size < 3) games.size else 3

            runOnIoThread(isLightWeightTask = true) {
                fillExposureInfo(item, subjectEntity)
            }

            if (binding.recyclerView.adapter == null) {
                binding.recyclerView.clearOnScrollListeners()
                snapHelper = SpanCountPagerSnapHelper(spanCount, true)
                binding.recyclerView.layoutManager =
                    GridLayoutManager(itemView.context, spanCount, RecyclerView.HORIZONTAL, false)
                binding.recyclerView.adapter = adapter
                snapHelper?.let {
                    it.attachToRecyclerView(binding.recyclerView)
                }
            }
            changeSpanCountIfNeeded()

            // 如果游戏全部被屏蔽，自动加载下一页
            if (games.isEmpty()) {
                childEventHelper.onRotateRefresh()
            } else {
                if (item.isBackToStart) {
                    item.isBackToStart = false
                    binding.recyclerView.scrollToPosition(0)
                }
                adapter.setData(spanCount, data = item, subjectEntity)
            }
        }
    }

    private fun fillExposureInfo(
        item: CustomSubjectCollectionItem,
        subjectEntity: CustomPageData.LinkColumnCollection.CustomSubjectEntity
    ) {
        val games = subjectEntity.games
        val source = if (item.isSubjectCollection) {
            listOf(
                ExposureSource("专题合集", "${item.data.name}+${item.componentStyle}+${item.data.id}"),
                ExposureSource(
                    "专题",
                    "${subjectEntity.title}+${subjectEntity.styleChinese}+${subjectEntity.id}"
                )
            )
        } else {
            listOf(
                ExposureSource("游戏单合集", "${item.data.name}+${item.componentStyle}+${item.data.id}"),
                ExposureSource("游戏单", "${subjectEntity.title}+${subjectEntity.id}")
            )
        }

        for ((i, game) in games.withIndex()) {
            game.isAdData = subjectEntity.adIconActive
            game.exposureEvent = createExposureEvent(
                game,
                source,
                pageConfigure.exposureSourceList,
                i,
                item.componentPosition,
                createTrackData(item)
            )

            if (game.adGroupId.isNotEmpty() && !game.isAdRequestReported) {
                AdHelper.reportAdRequest(game.exposureEvent!!)
                game.isAdRequestReported = true
            }
        }
    }

    private fun changeSpanCountIfNeeded() {
        binding.recyclerView.run {
            if (spanCount != (layoutManager as GridLayoutManager).spanCount) {
                snapHelper?.spanCount = spanCount
                (layoutManager as GridLayoutManager).spanCount = spanCount
            }
        }
    }
}
