package com.base.appzxhy.business.pangle

import android.app.Activity
import android.os.Bundle
import com.adjust.sdk.Adjust
import com.adjust.sdk.AdjustAdRevenue
import com.adjust.sdk.AdjustConfig
import com.base.appzxhy.MyApplication
import com.base.appzxhy.business.helper.EventUtils
import com.base.appzxhy.utils.AppPreferences
import com.base.appzxhy.utils.LogEx
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 org.json.JSONObject
import java.math.BigDecimal
import java.util.Currency


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(AdjustConfig.AD_REVENUE_SOURCE_PUBLISHER)
        //5965及以上请除以1000（美金）,5964及以下请除以100000（美分）
        adjustAdRevenue.setRevenue(showEcpm.cpm.toDouble() / 1000f, showEcpm.currency)
        //Optional
        adjustAdRevenue.setAdRevenueNetwork(showEcpm.adnName)
        adjustAdRevenue.setAdRevenueUnit(showEcpm.adUnit)
        adjustAdRevenue.setAdRevenuePlacement(showEcpm.placement)

        Adjust.trackAdRevenue(adjustAdRevenue)

        //fb
        val fbLogger = AppEventsLogger.newLogger(MyApplication.Companion.appContext)
        fbLogger.logPurchase(BigDecimal.valueOf(showEcpm.cpm.toDouble() / 100000), Currency.getInstance(showEcpm.currency))


        //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//重新清零，开始计算
        }

    }
}