package com.gh.gamecenter.home.gamecollection.slide

import android.content.Context
import android.util.SparseArray
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.content.res.AppCompatResources
import androidx.core.os.trace
import androidx.core.util.forEach
import androidx.recyclerview.widget.RecyclerView
import com.gh.common.util.DirectUtils
import com.gh.common.util.DownloadItemUtils
import com.gh.common.util.NewFlatLogUtils
import com.gh.gamecenter.GameDetailActivity
import com.gh.gamecenter.R
import com.gh.gamecenter.adapter.viewholder.GameViewHolder
import com.gh.gamecenter.common.base.BaseRecyclerViewHolder
import com.gh.gamecenter.common.base.activity.BaseActivity
import com.gh.gamecenter.common.json.json
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.common.view.AsyncCell
import com.gh.gamecenter.databinding.ItemHomeGameCollectionBigSlideCardBinding
import com.gh.gamecenter.databinding.ItemHomeGameCollectionBigSlideCardGameBinding
import com.gh.gamecenter.databinding.ItemHomeGameCollectionSmallSlideCardBinding
import com.gh.gamecenter.entity.GameListCollection
import com.gh.gamecenter.entity.HomeGameCollectionEntity
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.gamecollection.square.GameCollectionListItemData
import com.lightgame.adapter.BaseRecyclerAdapter
import com.lightgame.download.DownloadEntity

