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

import android.content.Context
import android.view.Gravity
import android.widget.LinearLayout
import android.widget.TextView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.gh.common.constant.Config
import com.gh.common.util.AdHelper
import com.gh.common.util.NewFlatLogUtils
import com.gh.gamecenter.R
import com.gh.gamecenter.common.exposure.ExposureSource
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.databinding.HomeDiscoverCardItemCustomBinding
import com.gh.gamecenter.entity.DiscoveryGameCardLabel
import com.gh.gamecenter.game.vertical.SpanCountPagerSnapHelper
import com.gh.gamecenter.home.custom.CustomPageViewModel
import com.gh.gamecenter.home.custom.IGameChangedNotifier
import com.gh.gamecenter.home.custom.adapter.CustomDiscoverCardGameAdapter
import com.gh.gamecenter.home.custom.createExposureEvent
import com.gh.gamecenter.home.custom.eventlistener.OtherItemEventHelper
import com.gh.gamecenter.home.custom.model.CustomDiscoverCardItem
import com.gh.gamecenter.home.custom.model.CustomPageItem
import splitties.views.dsl.core.endMargin

/**
 * 光环推荐
 * 发现页
 */
class CustomHomeDiscoverCardViewHolder(
    viewModel: CustomPageViewModel,
    val binding: HomeDiscoverCardItemCustomBinding
) : BaseCustomViewHolder(viewModel, binding.root) {

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

    private val adapter by lazy {
        CustomDiscoverCardGameAdapter(
            itemView.context,
            pageConfigure.entrance,
            childEventHelper
        )
    }

    override val gameChangedNotifier: IGameChangedNotifier
        get() = adapter

    init {
        binding.recyclerView.isNestedScrollingEnabled = false
        binding.recyclerView.itemAnimator = null
    }

    fun bindView(item: CustomPageItem, position: Int) {
        super.bindView(item)
        if (item is CustomDiscoverCardItem) {
            _item = item

            val spanCount = 3
            val snapHelper = SpanCountPagerSnapHelper(spanCount, false)
            val entity = item.data ?: return
            binding.run {
                val context = root.context
                labelHSV.background = com.gh.gamecenter.common.R.drawable.background_shape_white_radius_6_bottom_only.toDrawable(context)
                prefsIv.goneIf(!Config.getUserInterestedGame()) {
                    prefsIv.setOnClickListener {
                        context.ifLogin("${pageConfigure.entrance}-发现页卡片") {
                            childEventHelper.navigateToInterestedGamePage()
                        }
                    }
                }
                allTv.setOnClickListener {
                    childEventHelper.navigateToDiscoveryPage()
                }

                if (recyclerView.adapter == null) {
                    recyclerView.layoutManager = GridLayoutManager(context, spanCount, RecyclerView.HORIZONTAL, false)
                    recyclerView.adapter = adapter
                    snapHelper.attachToRecyclerView(recyclerView)
                }
                adapter.submitList(entity.games)

                val childCount = labelContainer.childCount
                entity.label.forEachIndexed { index, label ->
                    if (index < childCount) {
                        val labelView = labelContainer.getChildAt(index) as TextView
                        updateLabelView(
                            context,
                            labelView,
                            label,
                            index == entity.label.size - 1,
                            pageConfigure.entrance,
                            "",
                            position
                        )
                    } else {
                        val newLabelView = TextView(context)
                        updateLabelView(
                            context,
                            newLabelView,
                            label,
                            index == entity.label.size - 1,
                            pageConfigure.entrance,
                            "",
                            position
                        )
                        labelContainer.addView(newLabelView)
                    }
                }
            }

            fillExposureEventList(item)
        }
    }

    private fun updateLabelView(
        context: Context,
        textView: TextView,
        label: DiscoveryGameCardLabel,
        isLast: Boolean,
        entrance: String,
        blockName: String,
        position: Int
    ) {
        textView.background = com.gh.gamecenter.common.R.drawable.bg_shape_space_radius_4.toDrawable(context)
        textView.setTextColor(com.gh.gamecenter.common.R.color.text_secondary.toColor(context))

        if (textView.text == label.title) return

        textView.run {
            layoutParams = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                36F.dip2px()
            ).apply { endMargin = if (isLast) 14F.dip2px() else 8F.dip2px() }
            setPadding(12F.dip2px(), 0, 12F.dip2px(), 0)
            gravity = Gravity.CENTER
            setDrawableEnd(R.drawable.ic_interest_arrow)
            compoundDrawablePadding = 8F.dip2px()
            textSize = 12F
            text = label.title
            label.text = label.linkText
            setOnClickListener {
                NewFlatLogUtils.logDiscoverPageRecommendedInterestCardClick(
                    position,
                    label.text ?: "",
                    label.type ?: "",
                    label.link ?: "",
                    entrance,
                    blockName
                )
                childEventHelper.trackGameExploreClick("内容标签", label.title ?: "", linkEntity = label)
                childEventHelper.navigateToLinkPage(label)
            }
        }
    }

    fun fillExposureEventList(item: CustomDiscoverCardItem) {
        val gameList = item.data?.games ?: return
        for ((i, gameEntity) in gameList.withIndex()) {
            gameEntity.exposureEvent = createExposureEvent(
                gameEntity,
                listOf(ExposureSource("发现", gameEntity.getTypeName())),
                pageConfigure.exposureSourceList,
                i,
                item.componentPosition,
                createTrackData(item)
            )

            if (!gameEntity.adGroupId.isEmpty() && !gameEntity.isAdRequestReported) {
                AdHelper.reportAdRequest(gameEntity.exposureEvent!!)
                gameEntity.isAdRequestReported = true
            }
        }
    }
}