package com.gh.gamecenter.feature.game

import android.graphics.Color
import android.graphics.drawable.GradientDrawable
import android.text.TextUtils
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.view.isVisible
import com.therouter.TheRouter
import com.gh.gamecenter.common.base.BaseRecyclerViewHolder
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.common.view.DrawableView
import com.gh.gamecenter.feature.R
import com.gh.gamecenter.feature.databinding.GameItemBinding
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.feature.exposure.ExposureEvent
import com.gh.gamecenter.feature.exposure.IExposureProvider
import com.gh.gamecenter.feature.minigame.MiniGameItemHelper
import com.gh.gamecenter.feature.provider.IBindingAdaptersProvider

/**
 * 正常游戏
 */
class GameItemViewHolder(var binding: GameItemBinding) : BaseRecyclerViewHolder<Any>(binding.root), IExposureProvider {

    private var boundedGameEntity: GameEntity? = null

    fun initServerType(gameEntity: GameEntity) {
        initServerType(binding.gameName, binding.gameKaifuType, gameEntity)
    }

    fun bindGameItem(
        entity: GameEntity,
        briefStyle: String = "",
        isShowPlatform: Boolean = false,
        forceShowSubtitle: Boolean = false
    ) {
        boundedGameEntity = entity
        binding.run {
            bindCommonItem(entity, isShowPlatform)
            gameIconView.displayGameIcon(entity)
            initGameSubtitleAndAdLabel(
                entity,
                gameSubtitleTv,
                gameNameContainer,
                gameName,
                entity.adIconActive,
                adLabelTv,
                forceShowSubtitle
            )
        }
    }

    /**
     * 由 bindGameItem 方法复制过来
     * 只在专题详情页里面调用
     * @see bindGameItem
     */
    fun bindGameItemOnSubjectDetail(
        entity: GameEntity,
        showSubTitle: Boolean,
        showIconSubScript: Boolean
    ) {
        boundedGameEntity = entity
        binding.run {
            bindCommonItem(entity, false)
            gameIconView.displayGameIconWithIfShowSubscript(entity, showIconSubScript)
            initGameSubtitleAndAdLabelOnGameSubject(
                entity,
                gameSubtitleTv,
                gameNameContainer,
                gameName,
                entity.adIconActive,
                adLabelTv,
                canShowTitle = showSubTitle
            )
        }
    }

    private fun bindCommonItem(entity: GameEntity, isShowPlatform: Boolean) {
        boundedGameEntity = entity
        binding.run {
            root.background = com.gh.gamecenter.common.R.drawable.reuse_listview_item_style.toDrawable(root.context)
            selectIv.setImageDrawable(DrawableView.getCheckSelectorDrawable(root.context))
            gameKaifuType.setBackgroundColor(com.gh.gamecenter.common.R.color.primary_theme.toColor(root.context))
            gameName.setTextColor(com.gh.gamecenter.common.R.color.text_primary.toColor(root.context))
            gameDes.setTextColor(com.gh.gamecenter.common.R.color.text_tertiary.toColor(root.context))
            recommendStarPref.setTextColor(com.gh.gamecenter.common.R.color.text_tertiary.toColor(root.context))

            val provider = TheRouter.get(IBindingAdaptersProvider::class.java)
            provider?.setGameName(gameName, entity, isShowPlatform)
            provider?.setGameTagsWithSellingPoints(
                labelList,
                layoutSellingPoints,
                entity,
                entity.subjectData?.tag ?: ""
            )
            provider?.setGameDescription(gameDes, entity.subjectData?.briefStyle ?: "", entity)
            gameRating.textSize = if (entity.commentCount > 3) 12F else 10F
            gameRating.setDrawableStart(if (entity.commentCount > 3) R.drawable.game_horizontal_rating.toDrawable() else null)
            gameRating.setPadding(0, 0, if (entity.commentCount > 3) 8F.dip2px() else 0, 0)
            gameRating.text = if (entity.commentCount > 3) {
                if (entity.star == 10.0F) "10" else entity.star.toString()
            } else ""
            gameRating.setTextColor(
                if (entity.commentCount > 3) com.gh.gamecenter.common.R.color.text_theme.toColor(root.context) else com.gh.gamecenter.common.R.color.primary_theme.toColor(
                    root.context
                )
            )
            recommendStar.rating = entity.recommendStar.toFloat()
            MiniGameItemHelper.setMiniGameUsage(gamePlayCount, entity)

        }
    }

