package com.gh.gamecenter.search.viewholder

import android.content.Context
import android.graphics.Color
import android.util.SparseArray
import android.view.View
import android.view.ViewGroup
import android.view.ViewGroup.MarginLayoutParams
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.view.updateLayoutParams
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.gh.common.util.CheckLoginUtils
import com.gh.gamecenter.R
import com.gh.gamecenter.SearchActivity
import com.gh.gamecenter.common.exposure.ExposureSource
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.databinding.GameCollectionSquareItemBinding
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.feature.exposure.ExposureEvent
import com.gh.gamecenter.feature.exposure.ExposureType
import com.gh.gamecenter.home.custom.model.CustomPageData

class SearchGameListViewHolder(
    val binding: GameCollectionSquareItemBinding,
    private val location: String,
    private val exposureEventArray: SparseArray<ExposureEvent>?,
    private val listener: SearchGameListListener
) : ViewHolder(binding.root) {

    private val context: Context
        get() = binding.root.context

    private val posterWidth by lazy(LazyThreadSafetyMode.NONE) {
        context.resources.displayMetrics.widthPixels - 32F.dip2px()
    }

    fun bind(item: CustomPageData.LinkColumnCollection.CustomSubjectEntity, key: String, searchType: String) {
        with(binding) {
            val exposureEvent = ExposureEvent.createEvent(
                GameEntity().apply {
                    sequence = bindingAdapterPosition
                },
                listOf(
                    ExposureSource(location, ""),
                    ExposureSource(SearchActivity.toTrackSearchType(searchType), key)
                ),
                null,
                ExposureType.EXPOSURE
            )
            exposureEventArray?.put(bindingAdapterPosition, exposureEvent)
            root.updateLayoutParams {
                if (this is MarginLayoutParams) {
                    topMargin = 16F.dip2px()
                }
            }
            poster.setTag(ImageUtils.TAG_TARGET_WIDTH, posterWidth)
            ImageUtils.display(poster, item.image)
            ImageUtils.display(userIv, item.user.icon)
            titleTv.text = item.title.fromHtml()
            item.games.take(3).forEachIndexed { index, game ->
                when (index) {
                    0 -> iconIvOne.displayGameIcon(game)
                    1 -> iconIvTwo.displayGameIcon(game)
                    2 -> iconIvThree.displayGameIcon(game)
                }
            }
            item.games.size.let {
                iconIvOne.goneIf(it == 0)
                iconIvTwo.goneIf(it < 2)
                iconIvThree.goneIf(it < 3)
            }

            countTv.goneIf(item.count.game < 4 || item.games.isEmpty())
            countTv.text = "+ ${item.count.game - 3}"
            hotTv.text = if (item.count.hot > 10000) "10000+" else item.count.hot.toString()

            userTv.text = item.user.name
            playedGameProgress.max = item.count.game
            playedGameProgress.progress = item.count.gamePlayed ?: 0
            playedGameTv.text =
                "玩过 ${item.count.gamePlayed} / ${item.count.game} 款"
            stampIv.goneIf(item.stamp.isEmpty())
            stampIv.setBackgroundResource(if (item.stamp == "official") R.drawable.ic_official else R.drawable.ic_chosen)

            tagContainer.removeAllViews()
            tagContainer.visibleIf(!CheckLoginUtils.isLogin() || item.count.game == 0) {
                item.tags.forEachIndexed { index, tag ->
                    // 添加分隔线
                    if (index != 0) tagContainer.addView(View(context).apply {
                        layoutParams = ViewGroup.LayoutParams(1F.dip2px(), 14F.dip2px())
                        setBackgroundColor(Color.parseColor("#33FFFFFF"))
                    })
                    // 添加标签
                    tagContainer.addView(TextView(context).apply {
                        layoutParams = LinearLayout.LayoutParams(
                            LinearLayout.LayoutParams.WRAP_CONTENT,
                            LinearLayout.LayoutParams.WRAP_CONTENT
                        )
                        setPadding(if (index == 0) 0 else 6F.dip2px(), 0, 6F.dip2px(), 0)
                        text = tag.name
                        setTextColor(com.gh.gamecenter.common.R.color.white.toColor())
                        textSize = 10F
                    })
                }
            }
            playedGamesContainer.visibleIf(CheckLoginUtils.isLogin() && item.count.game != 0)
            adLabelTv.goneIf(!item.adIconActive)
            arrayOf(iconIvOne, iconIvTwo, iconIvThree).forEachIndexed { index, ivIcon ->
                ivIcon.setOnClickListener {
                    val game = item.games.getOrNull(index)
                    game?.id?.let { gameId ->
                        listener.navigateToGameDetailPage(gameId, bindingAdapterPosition, item)
                    }
                }
            }

            userContainer.setOnClickListener {
                listener.navigateToHomePage(item.user.id, bindingAdapterPosition, item)
            }
            root.setOnClickListener {
                listener.navigateGameCollectionDetailPage(bindingAdapterPosition, item, exposureEvent.source)
            }
        }
    }

    interface SearchGameListListener {

        fun navigateToGameDetailPage(
            gameId: String,
            position: Int,
            collection: CustomPageData.LinkColumnCollection.CustomSubjectEntity
        )

        fun navigateToHomePage(
            userId: String,
            position: Int,
            collection: CustomPageData.LinkColumnCollection.CustomSubjectEntity
        )

        fun navigateGameCollectionDetailPage(
            position: Int,
            collection: CustomPageData.LinkColumnCollection.CustomSubjectEntity,
            exposureSourceList: List<ExposureSource>
        )
    }
}