package com.base.filerecoveryrecyclebin.ads.admob

import android.annotation.SuppressLint
import android.app.Activity
import android.app.Dialog
import android.os.CountDownTimer
import android.widget.Toast
import com.base.filerecoveryrecyclebin.BuildConfig
import com.base.filerecoveryrecyclebin.R
import com.base.filerecoveryrecyclebin.ads.AdDisplayUtils
import com.base.filerecoveryrecyclebin.ads.AdmobCommonUtils.isMultiClick
import com.base.filerecoveryrecyclebin.ads.admob.AdmobEvent.clickAd
import com.base.filerecoveryrecyclebin.ads.admob.AdmobEvent.pullAd
import com.base.filerecoveryrecyclebin.ads.admob.AdmobEvent.showAd
import com.base.filerecoveryrecyclebin.help.BaseApplication
import com.base.filerecoveryrecyclebin.help.ConfigHelper
import com.base.filerecoveryrecyclebin.utils.AppPreferences
import com.base.filerecoveryrecyclebin.utils.EventUtils
import com.base.filerecoveryrecyclebin.view.CustomDialog
import com.google.android.gms.ads.AdError
import com.google.android.gms.ads.AdRequest
import com.google.android.gms.ads.FullScreenContentCallback
import com.google.android.gms.ads.LoadAdError
import com.google.android.gms.ads.interstitial.InterstitialAd
import com.google.android.gms.ads.interstitial.InterstitialAdLoadCallback
import org.json.JSONObject
import java.util.UUID

object AdmobInterstitialUtils {

    private var interAd: InterstitialAd? = null
    private var interLoadTime = Long.MAX_VALUE
    private var adLastDisplayTime: Long = 0
    private val mRequest = AdRequest.Builder().build()

    @SuppressLint("StaticFieldLeak")
    private var customDialog: CustomDialog? = null

    private fun isAdExpired(): Boolean {
        return System.currentTimeMillis() - interLoadTime > 1000 * 60 * 60
    }

    fun showInterAdSp(): Boolean {
        val isDeleteInterAd = AppPreferences.getInstance().getString("isDeleteInterAd", "0").toInt()
        //1要看插屏 0不看
        return isDeleteInterAd == 1
    }

    fun showInterstitialAd(
        activity: Activity,
        isReLoadAd: Boolean = false,
        isShowDialog: Boolean = true,
        onHidden: (() -> Unit)? = null
    ) {

        if (activity.isFinishing || activity.isDestroyed) {
            return
        }
        val obj1 = JSONObject()
        obj1.put("ad_unit", "interAd")
        EventUtils.event("ad_prepare_show", ext = obj1)

        if (isAdExpired()) {
            val obj2 = JSONObject()
            obj2.put("ad_unit", "interAd")
            EventUtils.event("ad_expire", ext = obj2)
            interAd = null
            loadInterstitialAd(activity)
            onHidden?.invoke()
            return
        }

        if (!AdDisplayUtils.getInstance().shouldShowAd()) {
            onHidden?.invoke()
            return
        }

        if (interAd != null) {
            showIntervalDialogAndShowAd(activity, isShowDialog, onHidden, 2)
        } else {
            showAdDialogAndLoadInterstitial(activity, isReLoadAd, isShowDialog, onHidden)
        }
    }

