package com.gh.gamecenter.search

import android.content.Context
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.gh.common.util.AdHelper
import com.gh.common.util.DirectUtils
import com.gh.common.util.NewFlatLogUtils
import com.gh.gamecenter.R
import com.gh.gamecenter.SearchActivity
import com.gh.gamecenter.common.base.GlobalActivityManager
import com.gh.gamecenter.common.exposure.ExposureSource
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.common.view.DrawableView
import com.gh.gamecenter.core.runOnIoThread
import com.gh.gamecenter.databinding.SearchGameIndexItemBinding
import com.gh.gamecenter.databinding.SearchGameItemBinding
import com.gh.gamecenter.databinding.SearchSubjectItemBinding
import com.gh.gamecenter.db.ISearchHistoryDao
import com.gh.gamecenter.entity.SubjectData
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.subject.SubjectActivity

class SearchGameIndexItemViewHolder(var binding: SearchGameIndexItemBinding)
    : RecyclerView.ViewHolder(binding.root), IExposureProvider {

    private var boundedGameEntity: GameEntity? = null

    var contentTag: GameEntity.ContentTag? = null

    fun bindData(game: GameEntity) {
        boundedGameEntity = game
    }

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

    companion object {

        fun initServerType(gameEntity: GameEntity, binding: SearchGameItemBinding) {
            val serverLabel = gameEntity.serverLabel
            when {
                gameEntity.test != null -> {
                    binding.gameKaifuType.visibility = View.GONE
                    binding.gameKaifuType.text = ""
                }

                serverLabel != null && !gameEntity.advanceDownload -> {
                    binding.gameKaifuType.visibility = View.VISIBLE
                    binding.gameKaifuType.text = serverLabel.value
                    if (gameEntity.isUseDefaultServerStyle()) {
                        binding.gameKaifuType.background =
                            com.gh.gamecenter.feature.R.drawable.server_label_default_bg.toDrawable(binding.root.context)
                        binding.gameKaifuType.setTextColor(
                            com.gh.gamecenter.common.R.color.text_secondary.toColor(
                                binding.root.context
                            )
                        )
                    } else {
                        binding.gameKaifuType.background =
                            DrawableView.getServerDrawable(serverLabel.color)
                        binding.gameKaifuType.setTextColor(com.gh.gamecenter.common.R.color.white.toColor(binding.root.context))
                    }
                }

                else -> binding.gameKaifuType.visibility = View.GONE
            }

            // 由于RecyclerView的复用机制 需要每次测量gameName的宽
            binding.gameName.requestLayout()
        }
    }
}

