package com.gh.gamecenter.home

import android.graphics.drawable.ColorDrawable
import android.view.View
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.constraintlayout.widget.ConstraintSet
import androidx.recyclerview.widget.RecyclerView
import com.gh.common.util.DirectUtils
import com.gh.common.util.DownloadItemUtils
import com.gh.gamecenter.GameDetailActivity
import com.gh.gamecenter.R
import com.gh.gamecenter.adapter.viewholder.GameViewHolder
import com.gh.gamecenter.common.base.BaseRecyclerViewHolder
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.core.utils.RandomUtils
import com.gh.gamecenter.databinding.HomeGameItemBinding
import com.gh.gamecenter.entity.SubjectEntity
import com.gh.gamecenter.feature.exposure.ExposureEvent
import com.gh.gamecenter.feature.exposure.ExposureSource
import com.gh.gamecenter.feature.game.GameItemViewHolder
import com.gh.gamecenter.video.detail.VideoDetailContainerViewModel
import com.shuyu.gsyvideoplayer.builder.GSYVideoOptionBuilder
import com.shuyu.gsyvideoplayer.video.base.GSYVideoView

class HomeGameItemViewHolder(val binding: HomeGameItemBinding) : BaseRecyclerViewHolder<Any>(binding.root) {

    fun bindAttachGame(
        holder: HomeGameItemViewHolder,
        subjectEntity: SubjectEntity,
        adapter: RecyclerView.Adapter<out RecyclerView.ViewHolder>,
        mBasicExposureSource: List<ExposureSource>,
        position: Int,
        entrance: String,
        createExposureEventCallback: (ExposureEvent) -> Unit
    ) {
        val game = subjectEntity.linkGame!!
        val topVideo = game.topVideo
        val homeSetting = game.homeSetting
        val displayContent = subjectEntity.displayContent

        game.displayContent = displayContent
        val exposureEvent = ExposureEvent.createEventWithSourceConcat(
            gameEntity = game.apply {
                isAdData = subjectEntity.adIconActive
                outerSequence = position
            },
            basicSource = mBasicExposureSource,
            source = listOf(ExposureSource("游戏", ""))
        )
        createExposureEventCallback.invoke(exposureEvent)
        holder.bindGameInfo(subjectEntity, adapter, position, exposureEvent, entrance)
        holder.binding.gameBrief.text = subjectEntity.recommendText
        holder.binding.gameImage.visibleIf(!(displayContent == "video" && game.topVideo != null))
        holder.binding.autoVideoView.goneIf(displayContent != "video" || game.topVideo == null) {
            if (!holder.binding.autoVideoView.isInPlayingState) {
                GSYVideoOptionBuilder()
                    .setIsTouchWiget(false)
                    .setUrl(topVideo?.url ?: "")
                    .setRotateViewAuto(false)
                    .setCacheWithPlay(true)
                    .setRotateWithSystem(false)
                    .setReleaseWhenLossAudio(true)
                    .setLooping(false)
                    .setShowFullAnimation(false)
                    .build(holder.binding.autoVideoView)
                holder.binding.autoVideoView.updateThumb(topVideo?.poster ?: "")
                holder.binding.autoVideoView.setParamsData(game, homeSetting.placeholderColor)
                holder.binding.autoVideoView.detailBtn?.setOnClickListener {
                    holder.itemView.performClick()
                    holder.binding.autoVideoView.uploadVideoStreamingPlaying("点击遮罩", true)
                }
                holder.binding.autoVideoView.setOnVideoClickListener { holder.itemView.performClick() }
            }
        }

        holder.binding.gameImage.setOnClickListener {
            if (subjectEntity.type == "video") {
                DirectUtils.directToVideoDetail(
                    binding.root.context,
                    subjectEntity.id!!,
                    VideoDetailContainerViewModel.Location.VIDEO_CHOICENESS.value,
                    entrance = "(${entrance}-游戏[" + game.name + "])",
                    path = "${entrance}-内容管理"
                )
            } else {
                GameDetailActivity.startGameDetailActivity(
                    binding.root.context,
                    game.id,
                    "(${entrance}-游戏[" + game.name + "])",
                    exposureEvent
                )
            }
        }
        holder.itemView.setOnClickListener {
            GameDetailActivity.startGameDetailActivity(
                binding.root.context,
                game.id,
                "(${entrance}-游戏[" + game.name + "])",
                exposureEvent
            )
            if (holder.binding.autoVideoView.isInPlayingState) {
                holder.binding.autoVideoView.uploadVideoStreamingPlaying(
                    "游戏详情-播放点击",
                    holder.binding.autoVideoView.detailBtn?.visibility == View.VISIBLE
                )
            } else {
                if (holder.binding.autoVideoView.currentState == GSYVideoView.CURRENT_STATE_AUTO_COMPLETE) {
                    holder.binding.autoVideoView.uploadVideoStreamingPlaying(
                        "游戏详情-完播点击",
                        holder.binding.autoVideoView.detailBtn?.visibility == View.VISIBLE
                    )
                }
            }
        }
    }

