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.util.AdHelper
import com.gh.gamecenter.common.entity.LinkEntity
import com.gh.gamecenter.common.exposure.ExposureSource
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.HomeSlideListCustomBinding
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.feature.exposure.ExposureEvent
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.CommonContentHomeSLideListUi

/**
 * 通用内容合集-轮播Banner
 */
class CustomHomeSlideListViewHolder(
    viewModel: CustomPageViewModel,
    private val lifecycleOwner: LifecycleOwner,
    val binding: HomeSlideListCustomBinding,
) : BaseCustomViewHolder(viewModel, binding.root), OnCustomPageRefreshStateListener {

    // 是否是首位
    private var isFirst = false

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

    private val slideListUi by lazy {
        CommonContentHomeSLideListUi(
            binding,
            lifecycleOwner,
            object : CommonContentHomeSLideListUi.OnCommonHomeSlideListEventListener {
                override fun navigateToLinkPage(link: LinkEntity, text: String, exposureEvent: ExposureEvent?) {
                    childEventHelper.navigateToLinkPage(link, text, exposureEvent)
                }

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

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

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

    override fun bindView(item: CustomPageItem) {
        super.bindView(item)
        if (item is CustomCommonContentCollectionItem) {
            val slideList = item.data.slides.slide

            runOnIoThread(isLightWeightTask = true) {
                for ((index, homeSlide) in slideList.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
                        }
                    }
                }
            }

            slideListUi.bind(slideList, bindingAdapterPosition)
        }
    }

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

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

    override fun onBackgroundAlphaChanged(alpha: Float) {
        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))
        }
    }
}