class SearchSubjectItemViewHolder(var binding: SearchSubjectItemBinding) : RecyclerView.ViewHolder(binding.root) {
    fun bindSubjectItem(
        context: Context,
        itemData: SearchItemData,
        type: String,
        key: String,
        dao: ISearchHistoryDao? = null,
        sourceEntrance: String
    ) {
        val entity = itemData.subject ?: return

        runOnIoThread(isLightWeightTask = true) {
            for ((index, game) in entity.getFilterGame().withIndex()) {
                game.sequence = index
                game.outerSequence = adapterPosition
                game.isAdData = entity.adIconActive
                game.subjectName = entity.name
                game.subjectId = entity.columnId
                game.searchKey = key

                val exposureSources = arrayListOf<ExposureSource>().apply {
                    add(ExposureSource("首页搜索"))
                    add(ExposureSource(type, key))
                    add(
                        ExposureSource(
                            if (entity.isDspSubject) "dsp广告专题" else "专题",
                            "${entity.name}+${entity.columnId}"
                        )
                    )
                }
                val exposureEvent = ExposureEvent.createEvent(game, exposureSources)
                exposureEvent.payload.searchContent = key
                game.exposureEvent = exposureEvent

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

        binding.run {
            subjectRv.layoutManager = LinearLayoutManager(context, RecyclerView.HORIZONTAL, false)
            subjectRv.adapter = SearchSubjectAdapter(
                context = context,
                mList = entity.getFilterGame(),
                mColumnId = entity.columnId,
                mColumnName = entity.name,
                mEntrance = "($type-专题)",
                mKey = key,
                isDspGame = entity.isDspSubject,
                showDownload = entity.showDownload
            ) {
                dao?.add(key)
                if (itemData.adConfig != null) {
                    NewFlatLogUtils.logClickGameAd(
                        itemData.adConfig.id,
                        itemData.adConfig.name,
                        "游戏搜索",
                        itemData.adConfig.typeChinese,
                        itemData.adConfig.ownerAd?.id ?: "",
                        itemData.adConfig.ownerAd?.sourceName ?: "",
                        it.id,
                        it.name ?: ""
                    )
                }

                if (!it.isMiniGame()) {
                    SensorsBridge.trackColumnClick(
                        location = "游戏搜索",
                        gameColumnId = entity.columnId,
                        gameColumnName = entity.name,
                        gameId = it.id,
                        gameName = it.name ?: "",
                        text = "游戏",
                        adGroupId = it.adGroupId
                    )
                }

                if (it.isMiniGame()) {
                    SensorsBridge.trackMiniGameSearchResultClick(
                        GlobalActivityManager.getCurrentPageEntity().pageId,
                        GlobalActivityManager.getCurrentPageEntity().pageName,
                        sourceEntrance,
                        key,
                        SearchActivity.toTrackSearchType(type),
                        it.id,
                        it.name ?: "",
                        it.categoryChinese,
                        bindingAdapterPosition
                    )
                } else {
                    SensorsBridge.trackGameSearchResultClick(
                        GlobalActivityManager.getCurrentPageEntity().pageId,
                        GlobalActivityManager.getCurrentPageEntity().pageName,
                        sourceEntrance,
                        key,
                        SearchActivity.toTrackSearchType(type),
                        it.id,
                        it.name ?: "",
                        it.categoryChinese,
                        bindingAdapterPosition,
                        it.adGroupId
                    )
                }
            }
            headContainer.adLabelTv.goneIf(!entity.adIconActive)
            headContainer.headTitle.text = entity.name

            if (entity.isDspSubject) {
                headContainer.headActionTv.text = ""
                headContainer.headActionTv.setOnClickListener {  }
            } else {
                headContainer.headActionTv.text = "全部"
                headContainer.headActionTv.setTextColor(com.gh.gamecenter.common.R.color.text_theme.toColor(context))
                headContainer.headActionTv.setDrawableEnd(R.drawable.ic_home_head_arrow.toDrawable(context))
                headContainer.headActionTv.setOnClickListener {
                    dao?.add(key)
                    if (entity.columnId.isNotEmpty()) {
                        DirectUtils.directToSubject(
                            context,
                            entity.columnId,
                            entity.name,
                            "($type-专题)",
                            subjectType = if (entity.isWGameSubjectCPM) {
                                SubjectData.SubjectType.WECHAT_GAME_CPM
                            } else {
                                SubjectData.SubjectType.NORMAL
                            }
                        )
                        SensorsBridge.trackGameSearchResultClick(
                            GlobalActivityManager.getCurrentPageEntity().pageId,
                            GlobalActivityManager.getCurrentPageEntity().pageName,
                            sourceEntrance,
                            key,
                            SearchActivity.toTrackSearchType(type),
                            "",
                            "",
                            "",
                            bindingAdapterPosition,
                            ""
                        )
                    } else if (entity.adId.isNotEmpty() && entity.codeId.isNotEmpty()) {
                        SubjectActivity.startAdSubjectActivity(
                            context,
                            entity.adId,
                            entity.codeId,
                            entity.name,
                            entity.adIconActive,
                            null,
                            "($type-专题)"
                        )
                    }
                    SensorsBridge.trackColumnClick(
                        location = "游戏搜索",
                        gameColumnId = entity.columnId,
                        gameColumnName = entity.name,
                        text = "右上角",
                        buttonType = "全部",
                        adGroupId = ""
                    )
                }
            }
        }
    }
}