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

import android.graphics.drawable.GradientDrawable
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.RecyclerView
import com.gh.common.exposure.ExposureManager
import com.gh.common.util.AdHelper
import com.gh.gamecenter.common.entity.LinkEntity
import com.gh.gamecenter.common.exposure.ExposureSource
import com.gh.gamecenter.common.json.json
import com.gh.gamecenter.common.utils.SensorsBridge
import com.gh.gamecenter.common.utils.toColor
import com.gh.gamecenter.common.view.DrawableView
import com.gh.gamecenter.core.runOnIoThread
import com.gh.gamecenter.databinding.HomeSlideWithCardsCustomBinding
import com.gh.gamecenter.entity.HomeSubSlide
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.CustomPageViewModel
import com.gh.gamecenter.home.custom.OnCustomPageRefreshStateListener
import com.gh.gamecenter.home.custom.adapter.CustomPageAdapter
import com.gh.gamecenter.home.custom.createExposureEvent
import com.gh.gamecenter.home.custom.eventlistener.CommonContentCollectionEventHelper
import com.gh.gamecenter.home.custom.model.CustomCommonContentCollectionItem
import com.gh.gamecenter.home.custom.model.CustomPageItem
import com.gh.gamecenter.home.custom.ui.CommonContentHomeSlideWithCardsUi

/**
 * 通用内容合集-轮播banner
 * 带右侧2个卡片的轮播图
 */
class CustomHomeSlideWithCardsViewHolder(
    viewModel: CustomPageViewModel,
    private val lifecycleOwner: LifecycleOwner,
    val binding: HomeSlideWithCardsCustomBinding,
) : BaseCustomViewHolder(viewModel, binding.root), OnCustomPageRefreshStateListener {

    private var backgroundAlpha: Float = 1F
    private var isFirst = false

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

    private val slideWithCardsUi by lazy {
        CommonContentHomeSlideWithCardsUi(
            viewModel.commonContentCollectionUseCase,
            lifecycleOwner,
            binding,
            viewModel.refreshCount,
            viewModel.pageConfigure.exposureSourceList,
            pageLocation.pageLevelString,
            object : CommonContentHomeSlideWithCardsUi.HomeSLideWithCardsEventListener {
                override fun updateImmersiveColor(color: Int) {
                    this@CustomHomeSlideWithCardsViewHolder.updateImmersiveColor(color)
                }

                override fun navigateToGameDetailPage(
                    childPosition: Int,
                    gameEntity: GameEntity,
                    text: String,
                    link: LinkEntity?
                ) {
                    childEventHelper.navigateToGameDetailPage(childPosition, gameEntity, text, link)
                }

                override fun navigateToLinkPageInSubSlide(
                    game: GameEntity,
                    homeSubSlide: HomeSubSlide,
                    text: String
                ) {
                    (_item as? CustomCommonContentCollectionItem)?.let {
                        val clickEvent = ExposureEvent.createEventWithSourceConcat(
                            gameEntity = game,
                            basicSource = pageConfigure.exposureSourceList,
                            source = listOf(
                                ExposureSource(
                                    "通用内容合集",
                                    "${it.data.name}+${it.data.layoutChinese}+${it.data.id}"
                                ),
                                ExposureSource("右侧卡片", homeSubSlide.id)
                            ),
                            event = ExposureType.CLICK
                        )
                        val homeSubLink = homeSubSlide.toLinkEntity()
                        if (homeSubLink.type != "game") {
                            ExposureManager.log(clickEvent)
                        }
                        SensorsBridge.trackEvent("RightSideCardClick", json {
                            "position" to homeSubSlide.sequence
                            "title" to homeSubSlide.title
                            "card_id" to homeSubSlide.id
                        })
                        childEventHelper.navigateToLinkPage(homeSubLink, "右侧卡片-游戏", clickEvent)
                    }
                }

                override fun navigateToLinkPage(link: LinkEntity, text: String, exposureEvent: ExposureEvent?) {
                    childEventHelper.navigateToLinkPage(link, text, exposureEvent)
                }
            })
    }

    private val firstShowPositionObserver = Observer<Int> {
        isFirst = bindingAdapterPosition <= it
        slideWithCardsUi.updateWhenTopVisibleItemCountChanged(isFirst)
    }

    override fun bindView(item: CustomPageItem) {
        super.bindView(item)

        if (item is CustomCommonContentCollectionItem) {
            runOnIoThread(isLightWeightTask = true) {
                fillExposureEvent(item)
            }
            slideWithCardsUi.bind(item.data, bindingAdapterPosition)
        }
    }

    private fun fillExposureEvent(item: CustomCommonContentCollectionItem) {
        // 处理轮播图
        for ((index, homeSlide) in item.data.slides.slide.withIndex()) {
            val game = homeSlide.linkGame
            game?.exposureEvent = createExposureEvent(
                game,
                listOf(
                    ExposureSource("通用内容合集", "${item.data.name}+${item.data.layoutChinese}+${item.data.id}"),
                    ExposureSource("轮播图", "")
                ),
                pageConfigure.exposureSourceList,
                index,
                _item.componentPosition,
                createTrackData(item)
            )

            game?.let {
                if (!it.adGroupId.isEmpty() && !it.isAdRequestReported) {
                    AdHelper.reportAdRequest(it.exposureEvent!!)
                    it.isAdRequestReported = true
                }
            }

            if (homeSlide.linkType != "game") {
                game?.exposureEvent?.let {
                    it.payload.controlType = "轮播图"
                    it.payload.controlName = homeSlide.title
                    it.payload.controlLinkName = homeSlide.linkText
                    it.payload.controlLinkType = homeSlide.linkType
                }
            }
        }
    }

    override fun onViewAttach(parent: RecyclerView?) {
        (bindingAdapter as? CustomPageAdapter)?.firstShowPosition?.observe(
            lifecycleOwner,
            firstShowPositionObserver
        )
        slideWithCardsUi.onViewAttach(parent)
    }

    override fun onViewDetach(parent: RecyclerView?) {
        (bindingAdapter as? CustomPageAdapter)?.firstShowPosition?.removeObserver(firstShowPositionObserver)
        slideWithCardsUi.onViewDetach(parent)
    }

    private fun updateImmersiveColor(color: Int) {
        if (pageConfigure.isInSearchToolbarTabWrapperPage) {
            if (isFirst) {
                viewModel.onChangeAppBarColor(color)
            }
            updateBackground(color)
        }
    }

    override fun onBackgroundAlphaChanged(alpha: Float) {
        backgroundAlpha = alpha
        binding.backgroundView.alpha = alpha
    }

    private fun updateBackground(color: Int) {
        if (isFirst) {
            val gradientDrawable = DrawableView.getGradientDrawable(
                color,
                com.gh.gamecenter.common.R.color.ui_surface.toColor(binding.root.context), GradientDrawable.Orientation.TOP_BOTTOM, 0f
            )
            binding.backgroundView.background = gradientDrawable
        } else {
            binding.backgroundView.setBackgroundColor(com.gh.gamecenter.common.R.color.ui_surface.toColor(itemView.context))
        }
    }
}