    private fun bindGameInfo(
        subjectEntity: SubjectEntity,
        adapter: RecyclerView.Adapter<out RecyclerView.ViewHolder>,
        position: Int,
        exposureEvent: ExposureEvent?,
        entrance: String
    ) {
        val game = subjectEntity.linkGame!!
        binding.gameIcon.displayGameIcon(game)
        binding.gameName.setTextColor(R.color.text_title.toColor(binding.root.context))
        binding.gameBrief.setTextColor(R.color.text_title.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())
        ImageUtils.display(binding.gameImage, game.homeSetting.image)
        binding.gameTags.postDelayed({
            binding.gameTags.visibility = if (game.tagStyle.isNotEmpty()) {
                binding.gameTags.setTags(game.tagStyle)
                View.VISIBLE
            } else View.GONE
        }, 5)
        GameItemViewHolder.initGameSubtitleAndAdLabel(
            game,
            binding.gameSubtitleTv,
            binding.gameNameContainer,
            binding.gameName,
            subjectEntity.adIconActive,
            binding.adLabelTv
        )
        val hierarchy = binding.gameImage.hierarchy
        try {
            hierarchy.setPlaceholderImage(ColorDrawable(game.homeSetting.placeholderColor.hexStringToIntColor()))
        } catch (ignore: Throwable) {
            hierarchy.setPlaceholderImage(RandomUtils.getRandomPlaceholderColor())
        }

        DownloadItemUtils.setOnClickListener(
            binding.root.context,
            binding.downloadBtn,
            game,
            position,
            adapter,
            entrance,
            "",
            exposureEvent
        )
        DownloadItemUtils.updateItem(
            binding.root.context,
            game,
            GameViewHolder(binding.root).apply {
                gameDownloadBtn = binding.downloadBtn
                multiVersionDownloadTv = binding.multiVersionDownloadTv
                gameDownloadTips = binding.downloadTipsLottie
            },
            true
        )
        binding.downloadBtn.goneIf(game.homeSetting.downloadBtnSwitch != "on")
        binding.gameRating.goneIf(!(game.showComment && game.commentCount >= 3 && game.star >= 7 && game.homeSetting.downloadBtnSwitch == "on"))
        binding.gameRating2.goneIf(!(game.showComment && game.commentCount >= 3 && game.star >= 7 && game.homeSetting.downloadBtnSwitch != "on"))
        ConstraintSet().apply {
            clone(binding.gameNameContainer.parent as ConstraintLayout)
            clear(binding.gameNameContainer.id, ConstraintSet.END)
            if (binding.downloadBtn.visibility == View.VISIBLE) {
                connect(binding.gameNameContainer.id, ConstraintSet.END, binding.downloadBtn.id, ConstraintSet.START)
            } else if (binding.gameRating2.visibility == View.VISIBLE) {
                connect(binding.gameNameContainer.id, ConstraintSet.END, binding.gameRating2.id, ConstraintSet.START)
            } else {
                connect(binding.gameNameContainer.id, ConstraintSet.END, ConstraintSet.PARENT_ID, ConstraintSet.END)
            }
            setMargin(binding.gameNameContainer.id, ConstraintSet.END, 8F.dip2px())
            applyTo(binding.gameNameContainer.parent as ConstraintLayout)
        }
    }
}