    companion object {
        const val ADVANCED_DOWNLOAD_WIDTH = 34F
        const val SUBTITLE_MIN_WIDTH = 24F
        const val SUBTITLE_MARGIN_START = 4F
        const val AD_LABEL_WITH_MARGIN_WIDTH = 25F
        fun initServerType(gameNameTv: TextView, serverTypeTv: TextView, gameEntity: GameEntity) {
            val serverLabel = gameEntity.serverLabel
            when {
                gameEntity.test != null -> {
                    serverTypeTv.visibility = View.GONE
                    serverTypeTv.text = ""
                }

                serverLabel != null && !gameEntity.advanceDownload -> {
                    serverTypeTv.visibility = View.VISIBLE
                    serverTypeTv.text = serverLabel.value
                    serverTypeTv.setTextColor(Color.WHITE)
                    if (gameEntity.isUseDefaultServerStyle()) {
                        serverTypeTv.background =
                            R.drawable.server_label_default_bg.toDrawable(gameNameTv.context)
                        serverTypeTv.setTextColor(com.gh.gamecenter.common.R.color.text_secondary.toColor(gameNameTv.context))
                    } else {
                        serverTypeTv.background = DrawableView.getServerDrawable(serverLabel.color)
                        serverTypeTv.setTextColor(com.gh.gamecenter.common.R.color.white.toColor(gameNameTv.context))
                    }
                }

                else -> serverTypeTv.visibility = View.GONE
            }

            // 由于RecyclerView的复用机制 需要每次测量gameName的宽
            gameNameTv.requestLayout()
        }

        @JvmStatic
        fun initGameSubtitleAndAdLabel(
            entity: GameEntity,
            gameSubtitleTv: TextView,
            gameNameContainer: LinearLayout? = null,
            gameNameTv: TextView? = null,
            adIconActive: Boolean = false,
            adLabelTv: TextView? = null,
            forceShowSubtitle: Boolean = false,
            modificationCallback: (() -> Unit)? = null
        ) {
            var showSubtitle = false
            var showAdvancedDownload = false
            if ((entity.serverLabel == null && entity.subtitle.isNotEmpty() && !entity.advanceDownload) || (forceShowSubtitle && entity.subtitle.isNotEmpty())) {
                showSubtitle = true
                gameSubtitleTv.run {
                    visibility = View.VISIBLE
                    text = entity.subtitle
                    if (entity.subtitleStyle != null && !TextUtils.isEmpty(entity.subtitleStyle?.color)) {
                        setTextColor("#${entity.subtitleStyle?.color}".hexStringToIntColor())
                        background = GradientDrawable().apply {
                            cornerRadius = 2F.dip2px().toFloat()
                            if (entity.subtitleStyle?.style == "border") {
                                setColor(Color.TRANSPARENT)
                                setStroke(0.5F.dip2px(), "#${entity.subtitleStyle?.background}".hexStringToIntColor())
                            } else {
                                shape = GradientDrawable.RECTANGLE
                                setColor("#${entity.subtitleStyle?.background}".hexStringToIntColor())
                            }
                        }
                    } else {
                        setTextColor(com.gh.gamecenter.common.R.color.text_secondary.toColor(context))
                        background = R.drawable.bg_advance_download_game_subtitle.toDrawable(context)
                    }
                }
            }
            if (entity.advanceDownload) {
                showAdvancedDownload = true
                gameSubtitleTv.apply {
                    visibility = View.VISIBLE
                    text = "预下载"
                    setTextColor(com.gh.gamecenter.common.R.color.text_secondary.toColor(context))
                    background = R.drawable.bg_advance_download_game_subtitle.toDrawable(context)
                }
            }

            if (entity.id == gameSubtitleTv.getTag(com.gh.gamecenter.common.R.string.tag_game_name_id)) return
            gameSubtitleTv.setTag(com.gh.gamecenter.common.R.string.tag_game_name_id, entity.id)

            if (showSubtitle || showAdvancedDownload) {
                val minWidth =
                    if (showSubtitle) SUBTITLE_MIN_WIDTH.dip2px() else if (showAdvancedDownload) ADVANCED_DOWNLOAD_WIDTH.dip2px() else 0
                gameSubtitleTv.post {
                    if (adIconActive && gameNameContainer != null && gameNameTv != null && adLabelTv != null) {
                        val remainWidth = gameNameContainer.width - gameNameTv.width
                        if (remainWidth >= AD_LABEL_WITH_MARGIN_WIDTH.dip2px() + SUBTITLE_MARGIN_START.dip2px() + minWidth) {
                            val subtitleMaxWidth =
                                remainWidth - AD_LABEL_WITH_MARGIN_WIDTH.dip2px() - SUBTITLE_MARGIN_START.dip2px()
                            gameSubtitleTv.maxWidthExcludeZero(subtitleMaxWidth)
                            adLabelTv.visibility = View.VISIBLE
                        } else {
                            // 如果不够位置直接不展示广告标识
                            adLabelTv.visibility = View.GONE
                        }
                    }
                    // 副标题至少展示2个字符，如果不够位置直接不展示副标题
                    if (gameSubtitleTv.layout != null) {
                        val layoutText = gameSubtitleTv.layout.text.toString()
                        val shouldShow =
                            gameSubtitleTv.width >= minWidth || (!layoutText.contains("\uFEFF") && layoutText.length > 2)
                        gameSubtitleTv.isVisible = shouldShow
                    }
                }
                modificationCallback?.invoke()
            } else {
                gameSubtitleTv.visibility = View.GONE
                adLabelTv?.post {
                    if (adIconActive && gameNameContainer != null && gameNameTv != null) {
                        val remainWidth = gameNameContainer.width - gameNameTv.width
                        if (remainWidth < AD_LABEL_WITH_MARGIN_WIDTH.dip2px()) {
                            gameNameTv.maxWidthExcludeZero(gameNameContainer.width - AD_LABEL_WITH_MARGIN_WIDTH.dip2px())
                        }
                        adLabelTv.visibility = View.VISIBLE
                    } else {
                        adLabelTv.visibility = View.GONE
                    }
                }
            }
        }

        /**
         * 复制的 initGameSubtitleAndAdLabel() 方法中的代码
         * 由于 initGameSubtitleAndAdLabel() 方法在太多地方使用，并且参数过多，为避免改动对其它位置代码造成影响，这里重新写一个方法
         * 仅限在 自定义页面/游戏专题详情页 使用
         */
        @JvmStatic
        fun initGameSubtitleAndAdLabelOnGameSubject(
            entity: GameEntity,
            gameSubtitleTv: TextView,
            gameNameContainer: LinearLayout? = null,
            gameNameTv: TextView? = null,
            adIconActive: Boolean = false,
            adLabelTv: TextView? = null,
            canShowTitle: Boolean
        ) {
            var showSubtitle = false
            var showAdvancedDownload = false
            if (canShowTitle && entity.serverLabel == null && entity.subtitle.isNotEmpty() && !entity.advanceDownload) {
                showSubtitle = true
                gameSubtitleTv.run {
                    visibility = View.VISIBLE
                    text = entity.subtitle
                    if (entity.subtitleStyle != null && !TextUtils.isEmpty(entity.subtitleStyle?.color)) {
                        setTextColor("#${entity.subtitleStyle?.color}".hexStringToIntColor())
                        background = GradientDrawable().apply {
                            cornerRadius = 2F.dip2px().toFloat()
                            if (entity.subtitleStyle?.style == "border") {
                                setColor(Color.TRANSPARENT)
                                setStroke(0.5F.dip2px(), "#${entity.subtitleStyle?.background}".hexStringToIntColor())
                            } else {
                                shape = GradientDrawable.RECTANGLE
                                setColor("#${entity.subtitleStyle?.background}".hexStringToIntColor())
                            }
                        }
                    } else {
                        setTextColor(com.gh.gamecenter.common.R.color.text_secondary.toColor(context))
                        background = R.drawable.bg_advance_download_game_subtitle.toDrawable(context)
                    }
                }
            }
            if (entity.advanceDownload) {
                showAdvancedDownload = true
                gameSubtitleTv.apply {
                    visibility = View.VISIBLE
                    text = "预下载"
                    setTextColor(com.gh.gamecenter.common.R.color.text_secondary.toColor(context))
                    background = R.drawable.bg_advance_download_game_subtitle.toDrawable(context)
                }
            }

            if (entity.id == gameSubtitleTv.getTag(com.gh.gamecenter.common.R.string.tag_game_name_id)) return
            gameSubtitleTv.setTag(com.gh.gamecenter.common.R.string.tag_game_name_id, entity.id)

            if (showSubtitle || showAdvancedDownload) {
                val minWidth =
                    if (showSubtitle) SUBTITLE_MIN_WIDTH.dip2px() else if (showAdvancedDownload) ADVANCED_DOWNLOAD_WIDTH.dip2px() else 0
                gameSubtitleTv.post {
                    if (adIconActive && gameNameContainer != null && gameNameTv != null && adLabelTv != null) {
                        val remainWidth = gameNameContainer.width - gameNameTv.width
                        if (remainWidth >= AD_LABEL_WITH_MARGIN_WIDTH.dip2px() + SUBTITLE_MARGIN_START.dip2px() + minWidth) {
                            val subtitleMaxWidth =
                                remainWidth - AD_LABEL_WITH_MARGIN_WIDTH.dip2px() - SUBTITLE_MARGIN_START.dip2px()
                            gameSubtitleTv.maxWidthExcludeZero(subtitleMaxWidth)
                            adLabelTv.visibility = View.VISIBLE
                        } else {
                            // 如果不够位置直接不展示广告标识
                            adLabelTv.visibility = View.GONE
                        }
                    }
                    // 副标题至少展示2个字符，如果不够位置直接不展示副标题
                    if (gameSubtitleTv.layout != null) {
                        val layoutText = gameSubtitleTv.layout.text.toString()
                        val shouldShow =
                            gameSubtitleTv.width >= minWidth || (!layoutText.contains("\uFEFF") && layoutText.length > 2)
                        gameSubtitleTv.isVisible = shouldShow
                    }
                }
            } else {
                gameSubtitleTv.visibility = View.GONE
                adLabelTv?.post {
                    if (adIconActive && gameNameContainer != null && gameNameTv != null) {
                        val remainWidth = gameNameContainer.width - gameNameTv.width
                        if (remainWidth < AD_LABEL_WITH_MARGIN_WIDTH.dip2px()) {
                            gameNameTv.maxWidthExcludeZero(gameNameContainer.width - AD_LABEL_WITH_MARGIN_WIDTH.dip2px())
                        }
                        adLabelTv.visibility = View.VISIBLE
                    } else {
                        adLabelTv.visibility = View.GONE
                    }
                }
            }
        }
    }

    override fun provideExposureData(): ExposureEvent? {
        return boundedGameEntity?.exposureEvent?.getFreshExposureEvent()
    }


}