class HomeGameCollectionSlideAdapter(
    context: Context,
    private var mIsBigSlide: Boolean,
    private val mEntrance: String,
    private var mGameListCollection: GameListCollection,
    private val mBlockId: String = "",
    private val mBlockName: String = ""
) : BaseRecyclerAdapter<RecyclerView.ViewHolder>(context) {

    private val mBigSlideViewHolderList = SparseArray<HomeGameCollectionBigSlideCardViewHolder>()

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder =
        if (mIsBigSlide) {
            HomeGameCollectionBigSlideCardViewHolder(
                HomeGameCollectionBigSlideCardCell(mContext).apply { inflate() }
            ).apply {
                mBigSlideViewHolderList.put(mBigSlideViewHolderList.size(), this)
            }
        } else {
            HomeGameCollectionSmallSlideCardViewHolder(parent.toBinding())
        }

    override fun getItemCount(): Int = mGameListCollection.gameCollectionItemDataList.size

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        val gameCollectionItemData = mGameListCollection.gameCollectionItemDataList.safelyGetInRelease(position)
        val entity = gameCollectionItemData?.homeGameCollectionItem
        val games = entity?.games ?: arrayListOf()

        // 大卡片
        if (holder is HomeGameCollectionBigSlideCardViewHolder) {
            gameCollectionItemData?.let { holder.initPackageAndPosition(it) }
            (holder.itemView as HomeGameCollectionBigSlideCardCell).bindWhenInflated {
                (holder.itemView as HomeGameCollectionBigSlideCardCell).binding?.run {
                    val params = root.layoutParams as ViewGroup.MarginLayoutParams
                    params.leftMargin = if (position == 0) 0 else (-24F).dip2px()

                    ImageUtils.display(coverImage, entity?.cover)
                    ImageUtils.display(userIv, entity?.user?.icon)
                    titleTv.text = entity?.title
                    userTv.text = entity?.user?.name
                    listOf(userIv, userTv).forEach {
                        it.setOnClickListener {
                            NewFlatLogUtils.logGameListCollectionClick(
                                mEntrance,
                                mBlockName,
                                mBlockId,
                                mGameListCollection.name,
                                mGameListCollection.id,
                                "个人主页"
                            )
                            SensorsBridge.trackEvent("GameListCollectionClick", json {
                                "location" to if (mEntrance.contains("首页")) "首页" else if (mEntrance.contains("版块")) "版块" else ""
                                "block_name" to mBlockName
                                "block_id" to mBlockId
                                "game_list_collection_name" to mGameListCollection.name
                                "game_list_collection_id" to mGameListCollection.id
                                "text" to "个人主页"
                                "mongold_id" to entity?.user?.id
                            })
                            DirectUtils.directToHomeActivity(mContext, entity?.user?.id, 0, mEntrance, "游戏单合集")
                        }
                    }

                    listOf(gameItem1, gameItem2, gameItem3).forEachIndexed { index, binding ->
                        binding.root.goneIf(games.size < index + 1) {
                            val gameEntity = games[index]
                            holder.updateGameItem(binding, gameEntity)
                        }
                    }

                    entity?.count?.let { moreTv.text = "查看全部${it.game}款游戏" }
                    root.setOnClickListener {
                        NewFlatLogUtils.logGameListCollectionClick(
                            mEntrance,
                            mBlockName,
                            mBlockId,
                            mGameListCollection.name,
                            mGameListCollection.id,
                            "游戏单"
                        )
                        SensorsBridge.trackEvent("GameListCollectionClick", json {
                            "location" to if (mEntrance.contains("首页")) "首页" else if (mEntrance.contains("版块")) "版块" else ""
                            "block_name" to mBlockName
                            "block_id" to mBlockId
                            "game_list_collection_name" to mGameListCollection.name
                            "game_list_collection_id" to mGameListCollection.id
                            "text" to "游戏单"
                            "game_collect_title" to entity?.title
                            "game_collect_id" to entity?.id
                        })
                        DirectUtils.directToGameCollectionDetail(
                            it.context,
                            entity?.id ?: "",
                            mEntrance,
                            "游戏单合集",
                            gameCollectionItemData?.exposureEvent
                        )
                    }
                }
            }
        }

        // 小卡片
        if (holder is HomeGameCollectionSmallSlideCardViewHolder) {
            holder.binding.run {
                val params = root.layoutParams as ViewGroup.MarginLayoutParams
                params.leftMargin = if (position == 0) 0 else (-24F).dip2px()

                container.background = R.drawable.bg_item_game_test_v2.toDrawable(mContext)
                titleTv.setTextColor(com.gh.gamecenter.common.R.color.text_primary.toColor(mContext))
                userTv.setTextColor(com.gh.gamecenter.common.R.color.text_secondary.toColor(mContext))

                ImageUtils.display(coverImage, entity?.cover)
                ImageUtils.display(userIv, entity?.user?.icon)
                titleTv.text = entity?.title
                userTv.text = entity?.user?.name
                gameCountTv.goneIf(games.isEmpty())
                entity?.count?.let { gameCountTv.text = "+${it.game - games.size}" }
                listOf(userIv, userTv).forEach {
                    it.setOnClickListener {
                        NewFlatLogUtils.logGameListCollectionClick(
                            mEntrance,
                            mBlockName,
                            mBlockId,
                            mGameListCollection.name,
                            mGameListCollection.id,
                            "个人主页"
                        )
                        SensorsBridge.trackEvent("GameListCollectionClick", json {
                            "location" to if (mEntrance.contains("首页")) "首页" else if (mEntrance.contains("版块")) "版块" else ""
                            "block_name" to mBlockName
                            "block_id" to mBlockId
                            "game_list_collection_name" to mGameListCollection.name
                            "game_list_collection_id" to mGameListCollection.id
                            "text" to "个人主页"
                            "mongold_id" to entity?.user?.id
                        })
                        DirectUtils.directToHomeActivity(mContext, entity?.user?.id, 0, mEntrance, "游戏单合集")
                    }
                }
                listOf(gameIcon1, gameIcon2, gameIcon3).forEachIndexed { index, gameIcon ->
                    gameIcon.goneIf(games.size < index + 1) {
                        val gameEntity = games[index]
                        gameIcon.displayGameIcon(gameEntity)
                        gameIcon.setBorderColor(com.gh.gamecenter.common.R.color.ui_surface)
                        gameIcon.setOnClickListener {
                            NewFlatLogUtils.logGameListCollectionClick(
                                mEntrance,
                                mBlockName,
                                mBlockId,
                                mGameListCollection.name,
                                mGameListCollection.id,
                                "游戏"
                            )
                            SensorsBridge.trackEvent("GameListCollectionClick", json {
                                "location" to if (mEntrance.contains("首页")) "首页" else if (mEntrance.contains("版块")) "版块" else ""
                                "block_name" to mBlockName
                                "block_id" to mBlockId
                                "game_list_collection_name" to mGameListCollection.name
                                "game_list_collection_id" to mGameListCollection.id
                                "text" to "游戏"
                                "game_name" to gameEntity.name
                                "game_id" to gameEntity.id
                            })
                            GameDetailActivity.startGameDetailActivity(
                                mContext,
                                gameEntity.id,
                                BaseActivity.mergeEntranceAndPath(mEntrance, "游戏单合集"),
                                gameEntity.exposureEvent
                            )
                        }
                    }
                }
                root.setOnClickListener {
                    NewFlatLogUtils.logGameListCollectionClick(
                        mEntrance,
                        mBlockName,
                        mBlockId,
                        mGameListCollection.name,
                        mGameListCollection.id,
                        "游戏单"
                    )
                    SensorsBridge.trackEvent("GameListCollectionClick", json {
                        "location" to if (mEntrance.contains("首页")) "首页" else if (mEntrance.contains("版块")) "版块" else ""
                        "block_name" to mBlockName
                        "block_id" to mBlockId
                        "game_list_collection_name" to mGameListCollection.name
                        "game_list_collection_id" to mGameListCollection.id
                        "text" to "游戏单"
                        "game_collect_title" to entity?.title
                        "game_collect_id" to entity?.id
                    })
                    DirectUtils.directToGameCollectionDetail(
                        it.context,
                        entity?.id ?: "",
                        mEntrance,
                        "游戏单合集",
                        gameCollectionItemData?.exposureEvent
                    )
                }
            }
        }
    }

    fun checkResetData(updateGameListCollection: GameListCollection, isBigSlide: Boolean) {
        val updateId = updateGameListCollection.id
        val id = mGameListCollection.id
        val updateStyle = updateGameListCollection.style
        val style = mGameListCollection.style
        mGameListCollection = updateGameListCollection

        if (updateId != id || updateStyle != style || mBigSlideViewHolderList.size() != updateGameListCollection.gameCollectionItemDataList.size) {
            notifyDataSetChanged()
        } else {
            if (isBigSlide) {
                mBigSlideViewHolderList.forEach { position, viewHolder ->
                    viewHolder.checkResetData(
                        updateGameListCollection.gameCollectionItemDataList.safelyGetInRelease(
                            position
                        )
                    )
                    (viewHolder.itemView as HomeGameCollectionBigSlideCardCell).binding?.run {
                        container.background = R.drawable.bg_item_game_test_v2.toDrawable(mContext)
                        divider.setBackgroundColor(com.gh.gamecenter.common.R.color.ui_divider.toColor(mContext))
                        moreTv.setTextColor(com.gh.gamecenter.common.R.color.text_tertiary.toColor(mContext))
                        moreTv.setDrawableEnd(
                            AppCompatResources.getDrawable(
                                mContext,
                                R.drawable.ic_home_game_collection_slide_jump
                            )
                        )
                        listOf(gameItem1, gameItem2, gameItem3).forEach { binding ->
                            binding.gameIconIv.setBorderColor(com.gh.gamecenter.common.R.color.resource_border)
                            binding.gameNameTv.setTextColor(com.gh.gamecenter.common.R.color.text_primary.toColor(mContext))
                            binding.gameDesTv.setTextColor(com.gh.gamecenter.common.R.color.text_tertiary.toColor(mContext))
                        }
                    }
                }
            } else {
                notifyItemRangeChanged(0, itemCount)
            }
        }
    }

    fun notifyItemByDownload(downloadEntity: DownloadEntity) {
        mBigSlideViewHolderList.forEach { _, it ->
            it.notifyItemByDownload(downloadEntity)
        }
    }

    fun notifyChildItem() {
        mBigSlideViewHolderList.forEach { _, it ->
            it.checkResetData()
        }
    }

    private inner class HomeGameCollectionBigSlideCardCell(context: Context) : AsyncCell(context) {
        var binding: ItemHomeGameCollectionBigSlideCardBinding? = null

        override val layoutId = R.layout.item_home_game_collection_big_slide_card
        override val switchToWrapContentWhenInflated = true
        override fun createDataBindingView(view: View): View? {
            binding = ItemHomeGameCollectionBigSlideCardBinding.bind(view)
            return view.rootView
        }
    }

    inner class HomeGameCollectionBigSlideCardViewHolder(view: View) : BaseRecyclerViewHolder<Any>(view) {

        private var countAndKey: Pair<Int, String>? = null
        val positionAndPackageMap = HashMap<String, Int>()
        private var mGameCollectionListItemData: GameCollectionListItemData? = null
        private var mGameCollectionEntity: HomeGameCollectionEntity? = null

        fun initPackageAndPosition(gameCollectionListItemData: GameCollectionListItemData) {
            mGameCollectionListItemData = gameCollectionListItemData
            mGameCollectionEntity = gameCollectionListItemData.homeGameCollectionItem

            val dataList = mGameCollectionEntity?.games ?: return

            var dataIds = ""
            dataList.forEach {
                dataIds += it.id
            }
            if (dataIds.isNotEmpty()) countAndKey = Pair(dataList.size, dataIds)

            positionAndPackageMap.clear()
            // 记录游戏位置
            for (i in dataList.indices) {
                val gameEntity = dataList[i]
                var packages = gameEntity.id
                for (apkEntity in gameEntity.getApk()) {
                    packages += apkEntity.packageName
                }
                positionAndPackageMap[packages + i] = i
            }
        }

        fun notifyItemByDownload(download: DownloadEntity) {
            val dataList = mGameCollectionEntity?.games ?: return

            for (key in positionAndPackageMap.keys) {
                if (key.contains(download.packageName) && key.contains(download.gameId)) {
                    val position = positionAndPackageMap[key]
                    if (position != null && position < dataList.size) {
                        dataList[position].getEntryMap()[download.platform] = download
                        (itemView as HomeGameCollectionBigSlideCardCell).binding?.run {

                            when (position) {
                                0 -> updateGameItem(gameItem1, dataList[position])
                                1 -> updateGameItem(gameItem2, dataList[position])
                                2 -> updateGameItem(gameItem3, dataList[position])
                            }
                        }
                    }
                }
            }
        }

        fun checkResetData(gameCollectionListItemData: GameCollectionListItemData? = mGameCollectionListItemData) {
            gameCollectionListItemData ?: return

            var dataIds = ""
            mGameCollectionListItemData = gameCollectionListItemData
            mGameCollectionEntity = gameCollectionListItemData.homeGameCollectionItem
            mGameCollectionEntity?.games?.forEach { dataIds += it.id }

            val games = mGameCollectionEntity?.games ?: arrayListOf()
            (itemView as HomeGameCollectionBigSlideCardCell).binding?.run {
                listOf(gameItem1, gameItem2, gameItem3).forEachIndexed { index, binding ->
                    binding.root.goneIf(games.size < index + 1) {
                        val gameEntity = games[index]
                        updateGameItem(binding, gameEntity)
                    }
                }
            }

            // 重新刷新数据标识
            countAndKey = Pair(mGameCollectionEntity?.games!!.size, dataIds)
        }

        fun updateGameItem(
            binding: ItemHomeGameCollectionBigSlideCardGameBinding,
            gameEntity: GameEntity
        ) {
            binding.root.visibility = View.VISIBLE

            binding.gameIconIv.displayGameIcon(gameEntity)
            binding.gameNameTv.text = gameEntity.name
            binding.gameDesTv.text = gameEntity.brief

            DownloadItemUtils.setOnClickListener(
                mContext,
                binding.downloadBtn,
                gameEntity,
                position,
                null,
                mEntrance,
                location = "游戏单合集",
                traceEvent = gameEntity.exposureEvent,
                clickCallback = null,
                refreshCallback = {
                    DownloadItemUtils.updateItem(
                        mContext,
                        gameEntity,
                        GameViewHolder(binding.root).apply {
                            gameDownloadBtn = binding.downloadBtn
                            gameDownloadTips = binding.downloadTipsLottie
                            multiVersionDownloadTv = binding.multiVersionDownloadTv
                        }
                    )
                },
                allStateClickCallback = null
            )

            DownloadItemUtils.updateItem(
                mContext,
                gameEntity,
                GameViewHolder(binding.root).apply {
                    gameDownloadBtn = binding.downloadBtn
                    gameDownloadTips = binding.downloadTipsLottie
                    multiVersionDownloadTv = binding.multiVersionDownloadTv
                }
            )

            binding.root.setOnClickListener {
                NewFlatLogUtils.logGameListCollectionClick(
                    mEntrance,
                    mBlockName,
                    mBlockId,
                    mGameListCollection.name,
                    mGameListCollection.id,
                    "游戏"
                )
                SensorsBridge.trackEvent("GameListCollectionClick", json {
                    "location" to if (mEntrance.contains("首页")) "首页" else if (mEntrance.contains("版块")) "版块" else ""
                    "block_name" to mBlockName
                    "block_id" to mBlockId
                    "game_list_collection_name" to mGameListCollection.name
                    "game_list_collection_id" to mGameListCollection.id
                    "text" to "游戏"
                    "game_name" to gameEntity.name
                    "game_id" to gameEntity.id
                })
                GameDetailActivity.startGameDetailActivity(
                    mContext,
                    gameEntity.id,
                    BaseActivity.mergeEntranceAndPath(mEntrance, "游戏单合集"),
                    gameEntity.exposureEvent
                )
            }
        }
    }

    class HomeGameCollectionSmallSlideCardViewHolder(val binding: ItemHomeGameCollectionSmallSlideCardBinding) :
        RecyclerView.ViewHolder(binding.root)
}