package com.zx.ad

import android.app.Activity
import android.content.Context
import android.content.ContextWrapper
import android.util.Log
import android.widget.FrameLayout
import com.bytedance.sdk.openadsdk.TTAdSdk
import com.zx.ad.callback.AdLoadCallBack
import com.zx.ad.callback.RewardVideoAdListener
import com.zx.ad.callback.SplashAdListener
import com.zx.ad.modulecommon.AdConstant
import com.zx.ad.modulecommon.AdNetConfig
import com.zx.ad.modulecommon.module.AdIdConfig
import com.zx.ad.modulecommon.module.NewsEntity
import com.zx.ad.modulecommon.net.BaseObserver
import com.zx.ad.modulecommon.net.RxSchedulers
import com.zx.ad.modulecommon.net.ZXADClient
import com.zx.ad.platform.ADType
import com.zx.ad.platform.csj.CSJAdManager
import com.zx.ad.platform.gdt.GdtAdManager
import com.zx.ad.platform.ks.KsAdManager
import com.zx.ad.utils.LoadingDialog
import com.zx.ad.utils.LogUtils
import com.zx.ad.utils.Utils

/**
 * @author (wangXuewei)
 * @datetime 2022-05-19 13:47 GMT+8
 * @detail : 广告控制
 */
object AdManager {
    private var TAG = "AdManager"
    private var isLoadReward = false
    private var isLoadSplash = false
    private var mLoading: LoadingDialog? = null
    private fun showLoadIng(activity: Activity) {
        activity.runOnUiThread {
            mLoading = LoadingDialog.getLoadingDialog(activity, "请稍后", true, true)
            mLoading?.setLoading("正在加载 请稍后")
            mLoading?.show()
        }
    }

    private fun dismissLoading() {
        try {
            if (mLoading != null) {
                if (mLoading?.isShowing!!) {
                    val context: Context =
                        (mLoading?.context as ContextWrapper).baseContext
                    if (context is Activity) {
                        if (!(context as Activity).isFinishing() && !(context as Activity).isDestroyed) mLoading?.dismiss()
                    } else {
                        mLoading?.dismiss()
                    }
                }
            }
        } catch (e: Exception) {

        } finally {
        }
    }

