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

import android.graphics.drawable.ColorDrawable
import android.view.View
import android.view.ViewGroup.MarginLayoutParams
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.gh.common.databind.BindingAdapters
import com.gh.common.util.AdHelper
import com.gh.common.util.DownloadItemUtils
import com.gh.gamecenter.R
import com.gh.gamecenter.adapter.viewholder.GameViewHolder
import com.gh.gamecenter.common.exposure.ExposureSource
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.core.utils.RandomUtils
import com.gh.gamecenter.databinding.HomeGameItemCustomBinding
import com.gh.gamecenter.feature.entity.CustomPageTrackData
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.feature.exposure.ExposureEvent
import com.gh.gamecenter.feature.exposure.IExposureProvider
import com.gh.gamecenter.feature.game.GameItemViewHolder
import com.gh.gamecenter.feature.minigame.MiniGameItemHelper
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.CustomGameItem
import com.gh.gamecenter.home.custom.model.CustomPageItem
import com.shuyu.gsyvideoplayer.builder.GSYVideoOptionBuilder
import com.shuyu.gsyvideoplayer.video.base.GSYVideoView

/**
 * 游戏专题-展开大图
 * 游戏-首页大图/顶部视频-v2
 */
class CustomHomeGameItemViewHolder(
    viewModel: CustomPageViewModel,
    val binding: HomeGameItemCustomBinding
) : BaseCustomViewHolder(viewModel, binding.root), IExposureProvider {

    private var boundedGameEntity: GameEntity? = null

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

    override val onlyNotifyItemChanged: Boolean
        get() = true

    fun bindView(
        item: CustomPageItem,
        position: Int,
        adapter: RecyclerView.Adapter<out RecyclerView.ViewHolder>
    ) {
        super.bindView(item)
        if (item is CustomGameItem) {
            val topMargin = if (item.isFirstLine) {
                0
            } else {
                -16f.dip2px()
            }
            (itemView.layoutParams as? MarginLayoutParams)?.let {
                it.topMargin = topMargin
            }

            val isDarkMode = DarkModeUtils.isDarkModeOn(itemView.context)
            if (isDarkMode) {
                binding.vBackground.background = null
            } else {
                binding.vBackground.setBackgroundResource(R.drawable.bg_custom_game_item)
            }

            binding.gameInfoContainer.background =
                ContextCompat.getDrawable(itemView.context, com.gh.gamecenter.common.R.drawable.bg_divider_game_expand_item_custom)

            val game = item.data
            val topVideo = game.topVideo
            val homeSetting = game.homeSetting

            boundedGameEntity = game
            game.pageLevelString = pageLocation.pageLevelString
            game.outerSequence = item.componentPosition
            game.exposureEvent = createExposureEvent(
                item.data,
                listOf(
                    ExposureSource(
                        "专题",
                        "${item.linkColumn?.name ?: ""}+${item.componentStyle}+${item.linkColumn?.id ?: ""}"
                    )
                ),
                pageConfigure.exposureSourceList,
                item.childPosition,
                item.componentPosition,
                createTrackData(item)
            )

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

            bindGameInfo(
                position,
                game,
                adapter,
                position,
                item.exposureEvent,
                pageConfigure.entrance,
                item.data.adIconActive
            ) {
                CustomPageTrackData(
                    viewModel.pageLocation,
                    item.componentName,
                    item.componentStyle,
                    item.linkColumn?.name ?: "",
                    item.linkColumn?.id ?: ""
                )
            }
            binding.gameBrief.goneIf(game.recommendText.isEmpty()) {
                binding.gameBrief.text = game.recommendText
            }
            binding.gameImage.visibleIf(game.showImage) {
                if (game.isWechatMiniGame()) {
                    ImageUtils.display(binding.gameImage, game.banner)
                } else {
                    ImageUtils.display(binding.gameImage, game.homeSetting.image)
                }
                val hierarchy = binding.gameImage.hierarchy
                try {
                    hierarchy.setPlaceholderImage(ColorDrawable(game.homeSetting.placeholderColor.hexStringToIntColor()))
                } catch (ignore: Throwable) {
                    hierarchy.setPlaceholderImage(RandomUtils.getRandomPlaceholderColor())
                }
            }
            binding.autoVideoView.goneIf(game.showImage) {
                if (!binding.autoVideoView.isInPlayingState) {
                    GSYVideoOptionBuilder()
                        .setIsTouchWiget(false)
                        .setUrl(topVideo?.url ?: "")
                        .setRotateViewAuto(false)
                        .setCacheWithPlay(true)
                        .setRotateWithSystem(false)
                        .setReleaseWhenLossAudio(true)
                        .setLooping(false)
                        .setShowFullAnimation(false)
                        .build(binding.autoVideoView)
                    binding.autoVideoView.updateThumb(topVideo?.poster ?: "")
                    binding.autoVideoView.setParamsData(game, homeSetting.placeholderColor, true)
                    binding.autoVideoView.detailBtn?.setOnClickListener {
                        itemView.performClick()
                        binding.autoVideoView.uploadVideoStreamingPlaying("点击遮罩", true)
                    }
                    binding.autoVideoView.setOnVideoClickListener { itemView.performClick() }
                }
            }

            binding.gameImage.setOnClickListener {
                childEventHelper.navigateToGameDetailPage(item.childPosition, game)
            }
            itemView.setOnClickListener {
                childEventHelper.navigateToGameDetailPage(item.childPosition, game)

                if (binding.autoVideoView.isInPlayingState) {
                    binding.autoVideoView.uploadVideoStreamingPlaying(
                        "游戏详情-播放点击",
                        binding.autoVideoView.detailBtn?.visibility == View.VISIBLE
                    )
                } else {
                    if (binding.autoVideoView.currentState == GSYVideoView.CURRENT_STATE_AUTO_COMPLETE) {
                        binding.autoVideoView.uploadVideoStreamingPlaying(
                            "游戏详情-完播点击",
                            binding.autoVideoView.detailBtn?.visibility == View.VISIBLE
                        )
                    }
                }
            }
        }
    }

    private fun bindGameInfo(
        childPosition: Int,
        game: GameEntity,
        adapter: RecyclerView.Adapter<out RecyclerView.ViewHolder>,
        position: Int,
        exposureEvent: ExposureEvent?,
        entrance: String,
        adIconActive: Boolean,
        createTrackData: () -> CustomPageTrackData
    ) {
        binding.gameIcon.displayGameIconWithIfShowSubscript(game, game.showIconSubscript)
        binding.gameName.setTextColor(com.gh.gamecenter.common.R.color.text_primary.toColor(binding.root.context))
        binding.gameBrief.setTextColor(com.gh.gamecenter.common.R.color.text_primary.toColor(binding.root.context))
        binding.gameName.text = game.name
        binding.gameRating.text = game.star.toString()
        binding.gameRating2.text = game.star.toString()
        binding.gameRating.setDrawableStart(R.drawable.home_game_rating, 12F.dip2px(), 12F.dip2px())
        BindingAdapters.setGameTags(binding.gameTags, game, "")

        GameItemViewHolder.initGameSubtitleAndAdLabelOnGameSubject(
            game,
            binding.gameSubtitleTv,
            binding.gameNameContainer,
            binding.gameName,
            adIconActive,
            binding.adLabelTv,
            canShowTitle = game.showSubtitle
        )

        MiniGameItemHelper.setMiniGameUsage(binding.gamePlayCount, game)

        game.customPageTrackData = createTrackData()

        DownloadItemUtils.setOnClickListener(
            binding.root.context,
            binding.downloadBtn,
            game,
            position,
            adapter,
            entrance,
            location = "",
            traceEvent = exposureEvent
        ) {
            childEventHelper.onDownloadButtonClick(childPosition, game)
        }
        DownloadItemUtils.updateItem(
            binding.root.context,
            game,
            GameViewHolder(binding.root).apply {
                gameDownloadBtn = binding.downloadBtn
                multiVersionDownloadTv = binding.multiVersionDownloadTv
                gameDownloadTips = binding.downloadTipsLottie
            },
            false
        )
        binding.downloadBtn.putWidgetBusinessName("首页游戏大图样式")
        binding.downloadBtn.goneIf(game.homeSetting.downloadBtnSwitch != "on")
        binding.gameRating.goneIf(!(game.commentCount > 3 && game.star >= 7 && game.homeSetting.downloadBtnSwitch == "on"))
        binding.gameRating2.goneIf(!(game.commentCount > 3 && game.star >= 7 && game.homeSetting.downloadBtnSwitch != "on"))
    }

    override fun provideExposureData(): ExposureEvent? {
        return boundedGameEntity?.exposureEvent?.getFreshExposureEvent()
    }

}