package com.gh.gamecenter.search

import android.content.Context
import android.view.ViewGroup
import com.gh.common.util.DownloadItemUtils
import com.gh.gamecenter.GameDetailActivity
import com.gh.gamecenter.adapter.viewholder.GameViewHolder
import com.gh.gamecenter.common.base.GlobalActivityManager
import com.gh.gamecenter.common.utils.SensorsBridge
import com.gh.gamecenter.common.utils.dip2px
import com.gh.gamecenter.common.utils.goneIf
import com.gh.gamecenter.common.utils.toBinding
import com.gh.gamecenter.dsp.DspReportHelper
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.feature.minigame.MiniGameItemHelper
import com.gh.gamecenter.game.horizontal.GameHorizontalSimpleItemViewHolder
import com.gh.gamecenter.gamedetail.dialog.DspGameDetailDialogFragment
import com.lightgame.adapter.BaseRecyclerAdapter
import com.lightgame.download.DownloadEntity
import com.lightgame.utils.Utils

class SearchSubjectAdapter(
    context: Context,
    private val mList: List<GameEntity>,
    private val mColumnId: String,
    private val mColumnName: String,
    private val mEntrance: String,
    private val mKey: String,
    private val isDspGame: Boolean,
    private val showDownload: Boolean,
    private val clickCallback: ((GameEntity) -> Unit),
) : BaseRecyclerAdapter<GameHorizontalSimpleItemViewHolder>(context) {

    override fun getItemCount() = mList.size

    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): GameHorizontalSimpleItemViewHolder {
        return GameHorizontalSimpleItemViewHolder(parent.toBinding())
    }

    override fun onBindViewHolder(
        holder: GameHorizontalSimpleItemViewHolder,
        position: Int,
        payloads: MutableList<Any>
    ) {
        val gameEntity = mList[position]
        val isRefreshDownloadStatus = payloads.any { gameEntity.id == it }

        if (isRefreshDownloadStatus) {
            DownloadItemUtils.updateItem(
                mContext,
                gameEntity,
                GameViewHolder(holder.binding.root).apply {
                    gameDownloadBtn = holder.binding.downloadBtn
                },
            )
        } else {
            super.onBindViewHolder(holder, position, payloads)
        }
    }

    override fun onBindViewHolder(holder: GameHorizontalSimpleItemViewHolder, position: Int) {
        val gameEntity = mList[position]
        holder.bindData(gameEntity)
        holder.binding.run {
            val padR = if (position == itemCount - 1) 16F.dip2px() else 0
            root.setPadding(16F.dip2px(), 0, padR, 0)
            gameIcon.displayGameIcon(gameEntity)
            holder.binding.downloadBtn.goneIf(!showDownload)
            holder.binding.gameName.maxLines = if (showDownload) 1 else 2
            GameHorizontalSimpleItemViewHolder.setHorizontalNameAndGravity(gameName, gameEntity.name)

            if (showDownload) {
                DownloadItemUtils.setOnClickListener(
                    mContext,
                    holder.binding.downloadBtn,
                    gameEntity,
                    position,
                    this@SearchSubjectAdapter,
                    "",
                    location = "",
                    traceEvent = null
                ) {
                    if (gameEntity.isDspGame) {
                        logDspClick("按钮", gameEntity)
                    }
                }

                DownloadItemUtils.updateItem(
                    mContext,
                    gameEntity,
                    GameViewHolder(holder.binding.root).apply {
                        gameDownloadBtn = holder.binding.downloadBtn
                    },
                )
            }

            root.setOnClickListener {
                clickCallback.invoke(gameEntity)

                if (isDspGame) {
                    logDspClick("广告内容", gameEntity)
                }

                if (gameEntity.isMiniGame()) {
                    MiniGameItemHelper.launchMiniGame(gameEntity)
                    MiniGameItemHelper.trackMiniGameClick(
                        gameEntity = gameEntity,
                        gameColumnId = mColumnId,
                        gameColumnName = mColumnName,
                        location = "小游戏搜索结果列表",
                        position = position,
                        searchContent = mKey,
                    )
                } else {
                    if (isDspGame) {
                        DspGameDetailDialogFragment.show(mContext, gameEntity)
                    } else {
                        GameDetailActivity.startGameDetailActivity(mContext, gameEntity.id, mEntrance, gameEntity.exposureEvent)
                    }
                }
            }
        }
    }

    fun notifyItemByDownload(downloadEntity: DownloadEntity?) {
        if (!showDownload) return

        if (downloadEntity == null) {
            notifyDataSetChanged()
        } else {
            mList.forEachIndexed { position, gameEntity ->
                if (downloadEntity.gameId == gameEntity.id) {
                    notifyItemChanged(position, gameEntity.id)
                    return
                }
            }
        }
    }

    fun notifyChildItem(packageName: String) {
        if (!showDownload) return

        mList.forEachIndexed { position, gameEntity ->
            gameEntity.getApk().forEach { apkEntity ->
                if (apkEntity.packageName == packageName) {
                    notifyItemChanged(position)
                    return
                }
            }
        }
    }

    private fun logDspClick(text: String, gameEntity: GameEntity){
        val json = SensorsBridge.trackDspAdClick(
            lastPageName = GlobalActivityManager.getLastPageEntity().pageName,
            lastPageId = GlobalActivityManager.getLastPageEntity().pageId,
            lastPageBusinessId = GlobalActivityManager.getLastPageEntity().pageBusinessId,
            location = "游戏搜索结果列表",
            gameColumnName = mColumnName,
            gameColumnId = mColumnId,
            searchContent = mKey,
            adId = gameEntity.id,
            interactionType = gameEntity.interactionType.toString(),
            wechatAppid = gameEntity.miniGameAppId,
            gameName = gameEntity.name ?: "",
            text = text
        )

        // 先尝试上报 show 再上报 click，保证先 show 后 click (已在 report 方法中进行简单去重处理)
        DspReportHelper.report(gameEntity.showUrl)
        DspReportHelper.report(gameEntity.clickUrl)

        // Parse the JSON string into a JSONObject
        if (json != null) {
            val map = mutableMapOf<String, String>()
            val keys = json.keys() // Returns an Iterator

            while (keys.hasNext()) {
                val key = keys.next()
                try {
                    val value = json.get(key)
                    map[key] = value.toString()
                } catch (e: Exception) {
                    Utils.log("Error parsing JSON key: $key, value: ${json.get(key)}")
                }
            }

            gameEntity.tempDspLogMap = map.toMap() // Return an immutable copy
        }
    }

}