package com.gh.gamecenter.game.rank

import android.content.Context
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 com.gh.gamecenter.core.AppExecutor
import com.gh.gamecenter.feature.exposure.ExposureEvent
import com.gh.common.util.*
import com.gh.gamecenter.GameDetailActivity
import com.gh.gamecenter.R
import com.gh.gamecenter.adapter.viewholder.GameViewHolder
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.core.utils.*
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.feature.entity.TagStyleEntity

class RankGameItem(val rankItemUi: RankGameItemUi) {

    fun updateGameItem(
        ui: RankGameItemUi,
        gameEntity: GameEntity,
        exposureEventList: ArrayList<ExposureEvent>?,
        position: Int,
        columnName: String
    ) {

        // 为什么要用 post 呢？
        // 因为普通用 recyclerView 来实现的纵向列表用的 notifyPositionChanged 是延时更新 UI 的
        // 如果不添加延时，刚开始下载任务时可能会出现奇怪的状态 "下载中 -> 下载 -> 下载中"
        // 为了避免更改其它地方的逻辑，就这里先 post 延时处理了
        ui.root.post {
            ui.run {
                iconIv.displayGameIcon(gameEntity)
                nameTv.text = gameEntity.name

                updateTag(tagContainer, gameEntity)
                updateOrder(orderTv, position)

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

                DownloadItemUtils.setOnClickListener(
                    root.context,
                    downloadTv,
                    gameEntity,
                    position,
                    null,
                    entrance,
                    location = "专题合集-排行榜-$columnName:${gameEntity.name}",
                    traceEvent = exposureEvent,
                    clickCallback = null,
                    refreshCallback = {
                        DownloadItemUtils.updateItem(root.context, gameEntity, GameViewHolder(root).also {
                            it.gameDownloadBtn = downloadTv
                            it.gameDownloadTips = downloadTipsLottie
                            it.multiVersionDownloadTv = multiVersionDownloadTv
                        })
                    },
                    allStateClickCallback = null
                )

                DownloadItemUtils.updateItem(root.context, gameEntity, GameViewHolder(root).also {
                    it.gameDownloadBtn = downloadTv
                    it.gameDownloadTips = downloadTipsLottie
                    it.multiVersionDownloadTv = multiVersionDownloadTv
                })

                downloadTv.putWidgetBusinessName("专题合集")
            }
        }
    }

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

    private fun updateTag(tagContainer: LinearLayout, gameEntity: GameEntity) {
        tagContainer.run {
            for (i in 0 until childCount) {
                getChildAt(i).visibility = View.GONE
            }

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

    private fun updateOrder(orderTv: TextView, position: Int) {
        orderTv.run {
            visibility = View.VISIBLE
            text = (position + 1).toString()
            setPadding(0)
            when (position + 1) {
                1 -> {
                    setTextColor(com.gh.gamecenter.common.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(com.gh.gamecenter.common.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(com.gh.gamecenter.common.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(com.gh.gamecenter.common.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()
                    }
                }
            }
        }
    }

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