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

import android.content.Context
import android.graphics.Rect
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.gh.common.util.AdHelper
import com.gh.gamecenter.common.exposure.ExposureSource
import com.gh.gamecenter.common.utils.dip2px
import com.gh.gamecenter.core.runOnIoThread
import com.gh.gamecenter.databinding.HomeGameCollectionRefreshItemCustomBinding
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.home.custom.CustomPageViewModel
import com.gh.gamecenter.home.custom.adapter.CustomRefreshIconAdapter
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.CustomPageItem.Companion.COMPONENTS_COLLECTION_STYLE_REFRESH_ICONS_4_2
import com.gh.gamecenter.home.custom.model.CustomSubjectCollectionItem

/**
 * 专题合集：轮换刷新-图标泳道
 * 专题合集:轮换刷新-图标矩阵
 * 游戏单合集-轮换刷新-横排列表
 */
class CustomRefreshIconViewHolder(
    private val context: Context,
    viewModel: CustomPageViewModel,
    private val isMatrix: Boolean,
    val binding: HomeGameCollectionRefreshItemCustomBinding
) :
    BaseCustomViewHolder(viewModel, binding.root) {

    private val showSubject: CustomPageData.LinkColumnCollection.CustomSubjectEntity?
        get() = (_item as? CustomSubjectCollectionItem)?.showSubject

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

    private val adapter by lazy {
        CustomRefreshIconAdapter(context, childEventHelper)
    }

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

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

    override fun bindView(item: CustomPageItem) {
        super.bindView(item)
        if (item is CustomSubjectCollectionItem) {
            val collection = item.data

            setSubjectCollectionTitle(item, binding.layoutTitle, childEventHelper, true)

            if (binding.recyclerView.adapter == null) {
                val layoutManager = if (isMatrix) {
                    binding.recyclerView.isNestedScrollingEnabled = false
                    GridLayoutManager(context, 4, RecyclerView.VERTICAL, false)
                } else {
                    LinearLayoutManager(context, RecyclerView.HORIZONTAL, false)
                }
                binding.recyclerView.layoutManager = layoutManager
                if (isMatrix) {
                    binding.recyclerView.addItemDecoration(MyItemDecoration())
                }

                binding.recyclerView.adapter = adapter
            }

            val subjectEntity = item.showSubject ?: return

            runOnIoThread(isLightWeightTask = true) {
                for ((index, game) in subjectEntity.games.withIndex()) {
                    fillExposureInfo(subjectEntity, game, index)
                }
            }

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

            // 如果游戏全部被屏蔽，自动加载下一页
            if (subjectEntity.games.isEmpty()) {
                childEventHelper.onRotateRefresh()
            } else {
                if (item.isBackToStart) {
                    item.isBackToStart = false
                    binding.recyclerView.scrollToPosition(0)
                }
                // 如果是 专题合集-图标矩阵，则需要读取后台返回的rows_num字段
                val games = if (item.data.style == COMPONENTS_COLLECTION_STYLE_REFRESH_ICONS_4_2) {
                    val needGameCount = item.data.styleSetting.rowsNum * 4
                    subjectEntity.games.take(needGameCount)
                } else {
                    subjectEntity.games
                }
                adapter.setData(collection.name, collection.id, subjectEntity, games)
            }
        }
    }

    private fun fillExposureInfo(subject: CustomPageData.LinkColumnCollection.CustomSubjectEntity,
                                 game: GameEntity,
                                 position: Int
    ) {
            (_item as? CustomSubjectCollectionItem)?.let {
                val source = if (it.isSubjectCollection) {
                    listOf(
                        ExposureSource("专题合集", "${it.data.name}+${it.componentStyle}+${it.data.id}"),
                        ExposureSource("专题", "${subject.title}+${subject.styleChinese}+${subject.id}")
                    )
                } else {
                    listOf(
                        ExposureSource("游戏单合集", "${it.data.name}+${it.componentStyle}+${it.data.id}"),
                        ExposureSource("游戏单", "${subject.title}+${subject.id}")
                    )
                }
                game.isAdData = subject.adIconActive
                game.exposureEvent = createExposureEvent(
                    game,
                    source,
                    pageConfigure.exposureSourceList,
                    position,
                    _item.componentPosition,
                    createTrackData(_item)
                )

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

    class MyItemDecoration : RecyclerView.ItemDecoration() {
        override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
            val position = parent.getChildAdapterPosition(view)
            val isFirstLine = position <= 3
            outRect.top = if (isFirstLine) {
                0
            } else {
                16f.dip2px()
            }
        }
    }
}