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

import android.graphics.Paint
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.view.marginStart
import com.gh.common.util.AdHelper
import com.gh.gamecenter.R
import com.gh.gamecenter.common.utils.ImageUtils
import com.gh.gamecenter.common.utils.dip2px
import com.gh.gamecenter.common.utils.display
import com.gh.gamecenter.common.utils.goneIf
import com.gh.gamecenter.core.runOnIoThread
import com.gh.gamecenter.databinding.GameDoubleWelfareCardCustomBinding
import com.gh.gamecenter.databinding.RecyclerDoubleWelfareCardCustomBinding
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.feature.exposure.ExposureEvent
import com.gh.gamecenter.feature.exposure.IExposureListProvider
import com.gh.gamecenter.home.custom.CustomPageViewModel
import com.gh.gamecenter.home.custom.createExposureEvent
import com.gh.gamecenter.home.custom.eventlistener.SubjectEventHelper
import com.gh.gamecenter.home.custom.model.CustomPageItem
import com.gh.gamecenter.home.custom.model.CustomSplitSubjectItem

/**
 * 游戏专题-双列福利卡片
 */
class CustomDoubleWelfareCardViewHolder(
    viewModel: CustomPageViewModel,
    val binding: RecyclerDoubleWelfareCardCustomBinding
) : BaseCustomViewHolder(viewModel, binding.root), IExposureListProvider {

    private var exposureEventList: ArrayList<ExposureEvent>? = arrayListOf()

    private val posterWidth by lazy {
        (itemView.context.resources.displayMetrics.widthPixels - 40F.dip2px()) / 2
    }

    override val childEventHelper by lazy {
        SubjectEventHelper(viewModel)
    }

    override fun bindView(item: CustomPageItem) {
        super.bindView(item)
        if (item is CustomSplitSubjectItem) {
            val gameList = item.data.data ?: return

            runOnIoThread(true) {
                fillExposureList(item)
            }

            setSplitSubjectTitle(binding.layoutTitle, item, childEventHelper)

            val topMargin = if (item.isFirstLine) {
                0
            } else {
                12f.dip2px()
            }
            val bottomMargin = if (item.isLastLine) {
                16f.dip2px()
            } else {
                0
            }
            (itemView.layoutParams as? ViewGroup.MarginLayoutParams)?.let {
                it.topMargin = topMargin
                it.bottomMargin = bottomMargin
                itemView.layoutParams = it
            }

            val leftPosition = item.startChildPosition
            val rightPosition = leftPosition + 1

            val hasLeft = gameList.size > leftPosition
            if (hasLeft) {
                bindSubView(
                    item,
                    gameList[leftPosition],
                    binding.leftCardView,
                    leftPosition
                )
            }

            val hasRight = gameList.size > rightPosition
            if (hasRight) {
                binding.rightCardView.posterCardView.visibility = View.VISIBLE
                bindSubView(
                    item,
                    gameList[rightPosition],
                    binding.rightCardView,
                    rightPosition
                )

            } else {
                binding.rightCardView.posterCardView.visibility = View.INVISIBLE
            }
        }
    }

    private fun bindSubView(
        item: CustomSplitSubjectItem,
        gameEntity: GameEntity,
        subBinding: GameDoubleWelfareCardCustomBinding,
        position: Int
    ) {
        subBinding.run {
            ivPoster.setTag(ImageUtils.TAG_TARGET_WIDTH, posterWidth)
            ivPoster.post {
                if (gameEntity.columnImage.isNullOrBlank()) {
                    gameEntity.image
                } else {
                    gameEntity.columnImage
                }?.let(ivPoster::display)
            }
            tvTitle.text = gameEntity.name

            // 如果一排无法完全显示，则按照 充值现价＞充值原价＞补充文案＞标签文案 的优先级显示
            val views = arrayListOf(
                subBinding.tvPriceUnit,
                subBinding.tvPrice,
                subBinding.tvPriceOriginal,
                subBinding.tvWelfareCopy,
                subBinding.tvLabel
            ).onEach { child ->
                child.goneIf(false)
            }
            val labelText = gameEntity.welfareInfo?.labelText
            if (labelText.isNullOrBlank()) {
                itemView.context.getString(R.string.recharge)
            } else {
                labelText
            }.let(tvLabel::setText)
            val currentPrice = gameEntity.welfareInfo?.rechargeCurrentPrice ?: 0F
            tvPrice.text = if (currentPrice == 0F) {
                "0"
            } else {
                "$currentPrice"
            }
            tvPriceOriginal.text = itemView.context.getString(
                R.string.price_with_symbol,
                "${gameEntity.welfareInfo?.rechargeOriginalPrice ?: 0F}"
            )
            tvPriceOriginal.paint.flags = Paint.STRIKE_THRU_TEXT_FLAG
            val additionalText = gameEntity.welfareInfo?.additionalText
            if (additionalText.isNullOrBlank()) {
                tvWelfareCopy.goneIf(true)
            } else {
                tvWelfareCopy.text = additionalText
            }

            itemView.post {
                hideViewsIfNeed(subBinding, views)
            }

            root.setOnClickListener {
                childEventHelper.navigateToGameDetailPage(position, gameEntity)
            }
        }
    }

    private fun hideViewsIfNeed(subBinding: GameDoubleWelfareCardCustomBinding, views: ArrayList<TextView>) {
        if (views.isEmpty()) {
            return
        }
        val totalWidth = views.sumOf {
            it.width + it.marginStart
        }
        if (totalWidth > subBinding.root.width) {
            val lastView = views.removeLast()
            lastView.goneIf(true)
            hideViewsIfNeed(subBinding, views)
        }
    }

    private fun fillExposureList(item: CustomSplitSubjectItem) {
        exposureEventList = arrayListOf<ExposureEvent>()
        for (i in item.startChildPosition..item.endChildPosition) {
            val game = item.data.data?.getOrNull(i) ?: break
            val event = createExposureEvent(
                game,
                item.exposureSource,
                pageConfigure.exposureSourceList,
                i,
                item.componentPosition,
                createTrackData(item)
            )
            game.exposureEvent = event

            if (game.adGroupId.isNotEmpty() && !game.isAdRequestReported) {
                AdHelper.reportAdRequest(game.exposureEvent!!)
                game.isAdRequestReported = true
            }

            exposureEventList?.add(event)
        }
    }

    override fun provideExposureDataList(): List<ExposureEvent>? {
        exposureEventList?.forEach {
            it.getFreshExposureEvent()
        }
        return exposureEventList
    }

    override fun provideExposureData(): ExposureEvent? = null
}