package com.gh.common.provider

import com.gh.common.util.NewFlatLogUtils
import com.gh.gamecenter.common.base.GlobalActivityManager
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.entity.LinkEntity
import com.gh.gamecenter.common.exposure.ExposureSource
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.entity.GameUpdateEntity
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.provider.IDownloadButtonClickedProvider
import com.gh.gamecenter.feature.view.DownloadButton
import com.gh.gamecenter.packagehelper.PackageRepository
import com.halo.assistant.HaloApp
import com.lightgame.download.DownloadEntity
import com.lightgame.utils.Utils

@com.therouter.inject.ServiceProvider
class DownloadButtonClickedProviderImpl : IDownloadButtonClickedProvider {
    override fun onClicked(downloadButton: DownloadButton) {
        var gameId = ""
        var gameName = ""
        var gameCategory = ""
        var gameTypeInChinese = ""
        var downloadStatus = ""
        var downloadStatusInChinese = ""
        var gameSchemaType = ""
        var packageName = ""
        var exposureSourceList: List<ExposureSource>? = null
        var customPageTrackData: CustomPageTrackData? = null
        var isAd = false
        var adGroupId = ""
        val pushMessageId = (HaloApp.get(Constants.PUSH_MESSAGE_ID, false) as? String) ?: ""
        val pushLinkId = (HaloApp.get(Constants.PUSH_LINK_ENTITY, false) as? LinkEntity)?.link ?: ""
        val isFromPush = pushMessageId.isNotEmpty()

        val boundedObject = downloadButton.getObject()

        Utils.log("DownloadButtonClickedProviderImpl", "$downloadButton onClicked ${boundedObject?.javaClass}")

        if (boundedObject != null) {
            when (boundedObject) {
                is GameEntity -> {
                    gameId = boundedObject.id
                    gameName = boundedObject.name ?: ""
                    gameCategory = boundedObject.category ?: ""
                    downloadStatus =
                        if (boundedObject.isVGamePreferred()) {
                            "畅玩"
                        } else {
                            if (boundedObject.downloadStatus == "demo") {
                                "试玩"
                            } else {
                                "下载"
                            }
                        }
                    gameTypeInChinese = boundedObject.categoryChinese
                    downloadStatusInChinese = boundedObject.downloadStatusChinese
                    gameSchemaType = boundedObject.gameBitChinese
                    packageName = boundedObject.getUniquePackageName() ?: ""
                    exposureSourceList = boundedObject.exposureEvent?.source
                    customPageTrackData = boundedObject.customPageTrackData
                    isAd = boundedObject.adGroupId.isNotEmpty()
                    adGroupId = boundedObject.adGroupId
                }

                is GameUpdateEntity -> {
                    gameId = boundedObject.id
                    gameName = boundedObject.name ?: ""
                    // 下载管理-更新页面，把下载状态都置为下载
                    downloadStatus = "下载"
                    gameTypeInChinese = boundedObject.categoryChinese
                    downloadStatusInChinese = boundedObject.downloadStatusChinese
                    packageName = boundedObject.packageName
                    exposureSourceList = boundedObject.exposureEvent?.source
                }

                is DownloadEntity -> {
                    gameId = boundedObject.gameId
                    gameName = boundedObject.name ?: ""
                    gameCategory = boundedObject.getGameCategory()
                    downloadStatus = if (boundedObject.asVGame()) "畅玩" else "下载"
                    packageName = boundedObject.packageName
                    exposureSourceList = boundedObject.exposureTrace?.toObject<ExposureEvent>()?.source
                }
            }

            // 上报 UI 状态为启动的点击事件 (样式为启动，或者文案包含启动都算能启动)
            if (downloadButton.buttonStyle == DownloadButton.ButtonStyle.LAUNCH_OR_OPEN
                || downloadButton.text.contains("启动")
            ) {

                // boundedObject 里找不到游戏类型时，尝试从已安装列表中获取
                if (gameCategory.isEmpty() && packageName.isNotEmpty()) {
                    gameCategory =
                        PackageRepository.gameInstalled.find { it.packageName == packageName }?.category ?: ""
                }

                NewFlatLogUtils.logGameLaunchButtonClicked(
                    gameId = gameId,
                    gameName = gameName,
                    location = downloadButton.getWidgetBusinessName(),
                    gameCategory = gameCategory,
                    downloadStatus = downloadStatus
                )
            }

            // 预约状态不上报
            if (downloadButton.buttonStyle == DownloadButton.ButtonStyle.NORMAL
                || downloadButton.buttonStyle == DownloadButton.ButtonStyle.PLUGIN
            ) {

                val text = downloadButton.text.ifEmpty {
                    downloadButton.getTag(com.gh.gamecenter.feature.R.string.download) ?: ""
                }.toString()

                val downloadType = if (text.contains("畅玩")) {
                    "畅玩下载"
                } else {
                    "本地下载"
                }

                // 小游戏的启动不需要上报下载点击事件
                // @see https://jira.shanqu.cc/browse/GHZSCY-7013 & https://jira.shanqu.cc/browse/GHZSCY-7918
                if (boundedObject is GameEntity
                    && (boundedObject.isMiniGame() || boundedObject.isDspGame)
                ) {
                    return
                }

                // 上报神策点击事件
                val customPageKV = customPageTrackData?.toKV() ?: arrayOf()
                SensorsBridge.trackEventWithExposureSource(
                    "DownLoadbuttonClick",
                    exposureSourceList,
                    "game_id", gameId,
                    "game_name", gameName,
                    "game_type", gameTypeInChinese,
                    "download_status", downloadStatusInChinese,
                    "button_name", text,
                    "game_schema_type", gameSchemaType,
                    "download_type", downloadType,
                    "page_name", GlobalActivityManager.getCurrentPageEntity().pageName,
                    "page_id", GlobalActivityManager.getCurrentPageEntity().pageId,
                    "page_business_id", GlobalActivityManager.getCurrentPageEntity().pageBusinessId,
                    "last_page_name", GlobalActivityManager.getLastPageEntity().pageName,
                    "last_page_id", GlobalActivityManager.getLastPageEntity().pageId,
                    "last_page_business_id", GlobalActivityManager.getLastPageEntity().pageBusinessId,
                    "is_ad", isAd.toString(),
                    "ad_group_id", adGroupId,
                    "is_from_push_notifications", isFromPush,
                    "message_id", pushMessageId,
                    "link_id", pushLinkId,
                    *customPageKV
                )
            }
        }
    }

}