package com.gamedog.statisticreporter.shushu

import android.os.Bundle
import cn.thinkingdata.analytics.BuildConfig
import cn.thinkingdata.analytics.TDAnalytics
import cn.thinkingdata.analytics.TDAnalytics.TDAutoTrackEventType
import cn.thinkingdata.analytics.TDAnalyticsAPI
import cn.thinkingdata.analytics.TDConfig
import cn.thinkingdata.analytics.ThinkingAnalyticsSDK
import com.ama.core.architecture.BaseApp
import com.google.gson.Gson
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
import org.json.JSONException
import org.json.JSONObject
import kotlin.collections.component1
import kotlin.collections.component2


class ShushuManager private constructor() {
    companion object {
        @Volatile
        private var INSTANCE: ShushuManager? = null

        fun instance(): ShushuManager {
            return INSTANCE ?: synchronized(this) {
                INSTANCE ?: ShushuManager().also { INSTANCE = it }
            }
        }
    }


    private val mAppContext = BaseApp.appContext()
    private val mBgScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
    private val mMainScope = CoroutineScope(SupervisorJob() + Dispatchers.Main)
    private lateinit var mShushuSdk: ThinkingAnalyticsSDK



    fun initShushu(shushuAppId: String, shushuServerUrl: String) {
        mMainScope.launch {
            TDAnalytics.init(mAppContext, shushuAppId, shushuServerUrl)

            val config = TDConfig.getInstance(mAppContext, shushuAppId, shushuServerUrl)
            config.setMode(/*if (BuildConfig.DEBUG) TDConfig.ModeEnum.DEBUG else*/ TDConfig.ModeEnum.NORMAL)
            mShushuSdk = ThinkingAnalyticsSDK.sharedInstance(config)

            configAutoTrack()
        }
    }

    /**
     * 记录用户的具体行为事件。
     * 用户点击按钮、浏览页面、完成购买等。
     */
    fun reportEvent(eventKey: String, params: Map<String, Any>?) {
        val jsonObj = params?.let {
            JSONObject(params)
        }
        TDAnalytics.track(eventKey, jsonObj)
    }



    /**
     * 设置用户属性（会覆盖同名属性）。
     * 记录用户会员等级、姓名等相对固定的属性。
     */
    fun reportUser() {
        try {
            val userProperties = JSONObject().apply {
                put("user_level", "VIP3") // 用户等级
                put("registration_date", "2025-01-01") // 注册日期
                put("total_orders", 15) // 总订单数
            }
            TDAnalytics.userSet(userProperties)
        } catch (e: JSONException) {
            e.printStackTrace()
        }
    }

    /**
     * 设置全局事件属性，自动附加到每个事件。
     * 应用版本号、用户渠道来源等所有事件都带有的属性。
     */
    fun reportSuper() {
        try {
            val superProperties = JSONObject().apply {
                put("app_version", "1.2.0")
                put("channel", "xx应用市场")
                put("user_city", "北京")
            }
            TDAnalytics.setSuperProperties(superProperties)
        } catch (e: JSONException) {
            e.printStackTrace()
        }
    }

    /**
     * 设置账号ID，将后续行为关联到具体用户。
     * 用户登录成功时调用。
     */
    fun reportLogin(userUUID: String) {
        TDAnalytics.login(userUUID)
    }

    //----------------------- PRIVATE ------------------------//

    private fun configAutoTrack() {
        TDAnalytics.enableAutoTrack(TDAutoTrackEventType.APP_START or TDAutoTrackEventType.APP_END or TDAutoTrackEventType.APP_INSTALL )
    }




}




