package com.gh.gamecenter.game.rank

import android.content.Context
import android.graphics.Color
import android.text.TextUtils
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.view.setPadding
import androidx.recyclerview.widget.RecyclerView
import com.gh.gamecenter.core.AppExecutor
import com.gh.common.exposure.ExposureEvent
import com.gh.common.util.*
import com.gh.gamecenter.GameDetailActivity
import com.gh.gamecenter.R
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.databinding.RankGameItemBinding
import com.gh.gamecenter.entity.GameEntity
import com.gh.gamecenter.entity.TagStyleEntity
import com.gh.gamecenter.eventbus.EBDownloadStatus
import com.lightgame.adapter.BaseRecyclerAdapter
import com.lightgame.download.DownloadEntity
import java.util.*

class RankAdapter(
    context: Context,
    private var mList: List<GameEntity>,
    private var columnName: String,
    private var exposureOffset: Int,
    private var exposureEventList: ArrayList<ExposureEvent>?,
) : BaseRecyclerAdapter<RankAdapter.RankGameItemViewHolder>(context) {

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

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

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

    override fun getItemCount() = mList.size

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RankGameItemViewHolder {
        return RankGameItemViewHolder(
            RankGameItemBinding.bind(
                mLayoutInflater.inflate(
                    R.layout.rank_game_item,
                    parent,
                    false
                )
            )
        )
    }

    override fun onBindViewHolder(holder: RankGameItemViewHolder, position: Int) {
        val gameEntity = mList[position]
        holder.binding.run {
            ImageUtils.display(gameIcon, gameEntity.icon)
            ImageUtils.display(gameIconDecoratorIv, gameEntity.iconSubscript)
            gameName.text = gameEntity.name
            tagContainer.run {
                for (i in 0 until childCount) {
                    getChildAt(i).visibility = View.GONE
                }

                run outside@{
                    gameEntity.tagStyle.forEachIndexed { index, tagStyleEntity ->
                        if (index < childCount) {
                            updateGameTagView(getChildAt(index) as TextView, tagStyleEntity)
                        } else {
                            AppExecutor.lightWeightIoExecutor.execute {
                                val tagView = getGameTagView(tagStyleEntity)
                                AppExecutor.uiExecutor.execute { addView(tagView) }
                            }
                        }
                        if (index >= 2) return@outside
                    }
                }
            }

            gameOrder.run {
                visibility = View.VISIBLE
                text = (position + 1).toString()
                setPadding(0)
                when (position + 1) {
                    1 -> {
                        setTextColor(R.color.white.toColor())
                        setBackgroundResource(R.drawable.subject_top_first)
                        textSize = 9F
                        setPadding(0, 2F.dip2px(), 0, 0)
                        layoutParams?.let {
                            it.height = 16F.dip2px()
                            it.width = 16F.dip2px()
                            if (it is ViewGroup.MarginLayoutParams) {
                                it.leftMargin = 8F.dip2px()
                                it.rightMargin = 8F.dip2px()
                            }
                        }
                    }
                    2 -> {
                        setTextColor(R.color.white.toColor())
                        setBackgroundResource(R.drawable.subject_top_second)
                        textSize = 9F
                        setPadding(0, 2F.dip2px(), 0, 0)
                        layoutParams?.let {
                            it.height = 16F.dip2px()
                            it.width = 16F.dip2px()
                            if (it is ViewGroup.MarginLayoutParams) {
                                it.leftMargin = 8F.dip2px()
                                it.rightMargin = 8F.dip2px()
                            }
                        }
                    }
                    3 -> {
                        setTextColor(R.color.white.toColor())
                        setBackgroundResource(R.drawable.subject_top_third)
                        textSize = 9F
                        setPadding(0, 2F.dip2px(), 0, 0)
                        layoutParams?.let {
                            it.height = 16F.dip2px()
                            it.width = 16F.dip2px()
                            if (it is ViewGroup.MarginLayoutParams) {
                                it.leftMargin = 8F.dip2px()
                                it.rightMargin = 8F.dip2px()
                            }
                        }
                    }
                    else -> {
                        textSize = 16F
                        background = null
                        setTextColor(R.color.text_989898.toColor())
                        layoutParams?.let {
                            it.height = 24F.dip2px()
                            it.width = 24F.dip2px()
                            if (it is ViewGroup.MarginLayoutParams) {
                                it.leftMargin = 4F.dip2px()
                                it.rightMargin = 4F.dip2px()
                            } else throwExceptionInDebug()
                        }
                    }
                }
            }

            val entrance = "(专题合集-排行榜:$columnName)"
            val exposureEvent = exposureEventList?.safelyGetInRelease(exposureOffset + position)
            root.setOnClickListener {
                if (exposureEvent != null) {
                    GameDetailActivity.startGameDetailActivity(
                        mContext,
                        gameEntity.id,
                        entrance,
                        exposureEvent
                    )
                } else {
                    GameDetailActivity.startGameDetailActivity(
                        mContext,
                        gameEntity.id,
                        entrance,
                    )
                }
            }

            DownloadItemUtils.setOnClickListener(
                mContext,
                holder.binding.downloadBtn,
                gameEntity,
                position,
                this@RankAdapter,
                entrance,
                "专题合集-排行榜-$columnName:${gameEntity.name}",
                exposureEvent
            )

            DownloadItemUtils.updateDownloadButton(mContext, downloadBtn, gameEntity, false)
        }
    }

    private fun getGameTagView(tagEntity: TagStyleEntity): TextView {
        return TextView(mContext).apply {
            updateGameTagView(this, tagEntity)
        }
    }

    private fun updateGameTagView(textView: TextView, tagEntity: TagStyleEntity) {
        textView.run {
            visibility = View.VISIBLE

            if (text == tagEntity.name) return

            isSingleLine = true
            ellipsize = TextUtils.TruncateAt.END
            includeFontPadding = false
            textSize = 10F
            text = tagEntity.name
            layoutParams = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
            ).apply { rightMargin = 8F.dip2px() }
            setTextColor(("#" + if (tagEntity.column?.isNotEmpty() == true) tagEntity.column else tagEntity.color).hexStringToIntColor())
        }
    }

    fun notifyItemByDownload(download: DownloadEntity) {
        for (key in positionAndPackageMap.keys) {
            if (key.contains(download.packageName) && key.contains(download.gameId)) {
                val position = positionAndPackageMap[key]
                if (position != null && position < mList.size) {
                    mList[position].getEntryMap()[download.platform] = download
                    notifyItemChanged(position)
                }
            }
        }
    }

    fun notifyItemAndRemoveDownload(status: EBDownloadStatus) {
        for (key in positionAndPackageMap.keys) {
            if (key.contains(status.packageName) && key.contains(status.gameId)) {
                val position = positionAndPackageMap[key]
                if (position != null && position < mList.size) {
                    mList[position].getEntryMap().remove(status.platform)
                    notifyItemChanged(position)
                }
            }
        }
    }

    fun checkResetData(update: List<GameEntity>) {
        var dataIds = ""
        update.forEach { dataIds += it.id }

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

        // 重新刷新数据标识
        countAndKey = Pair(update.size, dataIds)
    }

    inner class RankGameItemViewHolder(val binding: RankGameItemBinding) : RecyclerView.ViewHolder(binding.root)
}