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

import android.view.View
import android.view.ViewGroup
import android.view.ViewGroup.MarginLayoutParams
import androidx.core.view.updateLayoutParams
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.gh.gamecenter.R
import com.gh.gamecenter.common.entity.LinkEntity
import com.gh.gamecenter.common.exposure.ExposureSource
import com.gh.gamecenter.common.utils.dip2px
import com.gh.gamecenter.common.utils.goneIf
import com.gh.gamecenter.common.utils.visibleIf
import com.gh.gamecenter.common.view.GridSpacingItemColorDecoration
import com.gh.gamecenter.core.runOnIoThread
import com.gh.gamecenter.databinding.ItemHomeRecentVgameBinding
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.feature.exposure.ExposureEvent
import com.gh.gamecenter.home.custom.CustomPageViewModel
import com.gh.gamecenter.home.custom.adapter.CustomPageAdapter
import com.gh.gamecenter.home.custom.createExposureEvent
import com.gh.gamecenter.home.custom.eventlistener.RecentMiniGameItemEventHelper
import com.gh.gamecenter.home.custom.model.CustomPageItem
import com.gh.gamecenter.home.custom.model.CustomRecentQqMiniGamesItem
import com.gh.gamecenter.home.custom.model.CustomRecentWeChatMiniGamesItem
import com.gh.gamecenter.minigame.MiniGameRecentlyPlayListAdapter

/**
 * 小游戏-最近在玩
 */
class CustomHomeRecentMiniGameViewHolder(
    viewModel: CustomPageViewModel,
    var binding: ItemHomeRecentVgameBinding
) : BaseCustomViewHolder(viewModel, binding.root) {

    override val childEventHelper: RecentMiniGameItemEventHelper by lazy { RecentMiniGameItemEventHelper(viewModel) }

    override fun bindView(item: CustomPageItem) {
        super.bindView(item)
        binding.vspaceIv.visibility = View.GONE
        binding.divider.visibility = View.GONE
        if (item is CustomRecentWeChatMiniGamesItem) {
            // 微信小游戏最近在玩，不需要显示右上角
            binding.moreTv.visibleIf(false)
        }
        if (item is CustomRecentQqMiniGamesItem) {
            binding.moreTv.visibleIf(true)
            binding.moreTv.text = itemView.context.getString(R.string.custom_home_text_more)
            binding.moreTv.setOnClickListener {
                val link = item.linkQqGameRecentlyPlayed.moreLink ?: LinkEntity(type = "qq_mini_game_column")
                childEventHelper.navigateToLinkPage(link)
            }
        }

        val entities = when (item) {
            is CustomRecentWeChatMiniGamesItem -> {
                item.data
            }

            is CustomRecentQqMiniGamesItem -> {
                item.data
            }

            else -> listOf()
        }

        runOnIoThread(isLightWeightTask = true) {
            fillExposureEventList(item, entities)
        }

        if (entities.isEmpty()) {
            binding.root.goneIf(true)
            binding.root.updateLayoutParams {
                // 这里为什么当 viewHolder 为0时，需要将高度设为 1呢？
                // 因为当 viewHolder为第一个位置时，如果高度为0，用户想下拉刷新时，在计算RecyclerView滚动距离的时候，会从第二个itemView开始算起，从而得出错误的结果
                // 这会导致下拉无法触发刷新回调
                height = if (bindingAdapterPosition == 0) {
                    1
                } else {
                    0
                }
                width = RecyclerView.LayoutParams.MATCH_PARENT
                if (this is MarginLayoutParams) {
                    topMargin = 0
                    bottomMargin = 0
                }
            }
        } else {
            binding.root.goneIf(false)
            binding.root.updateLayoutParams {
                height = 106F.dip2px()
                width = RecyclerView.LayoutParams.MATCH_PARENT
                if (this is MarginLayoutParams) {
                    topMargin = 8F.dip2px()
                    bottomMargin = 8F.dip2px()
                }
            }
        }
        binding.titleTv.text = item.componentName

        val gameListAdapter = if (binding.recyclerView.adapter == null) {
            val layoutManager =
                LinearLayoutManager(binding.root.context, RecyclerView.HORIZONTAL, false)

            binding.recyclerView.layoutManager = layoutManager
            binding.recyclerView.itemAnimator = null

            val adapter = MiniGameRecentlyPlayListAdapter(binding.root.context) { game, position ->
                childEventHelper.navigateToGameDetailPage(position, game)
            }
            binding.recyclerView.adapter = adapter
            binding.recyclerView.addItemDecoration(
                GridSpacingItemColorDecoration(binding.root.context, 4, 0, com.gh.gamecenter.common.R.color.transparent)
            )

            binding.recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
                override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                    if (dx == 0) {
                        val scrollToEnd =
                            layoutManager.findLastCompletelyVisibleItemPosition() == (binding.recyclerView.adapter!!.itemCount - 1)
                        // 当游戏数量超过一屏时，需去除列表右侧的分隔线；去除后，列表最后一个游戏图标与卡片右侧的边距应为16dp
                        if (scrollToEnd) {
                            binding.recyclerViewContainer.post {
                                binding.recyclerViewContainer.layoutParams =
                                    (binding.recyclerViewContainer.layoutParams as ViewGroup.MarginLayoutParams).apply {
                                        rightMargin = 10F.dip2px()
                                    }
                            }
                            binding.divider.visibility = View.VISIBLE

                        } else {
                            binding.recyclerViewContainer.post {
                                binding.recyclerViewContainer.layoutParams =
                                    (binding.recyclerViewContainer.layoutParams as ViewGroup.MarginLayoutParams).apply {
                                        rightMargin = 0
                                    }
                            }
                            binding.divider.visibility = View.GONE
                        }
                    }
                }
            })
            adapter
        } else {
            binding.recyclerView.adapter as MiniGameRecentlyPlayListAdapter
        }

        gameListAdapter.submitList(entities)

        val bindingAdapter = bindingAdapter
        if (bindingAdapter is CustomPageAdapter) {
            bindingAdapter.updateFirstItemId()
        }
    }

    private fun fillExposureEventList(item: CustomPageItem, entities: List<GameEntity>) {
        entities.forEachIndexed { index, game ->
            game.exposureEvent = createExposureEvent(
                game,
                listOf(ExposureSource(item.componentName, "")),
                pageConfigure.exposureSourceList,
                index,
                item.componentPosition,
                createTrackData(item)
            )
        }
    }
}
