package com.gh.gamecenter.game.horizontal

import android.content.Context
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.gh.common.util.DataCollectionUtils
import com.gh.common.util.DownloadItemUtils
import com.gh.common.util.NewLogUtils
import com.gh.gamecenter.GameDetailActivity
import com.gh.gamecenter.R
import com.gh.gamecenter.adapter.viewholder.GameViewHolder
import com.gh.gamecenter.common.utils.dip2px
import com.gh.gamecenter.common.utils.goneIf
import com.gh.gamecenter.common.utils.toBinding
import com.gh.gamecenter.common.utils.toPx
import com.gh.gamecenter.core.utils.StringUtils
import com.gh.gamecenter.entity.SubjectEntity
import com.gh.gamecenter.feature.exposure.ExposureEvent
import com.lightgame.adapter.BaseRecyclerAdapter
import com.lightgame.download.DownloadEntity

class GameHorizontalAdapter(
    context: Context,
    private var mSubjectEntity: SubjectEntity,
    private var type: GameHorizontalListType = GameHorizontalListType.SubjectHorizontalType
) : BaseRecyclerAdapter<GameHorizontalItemViewHolder>(context) {

    var gameName = ""
    var gameId = ""
    var entrance = ""
    var path = ""
    var exposureEventList: ArrayList<ExposureEvent>? = null
    private val mDefaultHorizontalPadding by lazy { R.dimen.game_detail_item_horizontal_padding.toPx() }

    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(parent.toBinding())

    override fun getItemCount(): Int {
        val size = mSubjectEntity.data!!.size - getIndex()
        return if (type == GameHorizontalListType.GameDetailHorizontalType) {
            size
        } else {
            when {
                size < 4 -> size
                size < 8 -> 4
                else -> 8
            }
        }

    }

    override fun onBindViewHolder(holder: GameHorizontalItemViewHolder, position: Int) {
        val params = holder.binding.root.layoutParams as RecyclerView.LayoutParams
        params.width =
            if (gameName.isNotBlank()) RecyclerView.LayoutParams.WRAP_CONTENT else RecyclerView.LayoutParams.MATCH_PARENT
        if (type == GameHorizontalListType.GameDetailHorizontalType) {
            params.leftMargin = if (position == 0) mDefaultHorizontalPadding else 8F.dip2px()
            params.rightMargin = if (position == itemCount - 1) mDefaultHorizontalPadding else 0F.dip2px()
        }
        holder.binding.root.layoutParams = params

        val gameEntity = mSubjectEntity.data!![position + getIndex()]
        holder.binding.simpleGameContainer.run {
            gameIcon.displayGameIcon(gameEntity)
            GameHorizontalSimpleItemViewHolder.setHorizontalNameAndGravity(gameName, gameEntity.name)
            downloadBtn.goneIf(!mSubjectEntity.showDownload)
            gameName.maxLines = if (mSubjectEntity.showDownload) 1 else 2
        }
        holder.bindGameHorizontalItem(gameEntity, mSubjectEntity)
        val entranceResult: String
        val locationResult: String
        if (type == GameHorizontalListType.GameDetailHorizontalType) {
            entranceResult = StringUtils.buildString(
                entrance,
                "+(",
                "游戏详情",
                "[",
                gameName,
                "]:${path}[",
                (position + 1).toString(),
                "])"
            )
            locationResult = StringUtils.buildString("游戏详情-", gameName, "-${path}", ":", gameEntity.name)
        } else {
            entranceResult =
                StringUtils.buildString("(游戏-专题:", mSubjectEntity.name, "-列表[", (position + 1).toString(), "])")
            locationResult = StringUtils.buildString("游戏-专题-", mSubjectEntity.name, ":", gameEntity.name)
        }
        holder.itemView.setOnClickListener {
            if (type == GameHorizontalListType.GameDetailHorizontalType) {
                DataCollectionUtils.uploadClick(mContext, path, "游戏详情", gameEntity.name)
                NewLogUtils.logGameDetailPopularClick(gameName, gameId, "game", gameEntity.name ?: "")
            }

            GameDetailActivity.startGameDetailActivity(
                mContext,
                gameEntity.id,
                entranceResult,
                exposureEventList?.get(position)
            )
        }

        if (mSubjectEntity.showDownload && type != GameHorizontalListType.GameDetailHorizontalType) {
            DownloadItemUtils.setOnClickListener(
                mContext,
                holder.binding.simpleGameContainer.downloadBtn,
                gameEntity,
                position,
                this,
                entranceResult,
                locationResult,
                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
                },
                true
            )
        }
    }

    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()
        }

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

sealed class GameHorizontalListType {
    object GameDetailHorizontalType : GameHorizontalListType()
    object SubjectHorizontalType : GameHorizontalListType()
}