package com.gh.gamecenter.game.gallery

import android.content.Context
import android.view.ViewGroup
import androidx.activity.ComponentActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.gh.gamecenter.GameDetailActivity
import com.gh.gamecenter.common.base.BaseRecyclerViewHolder
import com.gh.gamecenter.common.exposure.ExposureSource
import com.gh.gamecenter.common.utils.toBinding
import com.gh.gamecenter.common.utils.toColor
import com.gh.gamecenter.core.runOnIoThread
import com.gh.gamecenter.databinding.GameGallerySlideItemBinding
import com.gh.gamecenter.databinding.ItemWithinGameGallerySlideBinding
import com.gh.gamecenter.entity.SubjectEntity
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.feature.exposure.ExposureEvent
import com.gh.gamecenter.feature.minigame.MiniGameItemHelper
import com.lightgame.adapter.BaseRecyclerAdapter

/**
 * 游戏专题-图集滚动
 */
class GameGallerySlideViewHolder(val binding: GameGallerySlideItemBinding) : BaseRecyclerViewHolder<Any>(binding.root) {

    private var mCachedSubject: SubjectEntity? = null
    private var mRecyclerViewList: ArrayList<RecyclerView>? = null

    private var mEntrance = ""
    private var mExposureClosure: ((ExposureEvent) -> Unit)? = null
    private var mBasicExposureSource: List<ExposureSource>? = null

    fun bindView(
        subjectEntity: SubjectEntity,
        basicExposureSource: List<ExposureSource>,
        entrance: String,
        exposureClosure: (ExposureEvent) -> Unit
    ) {
        if (subjectEntity.data == null) return

        resumeScrolling()

        if (subjectEntity == mCachedSubject) return

        mEntrance = entrance
        mExposureClosure = exposureClosure
        mBasicExposureSource = basicExposureSource

        mCachedSubject = subjectEntity
        mRecyclerViewList =
            arrayListOf(binding.firstRecyclerView, binding.secondRecyclerView, binding.thirdRecyclerView)

        for ((index, recyclerView) in mRecyclerViewList!!.withIndex()) {
            recyclerView.layoutManager = LinearLayoutManager(binding.root.context, RecyclerView.HORIZONTAL, false)
            recyclerView.adapter = GameGallerySlideAdapter(binding.root.context, getDividedGameList()[index])
            recyclerView.isNestedScrollingEnabled = false
        }

        binding.container.resumeScrolling()
        binding.container.setLifeCycleOwner((binding.root.context as ComponentActivity).lifecycle)
        binding.cardView.setCardBackgroundColor(com.gh.gamecenter.common.R.color.text_FAFAFA.toColor(binding.root.context))
    }

    /**
     * 获取分割好的游戏列表数据
     */
    private fun getDividedGameList(): ArrayList<ArrayList<GameEntity>> {
        val containerList = arrayListOf<ArrayList<GameEntity>>()
        val gameDataList = mCachedSubject!!.data!!
        val gameListSize = gameDataList.size

        // 分割大小
        val splitSize = gameDataList.size / 3

        if (splitSize > 1) {
            containerList.add(ArrayList(gameDataList.subList(0, splitSize)))
            containerList.add(ArrayList(gameDataList.subList(splitSize, splitSize * 2)))
            containerList.add(ArrayList(gameDataList.subList(splitSize * 2, gameListSize)))
        } else if (splitSize == 1) {
            containerList.add(ArrayList(gameDataList.subList(0, 1)))
            containerList.add(ArrayList(gameDataList.subList(1, 2)))
            containerList.add(ArrayList(gameDataList.subList(2, 3)))
        } else {
            val tempGameList = arrayListOf<GameEntity>()
            if (gameListSize != 0) {
                tempGameList.add(gameDataList.first())
            }
            containerList.add(tempGameList)
            containerList.add(tempGameList)
            containerList.add(tempGameList)
        }
        return containerList
    }

    fun resumeScrolling() {
        binding.container.resumeScrolling()
    }

    fun pauseScrolling() {
        binding.container.pauseScrolling()
    }

    inner class GameGallerySlideAdapter(context: Context, var gameList: ArrayList<GameEntity>) :
        BaseRecyclerAdapter<GameGallerySlideAdapter.GameGallerySlideItemViewHolder>(context) {

        override fun getItemCount() = Int.MAX_VALUE

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): GameGallerySlideItemViewHolder {
            return GameGallerySlideItemViewHolder(parent.toBinding())
        }

        override fun onBindViewHolder(holder: GameGallerySlideItemViewHolder, position: Int) {
            if (gameList.isEmpty()) return

            val gameEntity = gameList[position % gameList.size]

            runOnIoThread(true) {
                val exposureEvent = ExposureEvent.createEventWithSourceConcat(
                    gameEntity,
                    mBasicExposureSource!!,
                    listOf(ExposureSource("专题", "${mCachedSubject?.name}-图集滚动"))
                )

                mExposureClosure?.invoke(exposureEvent)

                gameEntity.exposureEvent = exposureEvent
            }
            holder.bindView(gameEntity)
        }

        inner class GameGallerySlideItemViewHolder(val binding: ItemWithinGameGallerySlideBinding) :
            BaseRecyclerViewHolder<Any>(binding.root) {
            fun bindView(gameEntity: GameEntity) {
                binding.iconIv.displayGameIcon(gameEntity)
                binding.iconIv.setOnClickListener {
                    if (gameEntity.isMiniGame()) {
                        MiniGameItemHelper.launchMiniGame(gameEntity)
                    } else {
                        GameDetailActivity.startGameDetailActivity(
                            binding.root.context,
                            gameEntity.id,
                            mEntrance,
                            gameEntity.exposureEvent
                        )
                    }
                }
            }
        }

    }

}