package com.gh.gamecenter.home.gamecollection.refresh

import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.gh.common.util.DirectUtils
import com.gh.common.util.NewFlatLogUtils
import com.gh.gamecenter.common.base.BaseRecyclerViewHolder
import com.gh.gamecenter.common.json.json
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.common.view.FixLinearLayoutManager
import com.gh.gamecenter.databinding.HomeGameCollectionRefreshItemBinding
import com.gh.gamecenter.entity.GameListCollection
import com.gh.gamecenter.entity.HomeGameCollectionEntity
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.game.vertical.SpanCountPagerSnapHelper
import com.gh.gamecenter.gamecollection.square.GameCollectionListItemData
import com.gh.gamecenter.home.LegacyHomeFragmentAdapterAssistant

/**
 * 首页内容列表/版块内容列表-游戏单合集-刷新轮换-竖排列表/横排列表
 */
class HomeGameCollectionRefreshViewHolder(val binding: HomeGameCollectionRefreshItemBinding) :
    BaseRecyclerViewHolder<ViewHolder>(binding.root) {
    private var mIsHorizontal = false
    private var mSpanCount = 0
    var currentPosition = 0
    private var mSnapHelper: SpanCountPagerSnapHelper? = null
    private var mGameCollectionList: List<GameCollectionListItemData>? = null
    private var mGameCollectionItemData: GameCollectionListItemData? = null
    private var mGameCollection: HomeGameCollectionEntity? = null
    private var mGameList: List<GameEntity> = listOf()
    private var mDarkMode = DarkModeUtils.isDarkModeOn(binding.root.context)

    fun bindGameCollectionRefresh(
        gameListCollection: GameListCollection,
        entrance: String,
        blockId: String = "",
        blockName: String = "",
        refreshAction: () -> Boolean
    ) {
        mGameCollectionList = gameListCollection.gameCollectionItemDataList
        refreshGameCollection()

        if (DarkModeUtils.isDarkModeOn(binding.root.context) != mDarkMode) {
            mDarkMode = DarkModeUtils.isDarkModeOn(binding.root.context)
            binding.run {
                titleTv.setTextColor(com.gh.gamecenter.common.R.color.text_primary.toColor(root.context))
                userTv.setTextColor(com.gh.gamecenter.common.R.color.text_tertiary.toColor(root.context))
                refreshLottie.cancelAnimation()
                refreshLottie.setAnimation(if (DarkModeUtils.isDarkModeOn(root.context)) "lottie/icon_title_change_dark.json" else "lottie/icon_title_change_light.json")
                refreshLottie.progress = 0F
            }
        }

        val isHorizontal =
            gameListCollection.style == LegacyHomeFragmentAdapterAssistant.GAME_COLLECTION_HORIZONTAL_REFRESH_STYLE
        if (binding.recyclerView.adapter is HomeGameCollectionRefreshAdapter && mIsHorizontal == isHorizontal) {
            if (!mIsHorizontal) changeSpanCountIfNeeded()
            (binding.recyclerView.adapter as HomeGameCollectionRefreshAdapter).checkResetData(mGameList, mSpanCount)
            return
        }

        mIsHorizontal = isHorizontal
        binding.refreshLottie.setAnimation(if (DarkModeUtils.isDarkModeOn(binding.root.context)) "lottie/icon_title_change_dark.json" else "lottie/icon_title_change_light.json")
        binding.recyclerView.run {
            clearOnScrollListeners()
            onFlingListener = null
            if (mIsHorizontal) {
                layoutParams = (layoutParams as ConstraintLayout.LayoutParams).also { it.topMargin = 16F.dip2px() }
                (itemAnimator as DefaultItemAnimator).supportsChangeAnimations = true
                layoutManager = FixLinearLayoutManager(context, RecyclerView.HORIZONTAL, false)
                adapter = HomeGameCollectionRefreshAdapter(
                    context,
                    mIsHorizontal,
                    0,
                    mGameList,
                    entrance,
                    blockId,
                    blockName,
                    gameListCollection.id,
                    gameListCollection.name
                )
            } else {
                layoutParams = (layoutParams as ConstraintLayout.LayoutParams).also { it.topMargin = 8F.dip2px() }
                mSnapHelper = SpanCountPagerSnapHelper(mSpanCount, true)
                (itemAnimator as DefaultItemAnimator).supportsChangeAnimations = false
                layoutManager = GridLayoutManager(context, mSpanCount, RecyclerView.HORIZONTAL, false)
                adapter = HomeGameCollectionRefreshAdapter(
                    context,
                    mIsHorizontal,
                    mSpanCount,
                    mGameList,
                    entrance,
                    blockId,
                    blockName,
                    gameListCollection.id,
                    gameListCollection.name
                )
                mSnapHelper?.attachToRecyclerView(this)
                isNestedScrollingEnabled = false
            }
        }

        listOf(binding.moreTv, binding.arrowIv).forEach {
            it.setOnClickListener { view ->
                NewFlatLogUtils.logGameListCollectionClick(
                    entrance,
                    blockName,
                    blockId,
                    gameListCollection.name,
                    gameListCollection.id,
                    "全部"
                )
                SensorsBridge.trackEvent("GameListCollectionClick", json {
                    "location" to if (entrance.contains("首页")) "首页" else if (entrance.contains("版块")) "版块" else ""
                    "block_name" to blockName
                    "block_id" to blockId
                    "game_list_collection_name" to gameListCollection.name
                    "game_list_collection_id" to gameListCollection.id
                    "text" to "游戏单"
                    "game_collect_title" to mGameCollection?.title
                    "game_collect_id" to mGameCollection?.id
                })
                DirectUtils.directToGameCollectionDetail(
                    view.context,
                    mGameCollection?.id ?: "",
                    entrance,
                    "游戏单合集",
                    mGameCollectionItemData?.exposureEvent
                )
            }
        }
        listOf(binding.userIconCv, binding.userTv).forEach {
            it.setOnClickListener {
                NewFlatLogUtils.logGameListCollectionClick(
                    entrance,
                    blockName,
                    blockId,
                    gameListCollection.name,
                    gameListCollection.id,
                    "个人主页"
                )
                SensorsBridge.trackEvent("GameListCollectionClick", json {
                    "location" to if (entrance.contains("首页")) "首页" else if (entrance.contains("版块")) "版块" else ""
                    "block_name" to blockName
                    "block_id" to blockId
                    "game_list_collection_name" to gameListCollection.name
                    "game_list_collection_id" to gameListCollection.id
                    "text" to "个人主页"
                    "mongold_id" to mGameCollection?.user?.id
                })
                DirectUtils.directToHomeActivity(
                    binding.root.context,
                    mGameCollection?.user?.id,
                    0,
                    entrance,
                    "游戏单合集"
                )
            }
        }
        binding.refreshLottie.setOnClickListener {
            if (!binding.refreshLottie.isAnimating) {
                binding.refreshLottie.playAnimation()
                currentPosition++
                if (!refreshAction()) {
                    refreshGameCollection()
                    if (!mIsHorizontal) changeSpanCountIfNeeded()
                    if (binding.recyclerView.adapter is HomeGameCollectionRefreshAdapter) {
                        (binding.recyclerView.adapter as HomeGameCollectionRefreshAdapter).checkResetData(
                            mGameList,
                            mSpanCount
                        )
                    }
                }
                NewFlatLogUtils.logGameListCollectionClick(
                    entrance,
                    blockName,
                    blockId,
                    gameListCollection.name,
                    gameListCollection.id,
                    "刷新"
                )
                SensorsBridge.trackEvent("GameListCollectionClick", json {
                    "location" to if (entrance.contains("首页")) "首页" else if (entrance.contains("版块")) "版块" else ""
                    "block_name" to blockName
                    "block_id" to blockId
                    "game_list_collection_name" to gameListCollection.name
                    "game_list_collection_id" to gameListCollection.id
                    "text" to "刷新"
                })
            }
        }
    }

    private fun refreshGameCollection() {
        mGameCollectionList?.let {
            mGameCollectionItemData = it.safelyGetInRelease(currentPosition % it.size)
            mGameCollection = mGameCollectionItemData?.homeGameCollectionItem
            mGameList = mGameCollection?.games ?: listOf()
            mSpanCount = if (mGameList.size < 3) mGameList.size else 3
        }
        ImageUtils.display(binding.userIv, mGameCollection?.user?.icon)
        binding.userTv.text = "${mGameCollection?.user?.name} 游戏单"
        binding.titleTv.text = mGameCollection?.title
    }

    private fun changeSpanCountIfNeeded() {
        binding.recyclerView.run {
            if (mSpanCount != (layoutManager as GridLayoutManager).spanCount) {
                clearOnScrollListeners()
                (itemAnimator as DefaultItemAnimator).supportsChangeAnimations = false
                onFlingListener = null
                layoutManager =
                    GridLayoutManager(binding.recyclerView.context, mSpanCount, RecyclerView.HORIZONTAL, false)
                mSnapHelper = SpanCountPagerSnapHelper(mSpanCount, true)
                mSnapHelper?.attachToRecyclerView(this)
            }
        }
    }
}