    fun loadInterstitialAd(activity: Activity, onLoad: (() -> Unit)? = null) {
        if (interAd != null) {
            onLoad?.invoke()
            return
        }
        if (!AdDisplayUtils.getInstance().shouldShowAd()) {
            onLoad?.invoke()
            return
        }
        val reqId = UUID.randomUUID().toString()
        val obj = JSONObject()
        obj.put("req_id", reqId)
        obj.put("ad_type", "interAd")
        obj.put("from", activity.javaClass.simpleName)
        EventUtils.event("ad_pull_start", ext = obj)
        InterstitialAd.load(
            activity,
            ConfigHelper.interAdmobId,
            mRequest,
            object : InterstitialAdLoadCallback() {
                override fun onAdFailedToLoad(p0: LoadAdError) {
                    interAd = null
                    onLoad?.invoke()
                    pullAd(p0.responseInfo, "interAd", p0.message, reqId = reqId)
                    if (BuildConfig.DEBUG) {
                        Toast.makeText(
                            BaseApplication.context,
                            "拉取失败" + p0.message,
                            Toast.LENGTH_SHORT
                        ).show()
                    }

                }

                override fun onAdLoaded(ad: InterstitialAd) {
                    interAd = ad
                    onLoad?.invoke()
                    interLoadTime = System.currentTimeMillis()
                    pullAd(ad.responseInfo, "interAd", reqId = reqId)
                    ad.onPaidEventListener = AdmobEvent.EventOnPaidEventListener(ad)
                }
            })
    }

    private fun showIntervalDialogAndShowAd(
        activity: Activity,
        isShowDialog: Boolean,
        onHidden: (() -> Unit)?,
        interval: Int
    ) {
        if (!isShowDialog) {
            displayInterstitialAd(activity, onHidden)
            return
        }

        if (customDialog != null && customDialog?.isShowing == true) {
            return  // 如果对话框已经显示，则不再显示
        }

        customDialog = CustomDialog(activity, R.layout.dialog_ad_loading)
        customDialog?.setCountdownText(R.id.dialog_ad_loading_text)
        val countdownTimer = object : CountDownTimer((interval * 1000).toLong(), 1000) {
            override fun onTick(millisUntilFinished: Long) {
                val seconds = (millisUntilFinished / 1000).toInt()
                customDialog?.updateCountdownText("Advertising in preparation ($seconds" + "s)...")
            }

            override fun onFinish() {
                displayInterstitialAd(activity, onHidden)
                if (!activity.isDestroyed && !activity.isFinishing) {
                    customDialog?.dismiss()
                }
                customDialog = null
            }
        }
        countdownTimer.start()
        customDialog?.show()
    }

    private fun showAdDialogAndLoadInterstitial(
        activity: Activity,
        isReLoadAd: Boolean,
        isShowDialog: Boolean,
        onHidden: (() -> Unit)?
    ) {
        if (!isShowDialog) {
            return
        }
        var mDialog: Dialog? = null
        if (!activity.isFinishing && !activity.isDestroyed) {
            mDialog = CustomDialog(activity, R.layout.dialog_ad_loading)
            // 设置对话框的样式和内容
            mDialog.show()
        }


        loadInterstitialAd(activity) {
            mDialog?.dismiss()
            if (!isReLoadAd) {
                showInterstitialAd(activity, true, false) {
                    onHidden?.invoke()
                }
            }
        }
        if (isReLoadAd) {
            mDialog?.dismiss()
            onHidden?.invoke()
        }
    }

    private fun displayInterstitialAd(activity: Activity, onHidden: (() -> Unit)? = null) {
        val thisInterAd = interAd
        interAd = null
        thisInterAd?.fullScreenContentCallback = object : FullScreenContentCallback() {
            override fun onAdClicked() {
                clickAd(thisInterAd?.responseInfo, "interAd")
                AdDisplayUtils.getInstance().incrementAdClickCount()
                isMultiClick(thisInterAd)
            }

            override fun onAdDismissedFullScreenContent() {
                interAd = null
                onHidden?.invoke()
                loadInterstitialAd(activity)
            }

            override fun onAdFailedToShowFullScreenContent(p0: AdError) {
                interAd = null
                onHidden?.invoke()
                loadInterstitialAd(activity)
            }

            override fun onAdShowedFullScreenContent() {
                showAd(thisInterAd?.responseInfo, "interAd", activity)
                AdDisplayUtils.getInstance().incrementAdDisplayCount()
                adLastDisplayTime = System.currentTimeMillis() / 1000
            }
        }
        thisInterAd?.show(activity)
    }
}