package com.gh.gamecenter.gamedetail.detail.viewholder

import androidx.core.view.isVisible
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.gh.common.exposure.ExposureManager
import com.gh.common.util.DirectUtils
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.common.view.divider.VerticalDividerItemDecoration
import com.gh.gamecenter.databinding.ItemGameDetailRecyclerViewBinding
import com.gh.gamecenter.entity.SubjectEntity
import com.gh.gamecenter.feature.exposure.ExposureEvent
import com.gh.gamecenter.feature.view.DownloadButton
import com.gh.gamecenter.game.horizontal.GameHorizontalAdapter
import com.gh.gamecenter.game.horizontal.GameHorizontalListType
import com.gh.gamecenter.gamedetail.GameDetailViewModel
import com.gh.gamecenter.gamedetail.entity.GameDetailData
import com.gh.gamecenter.gamedetail.entity.GameDetailRecommendColumn
import kotlin.collections.firstOrNull
import kotlin.collections.withIndex

class GameDetailRecommendColumnItemViewHolder(
    val binding: ItemGameDetailRecyclerViewBinding,
    downloadBtn: DownloadButton?,
    viewModel: GameDetailViewModel
) : BaseGameDetailItemViewHolder(binding.root, downloadBtn, viewModel) {
    override fun bindView(data: GameDetailData) {
        super.bindView(data)
        val columnData = data.recommendColumn ?: return
        binding.run {
            titleTv.setTextColor(com.gh.gamecenter.common.R.color.text_primary.toColor(context))
            moreTv.setTextColor(com.gh.gamecenter.common.R.color.text_theme.toColor(context))
            moreTv.setDrawableEnd(R.drawable.ic_auxiliary_arrow_right_text_theme_12.toDrawable(context))
            titleTv.text = columnData.columnTitle
            moreTv.isEnabled = true
            headPb.isVisible = false
            moreTv.goneIf(columnData.display?.home.isNullOrEmpty()) {
                moreTv.run {
                    text = columnData.display?.home
                    setDebouncedClickListener {
                        NewFlatLogUtils.logGameDetailColumnRecommendUpperRightClick(
                            viewModel.game?.name ?: "",
                            viewModel.game?.id ?: "",
                            columnData.display?.home ?: "",
                            columnData.columnTitle,
                            columnData.columnId,
                            columnData.display?.moreLink?.text ?: "",
                            columnData.display?.moreLink?.type ?: "",
                            columnData.display?.moreLink?.link ?: ""
                        )
                        SensorsBridge.trackGameDetailModuleClick(
                            gameId,
                            gameName,
                            gameType,
                            "右上角",
                            moduleType,
                            columnData.columnTitle,
                            sequence,
                            linkType = columnData.display?.moreLink?.type,
                            linkId = columnData.display?.moreLink?.link,
                            linkText = columnData.display?.moreLink?.text,
                            gameStatus = gameStatus
                        )
                        SensorsBridge.trackColumnClick(
                            location = "游戏详情",
                            gameName = gameName,
                            gameId = gameId,
                            gameColumnName = columnData.columnTitle,
                            gameColumnId = columnData.columnId,
                            linkText = columnData.display?.moreLink?.text ?: "",
                            linkType = columnData.display?.moreLink?.type ?: "",
                            linkId = columnData.display?.moreLink?.link ?: "",
                            text = "右上角",
                            buttonType = columnData.display?.home ?: "",
                            adGroupId = viewModel.game?.adGroupId ?: ""
                        )

                        when (columnData.display?.home) {
                            RIGHT_TOP_CHANGE -> {
                                headPb.isVisible = true
                                moreTv.isEnabled = false
                                viewModel.changeSubjectGame(columnData.columnId, columnData.gameCount) {
                                    headPb.isVisible = false
                                    moreTv.isEnabled = true
                                }
                            }
                            RIGHT_TOP_MORE -> {
                                columnData.display?.moreLink?.let {
                                    DirectUtils.directToLinkPage(
                                        context,
                                        it,
                                        viewModel.entrance ?: "",
                                        "游戏详情[${viewModel.game?.name ?: ""}]:专题游戏单推荐"
                                    )
                                }
                            }
                            else -> {
                                DirectUtils.directToSubject(context, columnData.columnId, columnData.columnTitle, "游戏详情", null)
                            }
                        }
                    }
                }
            }

            if (recyclerView.adapter !is GameHorizontalAdapter) {
                recyclerView.run {
                    isNestedScrollingEnabled = false
                    (itemAnimator as DefaultItemAnimator).supportsChangeAnimations = false
                    layoutManager = LinearLayoutManager(context, RecyclerView.HORIZONTAL, false)
                    val subjectEntity = SubjectEntity().apply {
                        id = columnData.columnId
                        name = columnData.columnTitle
                        this.data = columnData.columnGames
                    }
                    val subjectAdapter =
                        GameHorizontalAdapter(
                            context,
                            subjectEntity,
                            GameHorizontalListType.GameDetailHorizontalType,
                            gameDetailTrackData = baseTrackData.apply {
                                moduleName = columnData.columnTitle
                            },
                            getGameStatus = { gameStatus })
                    subjectAdapter.gameName = viewModel.game?.name ?: ""
                    subjectAdapter.game = viewModel.game
                    subjectAdapter.gameId = viewModel.game?.id ?: ""
                    subjectAdapter.entrance = viewModel.entrance ?: ""
                    subjectAdapter.path = "专题游戏单推荐"
                    subjectAdapter.exposureEventList = createAndLogExposureEventList(columnData)
                    (itemAnimator as DefaultItemAnimator).supportsChangeAnimations = false
                    val itemDecoration = VerticalDividerItemDecoration.Builder(context)
                        .size(8F.dip2px())
                        .color(com.gh.gamecenter.common.R.color.transparent.toColor(context))
                        .build()
                    addItemDecoration(itemDecoration)
                    adapter = subjectAdapter
                }
            } else {
                if (columnData.columnId != recyclerView.tag) {
                    val subjectEntity = SubjectEntity().apply {
                        id = columnData.columnId
                        name = columnData.columnTitle
                        this.data = columnData.columnGames
                    }
                    (recyclerView.adapter as? GameHorizontalAdapter)?.let {
                        it.subjectEntity = subjectEntity
                        it.exposureEventList = createAndLogExposureEventList(columnData)
                    }
                }
                recyclerView.adapter?.run {
                    notifyItemRangeChanged(0, itemCount)
                }
            }
            recyclerView.tag = columnData.columnId
        }
    }

    private fun createAndLogExposureEventList(columnData: GameDetailRecommendColumn): ArrayList<ExposureEvent> {
        val exposureEventList = arrayListOf<ExposureEvent>()
        for ((index, game) in columnData.columnGames?.withIndex() ?: return arrayListOf()) {
            game.sequence = index
            val event = ExposureEvent.createEvent(
                gameEntity = game,
                source = listOf(
                    ExposureSource("游戏详情", viewModel.game?.name ?: ""),
                    ExposureSource("专题推荐", columnData.columnTitle)
                )
            )
            exposureEventList.add(event)
            ExposureManager.log(event)
        }
        return exposureEventList
    }

    companion object {
        const val RIGHT_TOP_CHANGE = "换一批"
        const val RIGHT_TOP_MORE = "更多"
        const val RIGHT_TOP_ALL = "全部"
    }
}