package com.gh.gamecenter.game.horizontal

import android.content.Context
import android.view.ViewGroup
import com.gh.gamecenter.feature.exposure.ExposureEvent
import com.gh.common.util.DownloadItemUtils
import com.gh.gamecenter.GameDetailActivity
import com.gh.gamecenter.adapter.viewholder.GameViewHolder
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.core.utils.*
import com.gh.gamecenter.databinding.GameHorizontalItemBinding
import com.gh.gamecenter.entity.SubjectEntity
import com.gh.gamecenter.feature.minigame.MiniGameItemHelper
import com.lightgame.adapter.BaseRecyclerAdapter
import com.lightgame.download.DownloadEntity

class GameHorizontalSlideAdapter(
    context: Context,
    private var mSubjectEntity: SubjectEntity
) : BaseRecyclerAdapter<GameHorizontalItemViewHolder>(context) {

    var gameName = ""
    var entrance = ""
    var exposureEventList: ArrayList<ExposureEvent>? = null

    private var countAndKey: Pair<Int, String>? = null

    init {
        var dataIds = ""
        mSubjectEntity.data?.forEach {
            dataIds += it.id
        }
        if (dataIds.isNotEmpty()) countAndKey = Pair(mSubjectEntity.data?.size ?: 0, dataIds)
    }

    fun getIndex(): Int {
        if (mSubjectEntity.data!!.isNotEmpty()) {
            return if (mSubjectEntity.data!![0].image.isNullOrEmpty()) 0 else 1
        }
        return 0
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): GameHorizontalItemViewHolder {
        val binding: GameHorizontalItemBinding = parent.toBinding()
        return GameHorizontalItemViewHolder(binding)
    }

    override fun getItemCount(): Int {
        return mSubjectEntity.data!!.size - getIndex()
    }

    override fun onBindViewHolder(holder: GameHorizontalItemViewHolder, position: Int) {
        holder.binding.remarkLine.setBackgroundColor(com.gh.gamecenter.common.R.color.btn_gray_light.toColor(holder.binding.root.context))
        holder.binding.secondRemark.setTextColor(com.gh.gamecenter.common.R.color.text_tertiary.toColor(holder.binding.root.context))
        holder.binding.root.setPadding(0, 8F.dip2px(), 0, 8F.dip2px())
        holder.binding.simpleGameContainer.root.setPadding(8F.dip2px(), 0, 8F.dip2px(), 0)
        holder.binding.root.layoutParams =
            ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)
        holder.binding.simpleGameContainer.downloadBtn.goneIf(!mSubjectEntity.showDownload)
        holder.binding.simpleGameContainer.gameName.maxLines = if (mSubjectEntity.showDownload) 1 else 2

        val gameEntity = mSubjectEntity.data!![position + getIndex()]
        holder.binding.simpleGameContainer.run {
            gameName.setTextColor(com.gh.gamecenter.common.R.color.text_primary.toColor(root.context))
            gameIcon.displayGameIcon(gameEntity)
            GameHorizontalSimpleItemViewHolder.setHorizontalNameAndGravity(gameName, gameEntity.name)
        }
        holder.bindGameHorizontalItem(gameEntity, mSubjectEntity)
        holder.itemView.setOnClickListener {
            if (gameEntity.isMiniGame()) {
                MiniGameItemHelper.launchMiniGame(gameEntity)
            } else {
                val exposureEvent = exposureEventList?.safelyGetInRelease(position)
                if (exposureEvent != null) {
                    GameDetailActivity.startGameDetailActivity(
                        mContext,
                        gameEntity.id,
                        StringUtils.buildString("(游戏-专题:", mSubjectEntity.name, "-列表[", (position + 1).toString(), "])"),
                        traceEvent = exposureEvent
                    )
                } else {
                    GameDetailActivity.startGameDetailActivity(
                        mContext, gameEntity.id,
                        StringUtils.buildString("(游戏-专题:", mSubjectEntity.name, "-列表[", (position + 1).toString(), "])")
                    )
                }
            }
        }

        if (mSubjectEntity.showDownload) {
            DownloadItemUtils.setOnClickListener(
                mContext,
                holder.binding.simpleGameContainer.downloadBtn,
                gameEntity,
                position,
                this,
                StringUtils.buildString("(游戏-专题:", mSubjectEntity.name, "-列表[", (position + 1).toString(), "])"),
                location = StringUtils.buildString("游戏-专题-", mSubjectEntity.name, ":", gameEntity.name),
                traceEvent = if (position < (exposureEventList?.size ?: 0)) exposureEventList!![position] else null
            )

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

            holder.binding.simpleGameContainer.downloadBtn.putWidgetBusinessName("横向专题列表")
        }
    }

    fun notifyItemByDownload(downloadEntity: DownloadEntity?) {
        if (downloadEntity == null) {
            notifyDataSetChanged()
        } else {
            mSubjectEntity.data?.forEachIndexed { position, gameEntity ->
                if (downloadEntity.gameId == gameEntity.id) {
                    notifyItemChanged(position - getIndex())
                    return
                }
            }
        }
    }

    fun notifyChildItem(packageName: String) {
        mSubjectEntity.data?.forEachIndexed { position, gameEntity ->
            gameEntity.getApk().forEach { apkEntity ->
                if (apkEntity.packageName == packageName) {
                    notifyItemChanged(position - getIndex())
                    return
                }
            }
        }
    }

    // notifyDataSetChanged 会出现页面抖动情况
    fun checkResetData(subjectEntity: SubjectEntity) {
        var dataIds = ""
        subjectEntity.data?.forEach {
            dataIds += it.id
        }

        mSubjectEntity = subjectEntity
        if (countAndKey?.first == subjectEntity.data?.size && countAndKey?.second != dataIds) { // 数量不变,内容发生改变
            notifyItemRangeChanged(0, itemCount)
        } else if (countAndKey?.first != subjectEntity.data?.size) { // 数量发生改变
            notifyDataSetChanged()
        } else {
            notifyItemRangeChanged(0, itemCount)
        }

        // 重新刷新数据标识
        countAndKey = Pair(subjectEntity.data?.size ?: 0, dataIds)
    }
}