package com.gh.gamecenter.home.custom.viewholder

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 androidx.recyclerview.widget.RecyclerView
import com.therouter.TheRouter
import com.gh.common.util.DownloadItemUtils
import com.gh.gamecenter.adapter.viewholder.GameViewHolder
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.common.view.DrawableView
import com.gh.gamecenter.core.runOnIoThread
import com.gh.gamecenter.core.utils.StringUtils
import com.gh.gamecenter.databinding.GameItemCustomBinding
import com.gh.gamecenter.feature.R
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
import com.gh.gamecenter.home.custom.CustomPageViewModel
import com.gh.gamecenter.home.custom.adapter.CustomViewExt
import com.gh.gamecenter.home.custom.eventlistener.SubjectEventHelper
import com.gh.gamecenter.home.custom.model.CustomPageItem
import com.gh.gamecenter.home.custom.model.CustomSplitSubjectItem

/**
 * 游戏专题-长列表式
 * 专题游戏-竖屏-v2
 */
class CustomGameItemViewHolder(
    viewModel: CustomPageViewModel,
    val binding: GameItemCustomBinding
) : BaseCustomViewHolder(viewModel, binding.root), IExposureProvider {

    private var boundedGameEntity: GameEntity? = null

    override val onlyNotifyItemChanged: Boolean
        get() = true

    override val childEventHelper by lazy(LazyThreadSafetyMode.NONE) {
        SubjectEventHelper(viewModel)
    }

    fun bindView(
        item: CustomPageItem,
        adapter: RecyclerView.Adapter<out RecyclerView.ViewHolder>
    ) {
        super.bindView(item)
        if (item is CustomSplitSubjectItem) {
            setSplitSubjectTitle(binding.layoutTitle, item, childEventHelper, TITLE_TYPE_SMALL)

            val subject = item.data
            boundedGameEntity = subject.data?.getOrNull(item.startChildPosition) ?: return

            runOnIoThread(isLightWeightTask = true) {
                fillExposureAndReportAd(boundedGameEntity!!, item.startChildPosition, item)
            }

            val entity = boundedGameEntity ?: return

            binding.run {
                val paddingBottom = if (item.isLastLine) {
                    8f.dip2px()
                } else {
                    0
                }
                root.setPadding(root.paddingLeft, root.paddingTop, root.paddingRight, paddingBottom)

                clContainer.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))

                gameIconView.displayGameIconWithIfShowSubscript(entity, item.data.showIndexIconSubscript)
                val provider = TheRouter.get(IBindingAdaptersProvider::class.java)
                provider?.setGameName(gameName, entity, false)
                provider?.setGameTagsWithSellingPoints(labelList, layoutSellingPoints, entity, subject.tag ?: "")

                CustomViewExt.setGameRatting(gameRating, subject.briefStyle, entity)
                CustomViewExt.setDescription(gameDes, subject.briefStyle, entity)
                recommendStar.rating = entity.recommendStar.toFloat()
                initCustomGameSubtitleAndAdLabel(
                    entity,
                    gameSubtitleTv,
                    gameNameContainer,
                    gameName,
                    entity.adIconActive,
                    adLabelTv,
                    item.data.showIndexSubtitle
                )
                MiniGameItemHelper.setMiniGameUsage(gamePlayCount, entity)
            }

            entity.customPageTrackData = createTrackData(item)
            DownloadItemUtils.setOnClickListener(
                itemView.context, binding.downloadBtn, entity, bindingAdapterPosition,
                adapter,
                StringUtils.buildString(
                    "(游戏-专题:",
                    subject.name,
                    "-列表[",
                    (bindingAdapterPosition + 1).toString(),
                    "])"
                ),
                location = StringUtils.buildString("游戏-专题-", subject.name, ":", subject.name),
                traceEvent = item.exposureEvent
            ) {
                childEventHelper.onDownloadButtonClick(item.startChildPosition, entity)
            }
            DownloadItemUtils.updateItem(
                itemView.context,
                entity,
                CustomGameViewHolder(binding),
                briefStyle = subject.briefStyle
            )

            binding.clContainer.setOnClickListener {
                val entrance = if (entity.isPluggable) {
                    StringUtils.buildString("(游戏-专题:插件化-列表[", "${item.startChildPosition}", "])")
                } else {
                    StringUtils.buildString(
                        "(游戏-专题:",
                        subject.name,
                        "-列表[",
                        "${item.startChildPosition}",
                        "])"
                    )
                }
                childEventHelper.navigateToGameDetailPage(item.startChildPosition, entity)
            }

            initServerType(binding.gameName, binding.gameKaifuType, entity)
        }
    }

    companion object {
        private const val ADVANCED_DOWNLOAD_WIDTH = 34F
        private const val SUBTITLE_MIN_WIDTH = 24F
        private const val SUBTITLE_MARGIN_START = 4F
        private 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 initCustomGameSubtitleAndAdLabel(
            entity: GameEntity,
            gameSubtitleTv: TextView,
            gameNameContainer: LinearLayout? = null,
            gameNameTv: TextView? = null,
            adIconActive: Boolean = false,
            adLabelTv: TextView? = null,
            canShowSubTitle: Boolean
        ) {
            var showSubtitle = false
            var showAdvancedDownload = false
            if (canShowSubTitle && 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
                    }
                }
            }
        }
    }

    class CustomGameViewHolder(binding: GameItemCustomBinding) : GameViewHolder(binding.root) {
        init {
            gameDownloadBtn = binding.downloadBtn
            gameDes = binding.gameDes
            recommendContainer = binding.recommendContainer
            recommendIv = binding.recommendIv
            recommendTv = binding.recommendTv
            multiVersionDownloadTv = binding.multiVersionDownloadTv
            gameDownloadTips = binding.downloadTipsLottie
        }
    }

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

}