    fun init(application: Context, appLs: String) {
        LogUtils.isShowLog(false)
        AdNetConfig.setBase_Url(AdNetConfig.Environment.PRODUCT)
        AdConstant.param.mPacketName = application.packageName
        AdConstant.param.appLs = appLs
        ZXADClient.adApi.getADConfig(AdConstant.param.mPacketName)
            .compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<List<AdIdConfig>?>() {
                override fun onSuccess(result: List<AdIdConfig>?) {
                    if (!result.isNullOrEmpty()) {
                        LogUtils.d("初始化appId:${Utils.obj2Str(result)}")
                        initAd(result, application)
                    } else {
                        LogUtils.d("初始化appId IS NULL")
                    }
                }

                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {
                    LogUtils.d("初始化appId Error code:${code} errorMsg:${errorMsg}")
                }
            })
    }

    private fun initAd(result: List<AdIdConfig>, context: Context) {
        for (i in result.indices) {
            when (result[i].adPlatform) {
                ADType.PLATFORM_AD_TT -> {
                    CSJAdManager.adInit(context, result[i].codeAppId ?: "",null)
                }
                ADType.PLATFORM_AD_KS -> {
                    KsAdManager.adInit(context, result[i].codeAppId ?: "")
                }
                ADType.PLATFORM_AD_GDT -> {
                    GdtAdManager.adInit(context, result[i].codeAppId ?: "")
                }
            }
        }
    }


    fun loadSplashAd(context: Activity, mSplashContainer: FrameLayout, listener: SplashAdListener) {
        if (context.isDestroyed) {
            return
        }
        if (isLoadSplash) {
            Log.d("AdManager", "Splash正在加载..")
            return
        } else {
            isLoadSplash = true
        }
        ZXADClient.adApi.getAds(ADType.AD_SPLASH)
            .compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<List<NewsEntity>?>() {
                override fun onSuccess(result: List<NewsEntity>?) {
                    if (result.isNullOrEmpty()) {
                        isLoadSplash = false
                        listener.onError("loadSplashAd IS NULL")
                    } else {
                        loadingSplashAd(context, result, mSplashContainer, listener)
                    }
                }

                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {
                    isLoadSplash = false
                    listener.onError("loadSplashAd Error code:${code} errorMsg:${errorMsg}")
                }
            })
    }

    private fun loadingSplashAd(
        context: Activity,
        result: List<NewsEntity>,
        mSplashContainer: FrameLayout,
        listener: SplashAdListener
    ) {
        var totalEntity = ArrayList<NewsEntity>()
        totalEntity.add(result[0])
        totalEntity.addAll(result[0].backups)
        LogUtils.d("loadSplashAd totalEntity:${totalEntity.size}")
        var callBack = object : AdLoadCallBack {
            override fun OnAdLoadSuccess(platform: String, entity: NewsEntity) {
                isLoadSplash = false
                when (platform) {
                    ADType.PLATFORM_AD_TT -> {
                        CSJAdManager.showSplashAd(
                            context,
                            entity,
                            mSplashContainer,
                            listener
                        )
                    }
                    ADType.PLATFORM_AD_KS -> {
                        KsAdManager.showSplashAd(
                            context,
                            entity,
                            mSplashContainer,
                            listener
                        )
                    }
                    ADType.PLATFORM_AD_GDT -> {
                        GdtAdManager.showSplashAd(
                            context,
                            entity,
                            mSplashContainer,
                            listener
                        )
                    }
                }
            }

            override fun OnAdLoadFail(errorMsg: String?) {
                LogUtils.e(errorMsg)
                if (totalEntity.isNullOrEmpty()) {
                    isLoadSplash = false
                    listener.onError("loadFail end")
                } else {
                    LogUtils.e("errorMsg:${errorMsg}")
                    var entity = totalEntity[0];
                    totalEntity.removeAt(0)
                    loadAdPlatform(context, entity, ADType.AD_SPLASH, this)
                }
            }
        }
        var entity = totalEntity[0];
        totalEntity.removeAt(0)
        loadAdPlatform(context, entity, ADType.AD_SPLASH, callBack)
    }

    fun loadRewardAd(context: Activity, listener: RewardVideoAdListener) {
        if (context.isFinishing) {
            return
        }
        if (isLoadReward) {
            Log.d("AdManager", "正在加载..")
            return
        } else {
            isLoadReward = true
        }
        showLoadIng(context)
        ZXADClient.adApi.getAds(ADType.AD_REWARD_VIDEO)
            .compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<List<NewsEntity>?>() {
                override fun onSuccess(result: List<NewsEntity>?) {
                    isLoadReward = false
                    if (result.isNullOrEmpty()) {
                        dismissLoading()
                        listener.onRewardVideoAdError("loadRewardAd Config IS NULL")
                    } else {
                        LogUtils.d("loadRewardAd result:${result.size}")
                        loadingRewardAd(context, result, listener)
                    }
                }

                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {
                    isLoadReward = false
                    LogUtils.e("loadSplashAd Error code:${code} errorMsg:${errorMsg}")
                    dismissLoading()
                    listener.onRewardVideoAdError("loadRewardVideoAd Error code:${code} errorMsg:${errorMsg}")
                }
            })
    }

    private fun loadingRewardAd(
        context: Activity,
        result: List<NewsEntity>,
        listener: RewardVideoAdListener
    ) {
        var totalEntity = ArrayList<NewsEntity>()
        totalEntity.add(result[0])
        totalEntity.addAll(result[0].backups)
        var callBack = object : AdLoadCallBack {
            override fun OnAdLoadSuccess(platform: String?, entity: NewsEntity) {
                dismissLoading()
                when (platform) {
                    ADType.PLATFORM_AD_TT -> {
                        CSJAdManager.showRewardVideoAd(
                            context,
                            entity,
                            listener
                        )
                    }
                    ADType.PLATFORM_AD_KS -> {
                        KsAdManager.showRewardVideoAd(
                            context,
                            entity,
                            listener
                        )
                    }
                    ADType.PLATFORM_AD_GDT -> {
                        GdtAdManager.showRewardVideoAd(
                            context,
                            entity,
                            listener
                        )
                    }
                }
            }

            override fun OnAdLoadFail(errorMsg: String?) {
                LogUtils.e("errorMsg:${errorMsg}")
                if (totalEntity.isNullOrEmpty()) {
                    dismissLoading()
                    listener.onRewardVideoAdError("rewardAd loadFail end")
                } else {
                    var entity = totalEntity[0];
                    totalEntity.removeAt(0)
                    loadAdPlatform(context, entity, ADType.AD_REWARD_VIDEO, this)
                }
            }
        }
        var entity = totalEntity[0];
        totalEntity.removeAt(0)
        loadAdPlatform(context, entity, ADType.AD_REWARD_VIDEO, callBack)
    }


    private fun loadAdPlatform(
        context: Context,
        data: NewsEntity,
        slotName: String,
        callBack: AdLoadCallBack
    ) {
        when (data.adPlatform) {
            ADType.PLATFORM_AD_TT -> {
                when (slotName) {
                    ADType.AD_SPLASH -> {
                        CSJAdManager.loadSplashAd(context, data, callBack)
                    }

                    ADType.AD_REWARD_VIDEO -> {
                        CSJAdManager.loadRewardVideoAd(context, data, callBack)
                    }
                    else -> {
                        callBack.OnAdLoadFail("${data.adPlatform}暂不支持的广告类型:${slotName}")
                    }
                }
            }
            ADType.PLATFORM_AD_KS -> {
                when (slotName) {
                    ADType.AD_SPLASH -> {
                        KsAdManager.loadSplashAd(context, data, callBack)
                    }

                    ADType.AD_REWARD_VIDEO -> {
                        KsAdManager.loadRewardVideoAd(context, data, callBack)
                    }
                    else -> {
                        callBack.OnAdLoadFail("${data.adPlatform}暂不支持的广告类型:${slotName}")
                    }
                }
            }
            ADType.PLATFORM_AD_GDT -> {
                when (slotName) {
                    ADType.AD_SPLASH -> {
                        GdtAdManager.loadSplashAd(context, data, callBack)
                    }

                    ADType.AD_REWARD_VIDEO -> {
                        GdtAdManager.loadRewardVideoAd(context, data, callBack)
                    }
                    else -> {
                        callBack.OnAdLoadFail("${data.adPlatform}暂不支持的广告类型:${slotName}")
                    }
                }
            }
            else -> {
                callBack.OnAdLoadFail("暂不支持的广告平台:${data.adPlatform}")
            }
        }
    }

}