package com.ritoq.quickphone.business.pangle

import android.app.Activity
import android.os.Bundle
import com.adjust.sdk.Adjust
import com.adjust.sdk.AdjustAdRevenue
import com.bytedance.sdk.openadsdk.api.PangleAd
import com.facebook.appevents.AppEventsLogger
import com.google.firebase.analytics.FirebaseAnalytics
import com.google.firebase.analytics.ktx.analytics
import com.google.firebase.ktx.Firebase
import com.ritoq.quickphone.MyApplication
import com.ritoq.quickphone.business.helper.EventUtils
import com.ritoq.quickphone.utils.AppPreferences
import com.ritoq.quickphone.utils.LogEx
import org.json.JSONObject
import java.math.BigDecimal
import java.util.Currency
import kotlin.apply
import kotlin.jvm.javaClass
import kotlin.text.toDouble
import kotlin.text.uppercase


var pangeleCache = 0.0f
    get() {
        return AppPreferences.getInstance().getFloat("pangeleCache", field)
    }
    set(value) {
        field = value
        AppPreferences.getInstance().put("pangeleCache", value, true)
    }

object PangleEvent {

    private val TAG = "PangleEvent"

    fun eventPangleAd(ac: Activity, ad: PangleAd) {

        val showEcpm = ad.pagRevenueInfo?.showEcpm
        showEcpm ?: return
        val from = ac.javaClass.simpleName

        val adnName = showEcpm.adnName

        //Price per thousand impressions, in cents,前次展示加个,美分单位
        val ecpm = showEcpm.cpm

        //The currency of the CPM
        val currency = showEcpm.currency

        //Pangle Placament ID
        val adUnit = showEcpm.adUnit

        //Network Placement ID
        val placementId = showEcpm.placement

        //Country of the ads
        val country = showEcpm.country

        //Format of the ads
        val format = showEcpm.adFormat

        //Whether is bidding or waterfall
        val biddingOrWaterfall = showEcpm.biddingType

        //Price of the ad
        val price = showEcpm.revenue

        //Precision of the ad
        val precision = showEcpm.precision

        //Detailed segment ID of the ad
        val segmentId = showEcpm.segmentID

        LogEx.logDebug(TAG, "from=$from ecpm=$ecpm currency=$currency ad_unit=$adUnit format=$format")

        val obj = JSONObject()
        obj.put("ad_unit", "openAd")
        obj.put("valueMicros", showEcpm.cpm.toDouble() * 10)
        obj.put("currencyCode", showEcpm.currency)
        obj.put("precision", showEcpm.precision)
        EventUtils.event("ad_price", ext = obj)

        val adjustAdRevenue = AdjustAdRevenue("publisher_sdk")
        //5965及以上请除以1000（美金）,5964及以下请除以100000（美分）
        adjustAdRevenue.setRevenue(showEcpm.cpm.toDouble() / 1000f, showEcpm.currency)
        //Optional
        adjustAdRevenue.adRevenueNetwork = showEcpm.adnName
        adjustAdRevenue.adRevenueUnit = showEcpm.adUnit
        adjustAdRevenue.adRevenuePlacement = showEcpm.placement

        Adjust.trackAdRevenue(adjustAdRevenue)

        //fb
        // 1. 安全获取货币代码
        val currencyCode = when {
            // 优先使用ISO 4217代码（如USD/CNY）
            showEcpm.currency.length == 3 -> showEcpm.currency.uppercase()

            // 处理货币符号（如$→USD, ¥→CNY）
            showEcpm.currency == "$" -> "USD"
            showEcpm.currency == "¥" || showEcpm.currency == "￥" -> "CNY"
            showEcpm.currency == "€" -> "EUR"
            showEcpm.currency == "£" -> "GBP"

            // 默认回退方案
            else -> {
                "USD"
            }
        }
        val fbLogger = AppEventsLogger.newLogger(MyApplication.Companion.appContext)
        fbLogger.logPurchase(BigDecimal.valueOf(showEcpm.cpm.toDouble() / 100000), Currency.getInstance(currencyCode))


        //firebase
        val currentImpressionRevenue = showEcpm.cpm.toDouble() / 100000
        Firebase.analytics.logEvent("ad_price", Bundle().apply {
            putDouble("valueMicros", currentImpressionRevenue)
        })

        pangeleCache = pangeleCache + currentImpressionRevenue.toFloat()

        //上报Total_Ads_Revenue_001
        if (pangeleCache >= 0.01) {//如果超过0.01就触发一次tROAS taichi事件
            val roasbundle = Bundle()
            roasbundle.putDouble(FirebaseAnalytics.Param.VALUE, currentImpressionRevenue)
            roasbundle.putString(FirebaseAnalytics.Param.CURRENCY, showEcpm.currency)
            Firebase.analytics.logEvent("Total_Ads_Revenue_001", roasbundle)

            pangeleCache = 0.0f//重新清零，开始计算
        }

    }

    fun eventAdShow(){
        val obj = JSONObject()
        obj.put("ad_unit", "inter")
        EventUtils.event("ad_show", ext = obj)
    }

    fun eventAdClick(){
        val obj = JSONObject()
        obj.put("ad_unit", "inter")
        EventUtils.event("ad_click", ext = obj)
    }

    fun eventAdPullStart(){
        val obj = JSONObject()
        obj.put("ad_unit", "inter")
        EventUtils.event("ad_pull_start", ext = obj)
    }

    fun eventAdPull(error:Any?=null){
        var key = "ad_pull"
        val obj = JSONObject()

        if(error!=null){
            obj.put("errMsg", error.toString())
            obj.put("status", "2")
            key = "ad_pull_error"
        }
        obj.put("ad_unit", "inter")
        EventUtils.event(key, ext = obj)
    }
}