package com.gh.gamecenter.home.custom.adapter

import android.content.Context
import android.view.ViewGroup
import com.gh.common.util.DownloadItemUtils
import com.gh.gamecenter.adapter.viewholder.GameViewHolder
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.core.utils.StringUtils
import com.gh.gamecenter.entity.SubjectEntity
import com.gh.gamecenter.eventbus.EBDownloadStatus
import com.gh.gamecenter.eventbus.EBPackage
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.feature.exposure.ExposureEvent
import com.gh.gamecenter.game.horizontal.GameHorizontalSimpleItemViewHolder
import com.gh.gamecenter.home.custom.eventlistener.SubjectEventHelper
import com.gh.gamecenter.home.custom.model.CustomSubjectItem
import com.gh.gamecenter.home.custom.viewholder.CustomGameHorizontalItemViewHolder
import com.lightgame.download.DownloadEntity

class CustomGameHorizontalSlideAdapter(
    context: Context,
    private val eventHelper: SubjectEventHelper
) : CustomBaseChildAdapter<GameEntity, CustomGameHorizontalItemViewHolder>(context) {

    var gameName = ""
    var entrance = ""

    private var isShowFirstLine = false
    private var isShowSecondLine = false

    /**
     * 当第一屏所有的 游戏名称都只有一行的长度时，recyclerView的整体高度会被固定
     * 后续就算出现了两行长度的游戏，标题栏仍然只能显示一行
     * 所以：这里需要提前计算，当列表中出现一个需要展示两行标题高度的游戏，则所有游戏标题设为两行
     * */
    private var hasTwoLinesName = false

    private lateinit var _data: CustomSubjectItem

    private val subjectEntity: SubjectEntity
        get() = _data.data


    fun setData(data: CustomSubjectItem) {
        isShowFirstLine = false
        isShowSecondLine = false
        hasTwoLinesName = false
        _data = data
        data.data.data?.forEach {
            if (!isShowFirstLine && it.assignRemark.firstLine.isNotEmpty()) {
                isShowFirstLine = true
            }
            if (!isShowSecondLine && it.assignRemark.secondLine.isNotEmpty()) {
                isShowSecondLine = true
            }
            val gameName = it.name ?: ""
            if (!subjectEntity.showDownload && !hasTwoLinesName && gameName.length > 5) {
                hasTwoLinesName = true
            }
        }
        submitList(data.data.data)
    }

    override fun getKey(t: GameEntity): String {
        return t.id
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
        CustomGameHorizontalItemViewHolder(parent.toBinding())

    override fun onBindViewHolder(holder: CustomGameHorizontalItemViewHolder, 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.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(!subjectEntity.showDownload)
        holder.binding.simpleGameContainer.gameName.setLines(if (hasTwoLinesName) 2 else 1)
        val gameEntity = getItem(position)
        holder.binding.simpleGameContainer.run {
            gameName.setTextColor(com.gh.gamecenter.common.R.color.text_primary.toColor(root.context))
            gameIcon.displayGameIconWithIfShowSubscript(gameEntity, subjectEntity.showIndexIconSubscript)
            GameHorizontalSimpleItemViewHolder.setHorizontalNameAndGravity(gameName, gameEntity.name)
        }
        holder.bindGameHorizontalItem(gameEntity, subjectEntity, isShowFirstLine, isShowSecondLine)
        holder.itemView.setOnClickListener {
            eventHelper.navigateToGameDetailPage(position, gameEntity)
        }

        if (subjectEntity.showDownload) {
            DownloadItemUtils.setOnClickListener(
                context,
                holder.binding.simpleGameContainer.downloadBtn,
                gameEntity,
                position,
                this,
                StringUtils.buildString("(游戏-专题:", subjectEntity.name, "-列表[", (position + 1).toString(), "])"),
                location = StringUtils.buildString("游戏-专题-", subjectEntity.name, ":", gameEntity.name),
                traceEvent = gameEntity.exposureEvent
            ) {
                eventHelper.onDownloadButtonClick(position, gameEntity)
            }

            DownloadItemUtils.updateItem(
                context,
                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("横向专题列表")
        }
    }

    override fun notifyDownload(download: DownloadEntity) {
        dataList.forEachIndexed { index, item ->
            if (item.id == download.gameId) {
                notifyItemChanged(index)
            }
        }
    }

    override fun notifyDownloadDeleted(status: EBDownloadStatus) {
        notifyChildItem(status.packageName)
    }

    override fun notifyInstalled(busFour: EBPackage) {
        notifyChildItem(busFour.packageName)
    }

    private fun notifyChildItem(packageName: String) {
        dataList.forEachIndexed { position, gameEntity ->
            gameEntity.getApk().forEach { apkEntity ->
                if (apkEntity.packageName == packageName) {
                    notifyItemChanged(position)
                    return
                }
            }
        }
    }
}