package com.ym.admodule.config

import android.app.Activity
import android.app.Application
import android.content.Context
import android.content.ContextWrapper
import android.os.Build
import android.text.TextUtils
import android.view.ViewGroup
import android.webkit.WebView
import android.widget.FrameLayout
import android.widget.TextView
import com.`fun`.xm.ad.FSAD
import com.baidu.mobads.AdView
import com.bytedance.sdk.openadsdk.TTAdConfig
import com.bytedance.sdk.openadsdk.TTAdConstant
import com.bytedance.sdk.openadsdk.TTAdSdk
import com.kwad.sdk.api.KsAdSDK
import com.kwad.sdk.api.SdkConfig
import com.qq.e.comm.managers.GDTADManager
import com.sigmob.windad.WindAdOptions
import com.sigmob.windad.WindAds
import com.wannuosili.sdk.WNAdConfig
import com.wannuosili.sdk.WNAdSdk
import com.ym.admodule.BuildConfig
import com.ym.admodule.bd.BDADUtils
import com.ym.admodule.config.AdCache.TIME_OUT
import com.ym.admodule.csj.TTADUtils
import com.ym.admodule.fs.FunShionUtils
import com.ym.admodule.gdt.GDTAdUtils
import com.ym.admodule.ks.KSADUtils
import com.ym.admodule.listener.ZXADDrawListener
import com.ym.admodule.listener.ZXADFullVideoListener
import com.ym.admodule.listener.ZXADSplashListener
import com.ym.admodule.listener.ZXADVideoListener
import com.ym.admodule.news.NewsUtils
import com.ym.admodule.sh.SHADUtils
import com.ym.admodule.sm.SMADUtils
import com.ym.admodule.ylb.WNManager
import com.ym.modulecommon.AdConstant
import com.ym.modulecommon.module.AdIdConfig
import com.ym.modulecommon.module.NewsEntity
import com.ym.modulecommon.net.BaseObserver
import com.ym.modulecommon.net.RxSchedulers
import com.ym.modulecommon.net.ZXADClient
import com.ym.modulecommon.utils.*
import com.ym.modulecommon.weiget.LoadingDialog
import java.util.*
import kotlin.concurrent.thread
import com.ym.admodule.config.ZXADCallback as ZXADCallback1


/**
 * 广告的管理类
 */
object AdManager {


    var isInit = false
    var isLoadReward = false
    var isLoadFull = 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 DissmissLoadIng() {
        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()
                    }
                }
//                mLoading = null
            }
        } catch (e: Exception) {

        } finally {
//            mLoading = null
        }
    }

    fun init(application: Application, appls: String) {
        val config = LogUtils.getConfig()
        config.logSwitch = BuildConfig.DEBUG

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            val processName = Application.getProcessName()
            if (application.packageName != processName) {
                WebView.setDataDirectorySuffix(processName)
            }
        }
        AdConstant.param.appLs = appls
        ZXADClient.adApi.getADConfig(application.packageName)
            .compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<List<AdIdConfig>?>() {
                override fun onSuccess(result: List<AdIdConfig>?) {
                    if (result != null && result.isNotEmpty()) {
                        LogUtils.d(TAG, "初始化appId:${Utils.obj2Str(result)}")
                        val instances = ZXADConfig.getInstances()
                        for (value in result) {
                            when (value.adPlatform) {
                                ZXADType.PLANTFORM_AD_TT -> {
                                    if (!TextUtils.isEmpty(value.codeAppId)) {
                                        instances.csjId(value.codeAppId!!)
                                    }
                                }

                                ZXADType.PLANTFORM_AD_GDT -> {
                                    if (!TextUtils.isEmpty(value.codeAppId)) {
                                        instances.gdtId(value.codeAppId!!)
                                    }
                                }

                                ZXADType.PLANTFORM_AD_KUS -> {
                                    if (!TextUtils.isEmpty(value.codeAppId)) {
                                        instances.ksId(value.codeAppId!!)
                                    }
                                }

                                ZXADType.PLANTFORM_SH_YLB -> {
                                    if (!TextUtils.isEmpty(value.codeAppId)) {
                                        instances.ylbId(value.codeAppId!!)
                                    }
                                }

                                ZXADType.PLANTFORM_AD_SIGNMOB -> {
                                    if (!TextUtils.isEmpty(value.codeAppId) && !TextUtils.isEmpty(
                                            value.codeAppKey
                                        )
                                    ) {
                                        instances.signMob(value.codeAppId!!, value.codeAppKey!!)
                                    }
                                }


                                ZXADType.PLANTFORM_AD_BD -> {
                                    if (!TextUtils.isEmpty(value.codeAppId)) {
                                        instances.bdId(value.codeAppId!!)
                                    }
                                }
//                                ZXADType.PLANTFORM_AD_HL -> {
//                                    if (!TextUtils.isEmpty(value.codeAppId) && !TextUtils.isEmpty(
//                                            value.codeAppKey
//                                        )
//                                    ) {
//                                        instances.huiLiang(value.codeAppId!!, value.codeAppKey!!)
//                                    }
//                                }

                                ZXADType.PLANTFORM_AD_FENGXING -> {
                                    FSAD.init(application)  // 初始化风行广告sdk
                                }
                            }
                        }

                        init(application, instances)

                    }
                }

                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {

                }
            })
    }

    private val TAG = "AdManager"

    fun init(context: Application, adconfig: ZXADConfig) {
        //广点通广告
        if (context == null) {
            try {
                throw RuntimeException("ZXAD:===========初始化失败  context不能为null")
            } catch (e: Exception) {

            }
        }

        if (!(context is Application)) {
            try {
                throw RuntimeException("ZXAD:===========初始化失败  请在application中初始化")
            } catch (e: Exception) {

            }
        }
        if (adconfig == null) {
            try {
                throw RuntimeException("ZXAD:===========初始化失败")
            } catch (e: Exception) {

            }
        }
        //广点通初始化
        if (!TextUtils.isEmpty(adconfig.GDT_AD_APP_ID)) {
            GDTADManager.getInstance().initWith(context, adconfig.GDT_AD_APP_ID)
        }
        //百度初始化
        if (!TextUtils.isEmpty(adconfig.BAIDU_APP_ID)) {
            AdView.setAppSid(context, adconfig.BAIDU_APP_ID);
        }
        //穿山甲广告初始化
        if (!TextUtils.isEmpty(adconfig.TT_AD_APP_ID)) {
            TTAdSdk.init(
                context,
                TTAdConfig.Builder()
                    .appId(adconfig.TT_AD_APP_ID)
                    .useTextureView(adconfig.useTextureView) //使用TextureView控件播放视频,默认为SurfaceView,当有SurfaceView冲突的场景，可以使用TextureView
                    .appName(adconfig.appName)
                    .titleBarTheme(adconfig.titleBarTheme)
                    .allowShowNotify(adconfig.allowShowNotify) //是否允许sdk展示通知栏提示
                    .allowShowPageWhenScreenLock(adconfig.allowShowPageWhenScreenLock) //是否在锁屏场景支持展示广告落地页
                    .debug(adconfig.IS_DEUG) //测试阶段打开，可以通过日志排查问题，上线时去除该调用
                    .directDownloadNetworkType(
                        TTAdConstant.NETWORK_STATE_WIFI,
                        TTAdConstant.NETWORK_STATE_4G
                    ) //允许直接下载的网络状态集合
                    .supportMultiProcess(adconfig.supportMultiProcess) //是否支持多进程，true支持
                    //.httpStack(new MyOkStack3())//自定义网络库，demo中给出了okhttp3版本的样例，其余请自行开发或者咨询工作人员。
                    .build()


            )
            LogUtils.d("TT_VERSION", TTAdSdk.getAdManager().sdkVersion)
        }


        //SignMob广告 初始化
        if (!TextUtils.isEmpty(adconfig.SIGNMOB_APP_ID) && !TextUtils.isEmpty(adconfig.SIGNMOB_APP_KEY)) {
            val ads = WindAds.sharedAds()
            ads.startWithOptions(
                context,
                WindAdOptions(adconfig.SIGNMOB_APP_ID, adconfig.SIGNMOB_APP_KEY, false)
            )
        }

        //优量宝初始化
        if (!TextUtils.isEmpty(adconfig.YLB_APP_ID)) {
            WNAdSdk.initialize(
                WNAdConfig.Builder()
                    .setAppId(adconfig.YLB_APP_ID)
                    .setDebug(adconfig.IS_DEUG) // 设置是否是debug模式
                    .setContext(context) // 上下文
                    .build()
            )
        }
        //快手初始化
        if (!TextUtils.isEmpty(adconfig.KS_APP_ID)) {
            KsAdSDK.init(
                context, SdkConfig.Builder()
                    .appId(adconfig.KS_APP_ID) // 测试aapId，请联系快⼿平台申请正式AppId，必填
                    .appName("") // 测试appName，请填写您应⽤的名称，
                    .showNotification(true) // 是否展示下载通知栏
                    .debug(adconfig.IS_DEUG) // 是否开启sdk 调试⽇志 可选
                    .build()
            );
        }

//        //汇量初始化
//        if (!TextUtils.isEmpty(adconfig.HL_APP_ID) && !TextUtils.isEmpty(adconfig.HL_APP_KEY)) {
//            MIntegralSDKManager.getInstance().initialize(
//                context,
//                adconfig.HL_APP_KEY,
//                adconfig.HL_APP_ID,
//                true,
//                null,
//                object : MIntegralSDKManager.MIntegralSDKInitializeListener {
//                    override fun onInitializeSuccess(
//                        appKey: String?,
//                        appID: String?
//                    ) {
//                        LogUtils.e("SDKInitStatus", "onInitSuccess")
//                    }
//
//                    override fun onInitializeFailure(message: String?) {
//                        LogUtils.e("SDKInitStatus", "onInitFail")
//                    }
//                })
//        }


        isInit = true
    }


    fun loadSplashAd(type: String) {
        if (!isInit) {
            return
        }
        ZXADClient.adApi.getAd(type).compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<List<NewsEntity>>() {
                override fun onSuccess(result: List<NewsEntity>) {
                    if (result != null && result.isNotEmpty()) {
                        var arrayList = result as ArrayList
                        var newsEntity = arrayList[0]
                        AdCache.splashCacheList.put(type, newsEntity)
                        AdCache.splashTime.put(type, System.currentTimeMillis().toString())
                    }
                }

                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {
                }
            })

    }


    fun showSplashAd(
        activity: Activity,
        type: String,
        actionName: String,
        skipview: TextView?,
        container: FrameLayout,
        zxadListener: ZXADSplashListener
    ) {
        if (!isInit) {
            zxadListener.onError("没有初始化")
            return
        }
        val newsEntity = AdCache.splashCacheList.get(type)
        val time = AdCache.splashTime.get(type)
        if (newsEntity != null && time != null && (System.currentTimeMillis() - time!!.toLong()) < TIME_OUT) {
            var totalEntity = java.util.ArrayList<NewsEntity>()
            val backups = newsEntity.backups
            totalEntity.add(newsEntity)
            if (backups != null && backups.isNotEmpty()) {
                totalEntity.addAll(backups)
            }
            var cacheNewsEntity = totalEntity[0]

            cacheNewsEntity.actionName = actionName
            var callback: ZXADCallback1 = object : ZXADCallback1 {
                override fun onAdSuccess() {
                    LogUtils.e(TAG, "加载开屏广告成功 onAdSuccess  结束")
                    AdCache.splashCacheList.remove(type)
                }

                override fun onAdFail() {
                    LogUtils.e(TAG, "加载开屏流广告失败 onAdFail ")
                    // 执行保底
                    if (totalEntity.size > 0) {
                        LogUtils.e(TAG, "加载开屏流广告失败 onAdFail  执行保底策略")
                        cacheNewsEntity = totalEntity[0]
                        cacheNewsEntity.actionName = actionName
                        loadSplashAd(
                            cacheNewsEntity,
                            activity,
                            container,
                            zxadListener,
                            skipview,
                            this
                        )
                        totalEntity.removeAt(0)
                    } else {
                        AdCache.splashCacheList.remove(type)
                    }
                }
            }

            loadSplashAd(
                cacheNewsEntity,
                activity,
                container,
                zxadListener,
                skipview,
                callback
            )


        } else {
            loadSplashAd(
                activity,

                type,
                actionName,
                skipview,
                container,
                zxadListener
            )
        }
        FirstReportUtils.firstReport()//首次上报
    }


    //开屏广告
    fun loadSplashAd(
        activity: Activity,
        type: String,
        actionName: String,
        skipview: TextView?,
        container: FrameLayout,
        zxadListener: ZXADSplashListener
    ) {
        if (!isInit) {
            zxadListener.onError("没有初始化")
            return
        }
        ZXADClient.adApi.getAd(type).compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<List<NewsEntity>>() {
                override fun onSuccess(result: List<NewsEntity>) {
                    if (result != null && result.isNotEmpty()) {
                        var arrayList = result as ArrayList
                        var newsEntity = arrayList[0]
                        newsEntity.actionName = actionName
                        var callback: ZXADCallback1 = object : ZXADCallback1 {
                            override fun onAdSuccess() {
                            }

                            override fun onAdFail() {
                                if (arrayList.size > 0) {
                                    if (arrayList[0].backups != null && arrayList[0].backups.size > 0) {
                                        newsEntity = arrayList[0].backups[0]
                                        newsEntity.actionName = actionName
                                        loadSplashAd(
                                            newsEntity,
                                            activity,
                                            container,
                                            zxadListener,
                                            skipview,
                                            this
                                        )
                                        arrayList.remove(arrayList[0])
                                    } else {
                                        zxadListener.onError("拉取广告失败")
                                    }
                                } else {
                                    zxadListener.onError("拉取广告失败")
                                }
                            }
                        }
                        loadSplashAd(
                            newsEntity,
                            activity,
                            container,
                            zxadListener,
                            skipview,
                            callback
                        )
                    } else {
                        zxadListener.onError("请求服务器失败")
                    }
                }

                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {
                    zxadListener.onError("请求服务器失败")
                }
            })
    }

    //TODO 预加载插屏广告  (重要)
    fun loadInterstitialAd(activity: Activity, adType: String, zxadModelConfig: ZXADSizeConfig) {
        if (!isInit) {
            return
        }
        ZXADClient.adApi.getAd(adType).compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<List<NewsEntity>>() {
                override fun onSuccess(result: List<NewsEntity>) {
                    LogUtils.e("hloadInterstitialAd    接口返回 时间" + System.currentTimeMillis())
                    LogUtils.e(TAG, "请求插屏广告成功  返回" + result?.size + "条广告")
                    if (result?.isNotEmpty()) {
                        val get = result.get(0)
                        when (get.adPlatform) {
                            ZXADType.PLANTFORM_AD_TT -> {
                                TTADUtils.loadInteraction2Ad(
                                    activity,
                                    get,
                                    zxadModelConfig,
                                    object : ZXADCallback1 {
                                        override fun onAdSuccess() {
                                            AdCache.interaList.add(get)
                                        }

                                        override fun onAdFail() {
                                        }

                                    }
                                )

                            }
                            ZXADType.PLANTFORM_AD_GDT -> {
                                GDTAdUtils.loadInteractionAd2(activity,
                                    get,
                                    zxadModelConfig,
                                    object : ZXADCallback1 {
                                        override fun onAdSuccess() {
                                            AdCache.interaList.add(get)
                                        }

                                        override fun onAdFail() {
                                        }

                                    })
                            }
                            else -> {
                                AdCache.interaList.add(get)
                            }

                        }
                    }


                }

                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {
                    LogUtils.e(TAG, "请求插屏广告失败  返回" + errorMsg)
                }
            })

    }

    //TODO  直接加载的
    private fun loadInterstitialAd(
        activity: Activity,
        adType: String,
        actionName: String,
        zxadModelConfig: ZXADSizeConfig,
        listener: ZXADFullVideoListener
    ) {
        if (!isInit) {
            return
        }
        ZXADClient.adApi.getAd(adType).compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<List<NewsEntity>>() {
                override fun onSuccess(result: List<NewsEntity>) {
                    LogUtils.e(TAG, "请求插屏广告成功  返回" + result?.size + "条广告")
                    if (result?.isNotEmpty()) {
                        val get = result.get(0)
                        get.actionName = actionName
                        var callback: ZXADCallback1 = object : ZXADCallback1 {
                            override fun onAdSuccess() {
                            }

                            override fun onAdFail() {

                            }
                        }
                        when (get.adPlatform) {
                            ZXADType.PLANTFORM_AD_GDT -> {
                                GDTAdUtils.loadInteractionAd(activity, get, callback, listener)
                            }
                            ZXADType.PLANTFORM_AD_TT -> {
                                TTADUtils.loadInteractionAd(
                                    activity,
                                    get,
                                    zxadModelConfig,
                                    callback
                                )
                            }
                        }
                    }
                }

                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {
                    LogUtils.e(TAG, "请求插屏广告失败  返回" + errorMsg)
                }
            })

    }

    //TODO 展示广告      (重要)
    fun showInterstitialAd(
        mActivity: Activity,
        adType: String,
        actionName: String,
        zxadModelConfig: ZXADSizeConfig,
        listener: ZXADFullVideoListener
    ) {
        if (AdCache.interaList.isNotEmpty()) {//不为空
            var arrayList = AdCache.interaList
            var newsEntity = arrayList[0]

            var totalEntity = java.util.ArrayList<NewsEntity>()
            val backups = newsEntity.backups
            totalEntity.add(newsEntity)
            if (backups != null && backups.isNotEmpty()) {
                totalEntity.addAll(backups)
            }
            var cacheNewsEntity = totalEntity[0]
            cacheNewsEntity.actionName = actionName
            var callback: ZXADCallback1 = object : ZXADCallback1 {
                override fun onAdSuccess() {

                }

                override fun onAdFail() {
                    LogUtils.e(TAG, "加载插屏广告失败 onAdFail ")
                    // 执行保底
                    if (totalEntity.size > 0) {
                        LogUtils.e(TAG, "加载插屏广告失败 onAdFail  执行保底策略")
                        cacheNewsEntity = totalEntity[0]
                        cacheNewsEntity.actionName = actionName
                        loadInterstitia(mActivity, cacheNewsEntity, zxadModelConfig, this, listener)
                        totalEntity.removeAt(0)
                    }
                }
            }

            loadInterstitia(mActivity, cacheNewsEntity, zxadModelConfig, callback, listener)
            totalEntity.removeAt(0)
            AdCache.interaList.clear()
        } else {
            //直接请求加载
            LogUtils.e(TAG, "缓存里面没有插屏，直接请求并加载 ")
            loadInterstitialAd(mActivity, adType, actionName, zxadModelConfig, listener)
        }

    }

    //去加载
    fun loadInterstitia(
        activity: Activity,
        newsEntity: NewsEntity,
        zxadModelConfig: ZXADSizeConfig,
        callback: ZXADCallback1,
        listener: ZXADFullVideoListener
    ) {
        when (newsEntity.adPlatform) {
            ZXADType.PLANTFORM_AD_GDT -> {
//                GDTAdUtils.loadInteractionAd(activity, newsEntity, callback, listener)
                GDTAdUtils.showInteri(activity, newsEntity, callback, listener)
            }
            ZXADType.PLANTFORM_AD_TT -> {
                TTADUtils.showInteractionAd(activity, newsEntity, zxadModelConfig, callback)
            }
            else -> {
                callback?.onAdFail()
            }

        }
    }

    fun destroyInteractionAd() {
        GDTAdUtils.destroyInteractionAd()
        TTADUtils.destroyInteractionAd()
    }


    //TODO 加载信息流广告    模板广告
    fun loadFeedAd(
        adType: String,
        actionName: String,
        mActivity: Activity,
        zxadModelConfig: ZXADSizeConfig,
        container: FrameLayout
    ) {
        if (!isInit) {
            return
        }
        if (AdCache.nativeList.get(adType) == null || AdCache.nativeList.get(adType)!!.size <= 0) {
            ZXADClient.adApi.getAd(adType).compose(RxSchedulers.observableIO2Main())
                .subscribe(object : BaseObserver<List<NewsEntity>>() {
                    override fun onSuccess(result: List<NewsEntity>) {
                        LogUtils.e(TAG, "请求信息流广告成功  返回" + result?.size + "条广告")
                        if (result != null && result.isNotEmpty()) {
                            //清除并加入缓存
                            AdCache.nativeList.put(adType, result)
                            loadCacheFeedAd(
                                mActivity,
                                actionName,
                                result,
                                zxadModelConfig,
                                container,
                                adType
                            )
                        }
                    }

                    override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {
                        LogUtils.e(TAG, "请求信息流广告失败  返回" + errorMsg)
                    }
                })
        } else {
            loadCacheFeedAd(
                mActivity,
                actionName,
                AdCache.nativeList.get(adType)!!,
                zxadModelConfig,
                container,
                adType
            )
        }
    }

    //预加载
    fun loadFeedAdToCache(
        adType: String,
        mActivity: Activity,
        zxadModelConfig: ZXADSizeConfig
    ) {
        if (!isInit) {
            return
        }
        ZXADClient.adApi.getAd(adType).compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<List<NewsEntity>>() {
                override fun onSuccess(result: List<NewsEntity>) {
                    LogUtils.e(TAG, "请求信息流广告成功  返回" + result?.size + "条广告")
                    if (result != null && result.isNotEmpty()) {
                        if (result[0].bgroup != null) {
                            LogUtils.d(TAG, "信息流 B组有配置")
                            if (AdCache.nativeCacheList[adType] == null && AdCache.nativeCacheListB[adType] == null) {
                                loadCacheFeedAd(mActivity, result, zxadModelConfig, adType)
                                loadBCacheFeedAd(mActivity, result, zxadModelConfig, adType)
                                LogUtils.d(TAG, "信息流 无缓存 同时加载")
                            } else if (AdCache.nativeCacheList[adType] != null) {
                                LogUtils.d(TAG, "信息流 A有缓存 加载B")
                                loadBCacheFeedAd(mActivity, result, zxadModelConfig, adType)
                            } else if (AdCache.nativeCacheListB[adType] != null) {
                                LogUtils.d(TAG, "信息流 B有缓存 加载A")
                                loadCacheFeedAd(mActivity, result, zxadModelConfig, adType)
                            }
                        } else {
                            LogUtils.d(TAG, "信息流 B组无配置 正常加载")
                            loadCacheFeedAd(mActivity, result, zxadModelConfig, adType)
                        }
                    }
                }

                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {
                    LogUtils.e(TAG, "请求信息流广告失败  返回" + errorMsg)
                }
            })
    }

    //TODO 是否去缓存的 重要
    private fun loadCacheFeedAd(
        mActivity: Activity,
        actionName: String,
        result: List<NewsEntity>,
        zxadModelConfig: ZXADSizeConfig,
        container: FrameLayout,
        adType: String
    ) {
        var arrayList = result as ArrayList
        var newsEntity = arrayList[0]

        var totalEntity = java.util.ArrayList<NewsEntity>()
        val backups = newsEntity.backups
        totalEntity.add(newsEntity)
        if (backups != null && backups.isNotEmpty()) {
            totalEntity.addAll(backups)
        }
        var cacheNewsEntity = totalEntity[0]
        cacheNewsEntity.actionName = actionName
        var callback: ZXADCallback1 = object : ZXADCallback1 {
            override fun onAdSuccess() {
                LogUtils.e(TAG, "加载信息流广告成功 onAdSuccess  结束")
                result.remove(newsEntity)
                AdCache.nativeList.put(adType, result)
            }

            override fun onAdFail() {
                LogUtils.e(TAG, "加载信息流广告失败 onAdFail ")
                // 执行保底
                if (totalEntity.size > 0) {
                    LogUtils.e(TAG, "加载信息流广告失败 onAdFail  执行保底策略")
                    cacheNewsEntity = totalEntity[0]
                    cacheNewsEntity.actionName = actionName
                    loadFeedAd(mActivity, cacheNewsEntity, zxadModelConfig, container, this)
                    totalEntity.removeAt(0)
                }
            }
        }

        loadFeedAd(mActivity, cacheNewsEntity, zxadModelConfig, container, callback)
        totalEntity.removeAt(0)
    }

    //预加载信息流 A组
    private fun loadCacheFeedAd(
        mActivity: Activity,
        result: List<NewsEntity>,
        zxadModelConfig: ZXADSizeConfig,
        adType: String
    ) {
        var arrayList = result as ArrayList
        var newsEntity = arrayList[0]
        var totalEntity = ArrayList<NewsEntity>()
        val backups = newsEntity.backups
        totalEntity.add(newsEntity)
        if (backups != null && backups.isNotEmpty()) {
            totalEntity.addAll(backups)
        }

        var cacheNewsEntity = totalEntity[0]
        var callback: ZXADCallback1 = object : ZXADCallback1 {
            override fun onAdSuccess() {
                AdCache.nativeCacheList.put(adType, cacheNewsEntity)
                AdCache.nativeCacheTime.put(adType, System.currentTimeMillis().toString())
                LogUtils.e("huang", "A组 预加载信息流广告成功  " + cacheNewsEntity.adPlatform)
            }

            override fun onAdFail() {
                totalEntity.remove(cacheNewsEntity)
                LogUtils.e(TAG, "A组 加载信息流广告失败 onAdFail ")
                // 执行保底
                if (totalEntity.size > 0) {
                    cacheNewsEntity = totalEntity[0]
                    LogUtils.e(TAG, "A组 加载信息流广告失败 onAdFail  执行保底策略")
                    loadFeedAd(mActivity, cacheNewsEntity, zxadModelConfig, this)
                }
            }
        }

        loadFeedAd(mActivity, cacheNewsEntity, zxadModelConfig, callback)
    }

    //预加载信息流 B组
    private fun loadBCacheFeedAd(
        mActivity: Activity,
        result: List<NewsEntity>,
        zxadModelConfig: ZXADSizeConfig,
        adType: String
    ) {
        var arrayList = result as ArrayList
        var newsEntity = arrayList[0].bgroup
        var totalEntity = ArrayList<NewsEntity>()

        if (newsEntity != null) {
            val backups = newsEntity.backups
            totalEntity.add(newsEntity)
            if (backups != null && backups.isNotEmpty()) {
                totalEntity.addAll(backups)
            }

            var cacheNewsEntity = totalEntity[0]
            var callback: ZXADCallback1 = object : ZXADCallback1 {
                override fun onAdSuccess() {
                    AdCache.nativeCacheListB.put(adType, cacheNewsEntity)
                    AdCache.nativeCacheTime.put(adType, System.currentTimeMillis().toString())
                    LogUtils.e("huang", "B组 预加载信息流广告成功  " + cacheNewsEntity.adPlatform)
                }

                override fun onAdFail() {
                    totalEntity.remove(cacheNewsEntity)
                    LogUtils.e(TAG, "B组 加载信息流广告失败 onAdFail ")
                    // 执行保底
                    if (totalEntity.size > 0) {
                        cacheNewsEntity = totalEntity[0]
                        LogUtils.e(TAG, "B组 加载信息流广告失败 onAdFail  执行保底策略")
                        loadFeedAd(mActivity, cacheNewsEntity, zxadModelConfig, this)
                    }
                }
            }

            loadFeedAd(mActivity, cacheNewsEntity, zxadModelConfig, callback)
        } else {
            LogUtils.d(TAG, "信息流 B组空")
        }

    }

    //加载 激励视频广告  和 全屏广告  原始的逻辑
    fun loadRewardVideoAd(
        slotName: String,
        actionName: String,
        mActivity: Activity,
        listener: ZXADVideoListener
    ) {
        if (!isInit) {
            listener.onError("没有初始化")
            return
        }
        ShowLoadIng(mActivity);
        if (AdCache.rewardList.get(slotName) == null || AdCache.rewardList.get(slotName)?.size!! <= 0) {
            LogUtils.e(TAG, "请求服务器 获取广告数据")
            ZXADClient.adApi.getAd(slotName).compose(RxSchedulers.observableIO2Main())
                .subscribe(object : BaseObserver<List<NewsEntity>>() {
                    override fun onSuccess(result: List<NewsEntity>) {
                        if (result != null && result.isNotEmpty()) {
                            LogUtils.e("huang", "请求服务器 获取广告数据 放入缓存中" + result.size)
                            loadCacheRewardVideoAd(
                                mActivity,
                                listener,
                                result,
                                slotName,
                                actionName
                            )
                        } else {
                            listener.onError("接口请求失败")
                            DissmissLoadIng();
                        }
                    }

                    override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {
                        listener.onError(errorMsg)
                        DissmissLoadIng();
                    }
                })
        } else {
            loadCacheRewardVideoAd(
                mActivity,
                listener,
                AdCache.rewardList.get(slotName)!!,
                slotName,
                actionName
            )
        }
    }

    /**
     * 加载激励视频
     */
    private fun loadCacheRewardVideoAd(
        mActivity: Activity,
        listener: ZXADVideoListener,
        result: List<NewsEntity>,
        slotName: String,
        actionName: String
    ) {
        LogUtils.d(TAG, "激励视频 缓存中的数据" + result.size)
        var arrayList = result as ArrayList
        if (arrayList.size == 0) {
            return
        }
        var newsEntity = arrayList[0]
        var totalEntity = java.util.ArrayList<NewsEntity>()
        val backups = newsEntity.backups
        totalEntity.add(newsEntity)
        if (backups != null) {
            totalEntity.addAll(backups)
        }

        var cacgeNewsEntity = totalEntity[0]

        var callback: ZXADCallback1 = object : ZXADCallback1 {
            override fun onAdSuccess() {
                result.remove(cacgeNewsEntity)
                AdCache.rewardList.put(slotName, result)
//                AdCacheTimeOut = System.currentTimeMillis()
                AdCache.adCacheTimeOutList[AdEventUtils.AD_MODEL_REWARD] =
                    System.currentTimeMillis()
                LogUtils.d(TAG, "记录缓存成功的时间：" + System.currentTimeMillis())
                DissmissLoadIng();
            }

            override fun onAdFail() {
                if (totalEntity.size > 0) {
                    cacgeNewsEntity = totalEntity[0]
                    totalEntity.removeAt(0)
                    AdCache.rewardList.put(slotName, totalEntity)
                    cacgeNewsEntity.actionName = actionName
                    LogUtils.d(TAG, "onAdFail")
                    loadVideoAd(mActivity, cacgeNewsEntity, listener, this)
                } else {
                    listener.onError("视频加载失败")
                    DissmissLoadIng();
                }
            }
        }
        if (totalEntity.isNotEmpty()) {
            totalEntity.removeAt(0)
            cacgeNewsEntity.actionName = actionName
            LogUtils.d(TAG, "totalEntity.isNotEmpty()")
            loadVideoAd(mActivity, cacgeNewsEntity, listener, callback)
        }
    }

    //视频分类 激励 全屏
    private fun loadVideoAd(
        activity: Activity,
        newsEntity: NewsEntity,
        listener: ZXADVideoListener,
        callback: ZXADCallback1
    ) {
        when (newsEntity.adType) {
            8 -> {
                loadScreenVideoAd(newsEntity, activity, callback, listener)
            }
            7 -> {
                loadRewardVideoAd(activity, newsEntity, listener, callback)
            }
        }
    }

    //加载 DrawFeedVideoAd
    fun loadDrawFeedVideoAd(slotName: String, mActivity: Activity, listener: ZXADDrawListener) {
        if (!isInit) {
            return
        }
        ZXADClient.adApi.getAd(slotName).compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<List<NewsEntity>>() {
                override fun onSuccess(result: List<NewsEntity>) {
                    if (result != null && result.isNotEmpty()) {
                        val newsEntity = result[0]
                        loadDrawFeedVideoAd(newsEntity, mActivity, listener)

                        listener.onSuccess()
                    } else {
                        listener.onFail()
                    }
                }

                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {
                    listener.onFail()
                }
            })
    }


    //个性化 draw视频
    fun loadExpressDrawFeedAd(slotName: String, mActivity: Activity, listener: ZXADDrawListener) {
        if (!isInit) {
            return
        }
        ZXADClient.adApi.getAd(slotName).compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<List<NewsEntity>>() {

                override fun onSuccess(result: List<NewsEntity>) {
                    if (result != null && result.isNotEmpty()) {
                        val newsEntity = result[0]
                        loadDrawFeedSpecialVideoAd(
                            newsEntity,
                            mActivity,
                            listener,
                            ZXADSizeConfig(1080, 1920)
                        )

                        listener.onSuccess()
                    } else {
                        listener.onFail()
                    }
                }

                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {
                    listener.onFail()
                }
            })

    }

    /**
     * 全屏，插屏广告位 直接拉广告并播放
     */
    fun loadFullVideoAd(
        slotName: String,
        mActivity: Activity,
        actionName: String,
        listener: ZXADFullVideoListener
    ) {
        if (!isInit) {
            listener?.onError("SDK 初始化失败")
            return
        }
        ShowLoadIng(mActivity)
        if (AdCache.interactionList.get(slotName) == null || AdCache.interactionList.get(slotName)?.size!! <= 0) {
            LogUtils.e(TAG, "请求服务器 获取广告数据")
            ZXADClient.adApi.getAd(slotName).compose(RxSchedulers.observableIO2Main())
                .subscribe(object : BaseObserver<List<NewsEntity>>() {
                    override fun onSuccess(result: List<NewsEntity>) {
                        if (result != null && result.isNotEmpty()) {
                            LogUtils.e("huang", "请求服务器 获取广告数据 放入缓存中" + result.size)
                            loadCacheFullVideoAd(
                                mActivity,
                                listener,
                                result,
                                slotName,
                                actionName
                            )
                        } else {
                            DissmissLoadIng()
                            listener.onError("接口请求失败")
                        }
                    }

                    override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {
                        DissmissLoadIng()
                        listener.onError(errorMsg)
                    }
                })
        } else {
            loadCacheFullVideoAd(
                mActivity,
                listener,
                AdCache.interactionList.get(slotName)!!,
                slotName,
                actionName
            )
        }
    }

    //开屏广告
    private fun loadSplashAd(
        newsEntity: NewsEntity,
        activity: Activity,
        container: ViewGroup,
        zxadListener: ZXADSplashListener,
        skipview: TextView?,
        callback: ZXADCallback1
    ) {
        LogUtils.d(TAG, "开屏 ：" + newsEntity.adPlatform)
        when (newsEntity.adPlatform) {
            ZXADType.PLANTFORM_AD_GDT -> {
                GDTAdUtils.loadSplashAd(
                    newsEntity,
                    activity,
                    container,
                    zxadListener,
                    skipview,
                    callback
                )
            }
            ZXADType.PLANTFORM_AD_TT -> {
                TTADUtils.loadSplashAd(newsEntity, activity, container, zxadListener, callback)
            }
            ZXADType.PLANTFORM_AD_SH -> {
                SHADUtils.loadSplashAd(
                    newsEntity,
                    activity,
                    container,
                    zxadListener,
                    skipview,
                    callback
                )
            }
            //百度广告
            ZXADType.PLANTFORM_AD_BD -> {
                BDADUtils.loadSplashAd(
                    newsEntity,
                    activity,
                    container,
                    zxadListener,
                    skipview,
                    callback
                )
            }
            //快手
            ZXADType.PLANTFORM_AD_KUS -> {
                KSADUtils.loadSplashAd(
                    newsEntity,
                    activity,
                    container,
                    zxadListener,
                    callback
                )
            }
            //signmob
            ZXADType.PLANTFORM_AD_SIGNMOB -> {
                SMADUtils.loadSplashAd(
                    newsEntity,
                    activity,
                    container,
                    zxadListener,
                    callback
                )
            }
            //汇量
//            ZXADType.PLANTFORM_AD_HL -> {
//                HLAdUtils.loadSplashAd(
//                    newsEntity,
//                    activity,
//                    container,
//                    skipview,
//                    zxadListener,
//                    callback
//                )
//            }

            ZXADType.PLANTFORM_AD_FENGXING -> {
                FunShionUtils.loadSplash(
                    newsEntity,
                    activity,
                    container,
                    skipview,
                    zxadListener,
                    callback
                )
            }
        }

    }


    /**
     * 加载插屏视频
     */
    private fun loadCacheFullVideoAd(
        mActivity: Activity,
        listener: ZXADFullVideoListener,
        result: List<NewsEntity>,
        slotName: String,
        actionName: String
    ) {
        LogUtils.d(TAG, "插屏视频 缓存中的数据" + result.size)
        var arrayList = result as ArrayList
        if (arrayList.size == 0) {
            return
        }
        var newsEntity = arrayList[0]
        var totalEntity = java.util.ArrayList<NewsEntity>()
        val backups = newsEntity.backups
        totalEntity.add(newsEntity)
        if (backups != null) {
            totalEntity.addAll(backups)
        }

        var cacgeNewsEntity = totalEntity[0]

        var callback: ZXADCallback1 = object : ZXADCallback1 {
            override fun onAdSuccess() {
                result.remove(cacgeNewsEntity)
                DissmissLoadIng()
                AdCache.interactionList.put(slotName, result)
                AdCache.adCacheTimeOutList[AdEventUtils.AD_MODEL_FULL_VIDEO] =
                    System.currentTimeMillis()
                LogUtils.d(TAG, "记录缓存成功的时间：" + System.currentTimeMillis())
            }

            override fun onAdFail() {
                if (totalEntity.size > 0) {
                    cacgeNewsEntity = totalEntity[0]
                    totalEntity.removeAt(0)
                    AdCache.interactionList.put(slotName, totalEntity)
                    cacgeNewsEntity.actionName = actionName
                    LogUtils.d(TAG, "onAdFail")
                    loadDistributionFullVideoAd(
                        cacgeNewsEntity,
                        mActivity,
                        listener,
                        this
                    )
                } else {
                    DissmissLoadIng()
                    listener.onError("视频加载失败")
                }
            }
        }
        if (totalEntity.isNotEmpty()) {
            totalEntity.removeAt(0)
            cacgeNewsEntity.actionName = actionName
            LogUtils.d(TAG, "totalEntity.isNotEmpty()")
            loadDistributionFullVideoAd(
                cacgeNewsEntity,
                mActivity,
                listener,
                callback
            )
        }
    }


    //分发插屏广告实现
    private fun loadDistributionFullVideoAd(
        newsEntity: NewsEntity,
        activity: Activity,
        listener: ZXADFullVideoListener,
        callback: ZXADCallback1
    ) {
        LogUtils.d(TAG, "全屏：${newsEntity.adPlatform} -- ${newsEntity.adType}")
        when (newsEntity.adPlatform) {
            ZXADType.PLANTFORM_AD_GDT -> {
                GDTAdUtils.loadInteractionAd(activity, newsEntity, callback, listener)
            }
            ZXADType.PLANTFORM_AD_TT -> {
                if (newsEntity?.adType == 8) {
                    TTADUtils.loadFullVideoAd(activity, newsEntity, listener, callback)
                } else {
                    TTADUtils.loadInteractionAd(activity, newsEntity, null, callback)
                }
            }
            ZXADType.PLANTFORM_AD_BD -> {
                callback?.onAdFail()
//                BDADUtils.loadInteractionAd(activity, newsEntity, callback)
            }
            ZXADType.PLANTFORM_AD_SIGNMOB -> {
                SMADUtils.loadFullScreenAd(activity, newsEntity, callback)
            }

        }
    }

    //信息流
    private fun loadFeedAd(
        activity: Activity,
        newsEntity: NewsEntity,
        zxadModelConfig: ZXADSizeConfig,
        container: FrameLayout,
        callback: ZXADCallback1
    ) {
        when (newsEntity.adPlatform) {
            ZXADType.PLANTFORM_AD_GDT -> {
                LogUtils.e(TAG, "请求广点通 大图广告")
                GDTAdUtils.loadFeedAd(activity, newsEntity, zxadModelConfig, container, callback)
            }
            //穿山甲
            ZXADType.PLANTFORM_AD_TT -> {
                LogUtils.e(TAG, "请求穿山甲 大图广告")
                TTADUtils.loadFeedAd(activity, newsEntity, zxadModelConfig, container, callback)
            }
            //快手
            ZXADType.PLANTFORM_AD_KUS -> {
                LogUtils.e(TAG, "请求快手 大图广告")
                KSADUtils.loadFeedNativeAd(
                    activity,
                    newsEntity,
                    container,
                    callback
                )
            }
//            //汇量
//            ZXADType.PLANTFORM_AD_HL -> {
//                LogUtils.e(TAG, "请求汇量 大图广告")
//                HLAdUtils.loadFeedNativeAd(
//                    activity,
//                    newsEntity,
//                    container,
//                    callback
//                )
//            }

        }

    }

    //信息流
    private fun loadFeedAd(
        activity: Activity,
        newsEntity: NewsEntity,
        zxadModelConfig: ZXADSizeConfig,
        callback: ZXADCallback1
    ) {
        when (newsEntity.adPlatform) {
            ZXADType.PLANTFORM_AD_GDT -> {
                LogUtils.e(TAG, "请求广点通 大图广告")
                GDTAdUtils.loadFeedAd(activity, newsEntity, zxadModelConfig, callback)
            }
            //穿山甲
            ZXADType.PLANTFORM_AD_TT -> {
                LogUtils.e(TAG, "请求穿山甲 大图广告")
                TTADUtils.loadFeedAd(activity, newsEntity, zxadModelConfig, callback)
            }
            //快手
            ZXADType.PLANTFORM_AD_KUS -> {
                LogUtils.e(TAG, "请求快手 大图广告")
                KSADUtils.loadFeedNativeAd(newsEntity, callback)
            }
//            //汇量
//            ZXADType.PLANTFORM_AD_HL -> {
//                LogUtils.e(TAG, "请求汇量 大图广告")
//                HLAdUtils.loadFeedAd(activity, newsEntity, callback)
//            }
        }

    }

    fun showFeedAd(
        slotName: String,
        actionName: String,
        zxadModelConfig: ZXADSizeConfig,
        activity: Activity,
        container: FrameLayout
    ) {
        if (!isInit) {
            return
        }

        var targetEntity: NewsEntity? = null

        var entity = AdCache.nativeCacheList[slotName]
        var entityB = AdCache.nativeCacheListB[slotName]
        val time = AdCache.nativeCacheTime.get(slotName)

        if (entity != null && entityB != null) {
            LogUtils.d(TAG, "信息流 竞价：A:" + entity.codePrice + " --- B:" + entityB.codePrice)
            if (entity.codePrice > entityB.codePrice) {
                targetEntity = entity
            } else {
                targetEntity = entityB
            }
        } else if (entity == null) {
            LogUtils.d(TAG, "信息流 竞价：A is null")
            targetEntity = entityB
        } else if (entityB == null) {
            LogUtils.d(TAG, "信息流 竞价：B is null")
            targetEntity = entity
        }

        if (targetEntity != null && time != null && (System.currentTimeMillis() - time.toLong()) < TIME_OUT) {
            targetEntity.actionName = actionName
            showFeedAd(activity, targetEntity, container)

            if (targetEntity.bgroup != null) {
                if ("A".equals(targetEntity.codeGroup)) {
                    LogUtils.e("huang", "有b组策略 清除A")
                    AdCache.nativeCacheList.remove(slotName)
                } else {
                    LogUtils.e("huang", "有b组策略 清除B")
                    AdCache.nativeCacheListB.remove(slotName)
                }
            } else {
                AdCache.nativeCacheList.remove(slotName)
            }

            LogUtils.e(
                "huang",
                "展示缓存中的广告" + targetEntity?.adPlatform + "-- ${targetEntity.codeGroup + "组"}"
            )
        } else {
            LogUtils.e("huang", "Cache 缓存失败没有缓存数据走原始流程")
            loadFeedAd(slotName, actionName, activity, zxadModelConfig, container)
        }
    }

    private fun showFeedAd(activity: Activity, newsEntity: NewsEntity, container: FrameLayout) {
        when (newsEntity.adPlatform) {
            ZXADType.PLANTFORM_AD_GDT -> {
                LogUtils.e(TAG, "加载广点通 大图广告")
                GDTAdUtils.showFeedAd(activity, newsEntity, container)
            }
            //穿山甲
            ZXADType.PLANTFORM_AD_TT -> {
                LogUtils.e(TAG, "请求穿山甲 大图广告")
                TTADUtils.showFeedAd(activity, newsEntity, container)
            }
            //快手
            ZXADType.PLANTFORM_AD_KUS -> {
                LogUtils.e(TAG, "请求快手 大图广告")
                KSADUtils.showFeedAd(
                    activity,
                    newsEntity,
                    container
                )
            }
//            //汇量
//            ZXADType.PLANTFORM_AD_HL -> {
//                LogUtils.e(TAG, "请求汇量 大图广告")
//                HLAdUtils.showFeedAd(
//                    activity,
//                    newsEntity,
//                    container
//                )
//            }

        }
    }

    //激励视频广告
    private fun loadRewardVideoAd(
        activity: Activity,
        entity: NewsEntity,
        listener: ZXADVideoListener,
        callback: ZXADCallback1
    ) {
        LogUtils.e(
            TAG,
            "entity.adPlatform:  " + entity?.adPlatform ?: "" + " -- codeId=" + entity?.codeId ?: ""
        )
        when (entity.adPlatform) {
            ZXADType.PLANTFORM_AD_GDT -> {
                GDTAdUtils.loadRewardVideoAd(activity, entity, listener, callback)
            }
            ZXADType.PLANTFORM_AD_TT -> {
                TTADUtils.loadRewardVideoAd(activity, entity, listener, callback)
            }
            ZXADType.PLANTFORM_AD_SH -> {
                SHADUtils.loadRewardVideoAd(activity, entity, listener, callback)
            }
            ZXADType.PLANTFORM_AD_SIGNMOB -> {
                SMADUtils.loadRewardVideoAd(activity, entity, listener, callback)
            }
            ZXADType.PLANTFORM_AD_BD -> {
                BDADUtils.loadRewardVideoAd(activity, entity, listener, callback)
            }
            //优量宝
            ZXADType.PLANTFORM_SH_YLB -> {
                WNManager.loadRewardVideoAd(activity, entity, listener, callback)
            }
            //快手
            ZXADType.PLANTFORM_AD_KUS -> {
                KSADUtils.loadRewardVideoAd(activity, entity, listener, callback)
            }
//            ZXADType.PLANTFORM_AD_HL -> {
//                HLAdUtils.loadRewardVideoAd(activity, entity, listener, callback)
//            }
            ZXADType.PLANTFORM_AD_NEWS -> {
                NewsUtils.loadReward(callback)
            }
            ZXADType.PLANTFORM_AD_FENGXING -> {
                FunShionUtils.loadRewardVideo(activity, entity, listener, callback)
            }
        }

    }

    //TODO  全屏视频广告   只有穿山甲    所以不需要重试
    private fun loadScreenVideoAd(
        entity: NewsEntity,
        activity: Activity,
        callback: ZXADCallback1,
        listener: ZXADVideoListener
    ) {
        when (entity.adPlatform) {
            ZXADType.PLANTFORM_AD_TT -> {
//                TTADUtils.loadFullVideoAd(activity, entity, listener, callback)
            }
        }
    }


    //TODO  Draw视频
    private fun loadDrawFeedVideoAd(
        entity: NewsEntity,
        activity: Activity,
        listener: ZXADDrawListener
    ) {
        TTADUtils.loadDrawFeedVideoAd(activity, entity, listener)
    }


    //TODO  Draw视频 个性化
//广点通的 个性化 draw视频
    private fun loadDrawFeedSpecialVideoAd(
        entity: NewsEntity,
        activity: Activity,
        listener: ZXADDrawListener,
        zxadModelConfig: ZXADSizeConfig
    ) {
        TTADUtils.loadDrawFeedSpecialVideoAd(activity, entity, listener, zxadModelConfig)
    }

    //TODO 珊瑚的 视频流
    fun loadSHFeedSpecialVideoAd(activity: Activity, i: Int) {
        if (!isInit) {
            return
        }
        SHADUtils.loadSHFeedSpecialVideoAd(activity, i)
    }

    //加载缓存
    fun loadNextCacheFullVideoAd(
        slotName: String, mActivity: Activity
    ) {
        if (!isInit) {
            return
        }
        ZXADClient.adApi.getAd(slotName).compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<List<NewsEntity>>() {
                override fun onSuccess(result: List<NewsEntity>) {
                    if (!isLoadFull && result != null && result.isNotEmpty()) {
                        for (value in result) {
                            val backups = value.backups
                            if (backups != null && backups.isNotEmpty()) {
                                Collections.reverse(backups)
                            }
                        }
                        Collections.reverse(result)
                        isLoadFull = true
                    }

                    if (result != null && result.isNotEmpty()) {
                        if (result[0].bgroup != null) {
                            if (AdCache.cacheAdFullMap[AdCache.cacheAdMapKey] == null && AdCache.cacheAdFullMapB[AdCache.cacheAdMapKey] == null) {
                                loadCacheFullVideoAd(mActivity, result)
                                loadBCacheFullVideoAd(mActivity, result)
                                LogUtils.d(TAG, "全屏 A B组无缓存数据，同时加载")
                            } else if (AdCache.cacheAdFullMap[AdCache.cacheAdMapKey] != null) {
                                LogUtils.d(TAG, "全屏 A 组有缓存数据，加载B组")
                                loadBCacheFullVideoAd(mActivity, result)
                            } else if (AdCache.cacheAdFullMapB[AdCache.cacheAdMapKey] != null) {
                                LogUtils.d(TAG, "全屏 B 组有缓存数据，加载A组")
                                loadCacheFullVideoAd(mActivity, result)
                            }
                        } else {
                            LogUtils.d(TAG, "全屏 B组无配置，走之前流程")
                            loadCacheFullVideoAd(mActivity, result)
                        }
                    }
                }

                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {
                }
            })
    }

    /**
     * 加载全屏视频
     */
    private fun loadCacheFullVideoAd(
        mActivity: Activity,
        result: List<NewsEntity>
    ) {
        var arrayList = result as ArrayList
        if (arrayList.size == 0) {
            return
        }
        thread {
            var cacheNewsEntity: NewsEntity? = null
            var newsEntity = arrayList[0]
            var totalEntity = ArrayList<NewsEntity>()
            val backups = newsEntity.backups
            if (newsEntity != null) {
                totalEntity.add(newsEntity)
            }
            if (backups != null) {
                totalEntity.addAll(backups)
            }

            LogUtils.d(TAG, "run 全屏视频 A组长度${totalEntity.size}")
            var callback: ZXADCallback1 = object : ZXADCallback1 {
                override fun onAdSuccess() {
                    LogUtils.d(
                        "huang",
                        "Cache A组 onAdSuccess 缓存成功广告:${cacheNewsEntity?.adPlatform} -- CodeId:${cacheNewsEntity?.codeId}"
                    )
//                    AdCacheTimeOut = System.currentTimeMillis()
                    AdCache.adCacheTimeOutList[AdEventUtils.AD_MODEL_FULL_VIDEO] =
                        System.currentTimeMillis()
                    AdCache.cacheAdFullMap[AdCache.cacheAdMapKey] = cacheNewsEntity
                    result.remove(newsEntity)
                }

                override fun onAdFail() {
                    LogUtils.d(
                        "huang",
                        "Cache A组 onAdFail 缓存失败广告:${cacheNewsEntity?.adPlatform} -- codeGroup:${cacheNewsEntity?.codeId}"
                    )
                    if (totalEntity.size > 0) {
                        cacheNewsEntity = totalEntity[0]
                        totalEntity.removeAt(0)
                        initCacheFullVideo(mActivity, cacheNewsEntity!!, this)
                    }
                }
            }
            if (totalEntity.isNotEmpty()) {
                cacheNewsEntity = totalEntity[0]
                totalEntity.removeAt(0)
                initCacheFullVideo(mActivity, cacheNewsEntity!!, callback)
            }
        }
    }

    /**
     * 加载全屏视频 B组
     */
    private fun loadBCacheFullVideoAd(
        mActivity: Activity,
        result: List<NewsEntity>
    ) {
        var arrayList = result as ArrayList
        if (arrayList.size == 0) {
            return
        }
        thread {
            var cacheNewsEntity: NewsEntity? = null
            var newsEntity = arrayList[0].bgroup
            if (newsEntity != null) {
                var totalEntity = ArrayList<NewsEntity>()
                val backups = newsEntity.backups
                if (newsEntity != null) {
                    totalEntity.add(newsEntity)
                }
                if (backups != null) {
                    totalEntity.addAll(backups)
                }
                LogUtils.d(TAG, "run 全屏视频 B组长度${totalEntity.size}")
                var callback: ZXADCallback1 = object : ZXADCallback1 {
                    override fun onAdSuccess() {
                        LogUtils.d(
                            "huang",
                            "Cache B组 onAdSuccess 缓存成功广告:${cacheNewsEntity?.adPlatform} --- CodeId:${cacheNewsEntity?.codeId}"
                        )
//                        AdCacheTimeOut = System.currentTimeMillis()
                        AdCache.adCacheTimeOutList[AdEventUtils.AD_MODEL_FULL_VIDEO] =
                            System.currentTimeMillis()
                        AdCache.cacheAdFullMapB[AdCache.cacheAdMapKey] = cacheNewsEntity
                        result.remove(newsEntity)
                    }

                    override fun onAdFail() {
                        LogUtils.d(
                            "huang",
                            "Cache B组 onAdFail 缓存失败广告:${cacheNewsEntity?.adPlatform} --- CodeId:${cacheNewsEntity?.codeId}"
                        )
                        if (totalEntity.size > 0) {
                            cacheNewsEntity = totalEntity[0]
                            totalEntity.removeAt(0)
                            initCacheFullVideo(mActivity, cacheNewsEntity!!, this)
                        }
                    }
                }
                if (totalEntity.isNotEmpty()) {
                    cacheNewsEntity = totalEntity[0]
                    totalEntity.removeAt(0)
                    initCacheFullVideo(mActivity, cacheNewsEntity!!, callback)
                }
            }
        }
    }


    private fun initCacheFullVideo(
        activity: Activity,
        entity: NewsEntity,
        callback: ZXADCallback1
    ) {
        when (entity.adPlatform) {
            ZXADType.PLANTFORM_AD_GDT -> {
                GDTAdUtils.loadCacheFullVideoAd(activity, entity, callback)
            }
            ZXADType.PLANTFORM_AD_TT -> {
                if (entity?.adType == 8) {
                    TTADUtils.loadCacheFullVideoAd(activity, entity, callback)
                } else {
                    TTADUtils.loadInteractionAd(activity, entity, null, callback)
                }
            }
            ZXADType.PLANTFORM_AD_SIGNMOB -> {
                SMADUtils.loadFullScreenAd(activity, entity, callback)
            }
        }
    }

    //
    private fun playCacheFullVideoAd(
        activity: Activity,
        newsEntity: NewsEntity,
        listener: ZXADFullVideoListener,
        callback: ZXADCallback1
    ) {
        LogUtils.d(
            "huang",
            "播放全屏视频广告源:" + newsEntity.adPlatform + " -- codeId=" + newsEntity.codeId
        );
        when (newsEntity.adPlatform) {
            ZXADType.PLANTFORM_AD_GDT -> {
                GDTAdUtils.playCacheFullVideoAd(activity, newsEntity, listener, callback)
            }
            ZXADType.PLANTFORM_AD_TT -> {
                if (newsEntity?.adType == 8) {
                    TTADUtils.playCacheFullAd(activity, newsEntity, listener, callback)
                } else {
                    //插屏
                }
            }
            ZXADType.PLANTFORM_AD_SIGNMOB -> {
                SMADUtils.playCacheFullAd(activity, newsEntity, listener, callback)
            }
        }
    }

    /**
     * 播放全屏广告
     */
    fun playFullVideoAd(
        slotName: String,
        actionName: String,
        activity: Activity,
        listener: ZXADFullVideoListener
    ) {
        if (!isInit) {
            listener.onError("sdk没有初始化")
            return
        }
        var entity = AdCache.cacheAdFullMap[AdCache.cacheAdMapKey]
        var entityB = AdCache.cacheAdFullMapB[AdCache.cacheAdMapKey]
        var targetEntity: NewsEntity? = null

        if (entity != null && entityB != null) {
            LogUtils.d(TAG, "竞价：A:" + entity.codePrice + " --- B:" + entityB.codePrice)
            if (entity.codePrice > entityB.codePrice) {
                targetEntity = entity
            } else {
                targetEntity = entityB
            }
        } else if (entity == null) {
            LogUtils.d(TAG, "竞价：A is null")
            targetEntity = entityB
        } else if (entityB == null) {
            LogUtils.d(TAG, "竞价：B is null")
            targetEntity = entity
        }

        MainLooper.get()?.post(Runnable {
            if (targetEntity != null && !checkTimeOut(AdEventUtils.AD_MODEL_FULL_VIDEO)) {
                targetEntity?.actionName = actionName
                //有缓存数据
                var callback: ZXADCallback1 = object : ZXADCallback1 {
                    override fun onAdSuccess() {}

                    override fun onAdFail() {
                        AdCache.cacheAdFullMap.clear()
                        AdCache.cacheAdFullMapB.clear()
                        LogUtils.e(
                            "huang",
                            "播放失败   播放失败走原始流程" + "    ${targetEntity?.codeId}   ${targetEntity?.adPlatform}"
                        )
                        loadFullVideoAd(
                            slotName,
                            activity,
                            actionName,
                            listener
                        )
                    }
                }
                playCacheFullVideoAd(activity, targetEntity, listener, callback)
                if (entityB != null) {
                    LogUtils.e("huang", "有缓存的数据，走缓存:" + targetEntity.codeGroup + "组")
                    if ("A".equals(targetEntity.codeGroup)) {
                        AdCache.cacheAdFullMap.remove(AdCache.cacheAdMapKey)
                        LogUtils.e("huang", "有B组策略 清除缓存:A组")
                    } else {
                        AdCache.cacheAdFullMapB.remove(AdCache.cacheAdMapKey)
                        LogUtils.e("huang", "有B组策略 清除缓存:B组")
                    }
                } else {
                    LogUtils.e("huang", "有缓存的数据，走正常缓存 无B组策略 清除")
                    AdCache.cacheAdFullMap.remove(AdCache.cacheAdMapKey)
                }
            } else {
                AdCache.cacheAdFullMap.remove(AdCache.cacheAdMapKey)
                AdCache.cacheAdFullMapB.remove(AdCache.cacheAdMapKey)
                LogUtils.e("huang", "超时   没有缓存数据走原始流程")
                loadFullVideoAd(slotName, activity, actionName, listener)
            }
        })
    }

    //加载缓存
    fun loadNextCacheRewardVideoAd(slotName: String, mActivity: Activity) {
        if (!isInit) {
            return
        }
        ZXADClient.adApi.getAd(slotName).compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<List<NewsEntity>>() {
                override fun onSuccess(result: List<NewsEntity>) {
                    if (!isLoadReward && result != null && result.isNotEmpty()) {
                        for (value in result) {
                            val backups = value.backups
                            if (backups != null && backups.isNotEmpty()) {
                                Collections.reverse(backups)
                            }
                        }
                        Collections.reverse(result)
                        isLoadReward = true
                    }

                    if (result != null && result.isNotEmpty()) {
                        if (result[0].bgroup != null) {
                            if (AdCache.cacheAdMap[AdCache.cacheAdMapKey] == null && AdCache.cacheAdMapB[AdCache.cacheAdMapKey] == null) {
                                loadCacheRewardVideoAd2(mActivity, result)
                                loadBCacheRewardVideoAd2(mActivity, result)
                                LogUtils.d(TAG, "激励 A B组无缓存数据，同时加载")
                            } else if (AdCache.cacheAdMap[AdCache.cacheAdMapKey] != null) {
                                LogUtils.d(TAG, "激励 A 组有缓存数据，加载B组")
                                loadBCacheRewardVideoAd2(mActivity, result)
                            } else if (AdCache.cacheAdMapB[AdCache.cacheAdMapKey] != null) {
                                LogUtils.d(TAG, "激励 B 组有缓存数据，加载A组")
                                loadCacheRewardVideoAd2(mActivity, result)
                            }
                        } else {
                            LogUtils.d(TAG, "激励 B组无配置，走之前流程")
                            loadCacheRewardVideoAd2(mActivity, result)
                        }
                    }
                }

                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {
                }
            })
    }

    /**
     * 加载激励视频
     */
    private fun loadCacheRewardVideoAd2(
        mActivity: Activity,
        result: List<NewsEntity>
    ) {
        var arrayList = result as ArrayList
        if (arrayList.size == 0) {
            return
        }
        thread {
            var cacheNewsEntity: NewsEntity? = null
            var newsEntity = arrayList[0]
            var totalEntity = ArrayList<NewsEntity>()
            val backups = newsEntity.backups
            if (newsEntity != null) {
                totalEntity.add(newsEntity)
            }
            if (backups != null) {
                totalEntity.addAll(backups)
            }

            LogUtils.d(TAG, "run 激励视频 A组长度${totalEntity.size}")
            var callback: ZXADCallback1 = object : ZXADCallback1 {
                override fun onAdSuccess() {
                    LogUtils.d(
                        "huang",
                        "Cache A组 onAdSuccess 缓存成功广告:${cacheNewsEntity?.adPlatform} -- CodeId:${cacheNewsEntity?.codeId}"
                    )
//                    AdCacheTimeOut = System.currentTimeMillis()
                    AdCache.adCacheTimeOutList[AdEventUtils.AD_MODEL_REWARD] =
                        System.currentTimeMillis()
                    AdCache.cacheAdMap[AdCache.cacheAdMapKey] = cacheNewsEntity
                    result.remove(newsEntity)
                }

                override fun onAdFail() {
                    LogUtils.d(
                        "huang",
                        "Cache A组 onAdFail 缓存失败广告:${cacheNewsEntity?.adPlatform} -- codeGroup:${cacheNewsEntity?.codeId}"
                    )
                    if (totalEntity.size > 0) {
                        cacheNewsEntity = totalEntity[0]
                        totalEntity.removeAt(0)
                        initCacheReward(mActivity, cacheNewsEntity!!, this)
                    }
                }
            }
            if (totalEntity.isNotEmpty()) {
                cacheNewsEntity = totalEntity[0]
                totalEntity.removeAt(0)
                initCacheReward(mActivity, cacheNewsEntity!!, callback)
            }
        }
    }

    /**
     * 加载激励视频 B组
     */
    private fun loadBCacheRewardVideoAd2(
        mActivity: Activity,
        result: List<NewsEntity>
    ) {
        var arrayList = result as ArrayList
        if (arrayList.size == 0) {
            return
        }
        thread {
            var cacheNewsEntity: NewsEntity? = null
            var newsEntity = arrayList[0].bgroup
            if (newsEntity != null) {
                var totalEntity = ArrayList<NewsEntity>()
                val backups = newsEntity.backups
                if (newsEntity != null) {
                    totalEntity.add(newsEntity)
                }
                if (backups != null) {
                    totalEntity.addAll(backups)
                }
                LogUtils.d(TAG, "run 激励视频 B组长度${totalEntity.size}")
                var callback: ZXADCallback1 = object : ZXADCallback1 {
                    override fun onAdSuccess() {
                        LogUtils.d(
                            "huang",
                            "Cache B组 onAdSuccess 缓存成功广告:${cacheNewsEntity?.adPlatform} --- CodeId:${cacheNewsEntity?.codeId}"
                        )
//                        AdCacheTimeOut = System.currentTimeMillis()
                        AdCache.adCacheTimeOutList[AdEventUtils.AD_MODEL_REWARD] =
                            System.currentTimeMillis()
                        AdCache.cacheAdMapB[AdCache.cacheAdMapKey] = cacheNewsEntity
                        result.remove(newsEntity)
                    }

                    override fun onAdFail() {
                        LogUtils.d(
                            "huang",
                            "Cache B组 onAdFail 缓存失败广告:${cacheNewsEntity?.adPlatform} --- CodeId:${cacheNewsEntity?.codeId}"
                        )
                        if (totalEntity.size > 0) {
                            cacheNewsEntity = totalEntity[0]
                            totalEntity.removeAt(0)
                            initCacheReward(mActivity, cacheNewsEntity!!, this)
                        }
                    }
                }
                if (totalEntity.isNotEmpty()) {
                    cacheNewsEntity = totalEntity[0]
                    totalEntity.removeAt(0)
                    initCacheReward(mActivity, cacheNewsEntity!!, callback)
                }
            }
        }


    }

    private fun initCacheReward(activity: Activity, entity: NewsEntity, callback: ZXADCallback1) {
        if (entity.adType != 7) {
            return
        }
        when (entity.adPlatform) {
            ZXADType.PLANTFORM_AD_GDT -> {
                GDTAdUtils.loadCacheRewardAd(activity, entity, callback)
            }
            ZXADType.PLANTFORM_AD_TT -> {
                TTADUtils.loadCacheRewardAd(activity, entity, callback)
            }
            ZXADType.PLANTFORM_AD_SH -> {
                callback.onAdFail()
            }
            ZXADType.PLANTFORM_AD_SIGNMOB -> {//TODO 待处理
                SMADUtils.loadCacheRewardAd(activity, entity, callback);
            }
            ZXADType.PLANTFORM_AD_BD -> {
                callback.onAdFail()
            }
            //优量宝
            ZXADType.PLANTFORM_SH_YLB -> {//TODO 优量宝播放没有error
                WNManager.loadCacheRewardAd(activity, entity, callback)
            }
            //快手
            ZXADType.PLANTFORM_AD_KUS -> {
                KSADUtils.loadCacheRewardAd(activity, entity, callback)
            }
            //风行
            ZXADType.PLANTFORM_AD_FENGXING -> {
                FunShionUtils.loadCacheRewardVideo(activity, entity, callback)
            }
//            //汇量
//            ZXADType.PLANTFORM_AD_HL -> {
//                HLAdUtils.loadCacheRewardAd(activity, entity, callback)
//            }
            //新闻站
            ZXADType.PLANTFORM_AD_NEWS -> {
                NewsUtils.loadReward(callback)
            }
        }
    }

    private fun playCacheRewardAd(
        activity: Activity,
        newsEntity: NewsEntity,
        listener: ZXADVideoListener,
        callback: ZXADCallback1
    ) {
        LogUtils.d(
            "huang",
            "播放激励视频广告源:" + newsEntity.adPlatform + " -- codeId=" + newsEntity.codeId
        );
        when (newsEntity.adPlatform) {
            ZXADType.PLANTFORM_AD_GDT -> {
                GDTAdUtils.playCacheRewardAd(activity, newsEntity, listener, callback)
            }
            ZXADType.PLANTFORM_AD_TT -> {
                TTADUtils.playCacheRewardAd(activity, newsEntity, listener, callback)
            }
//            ZXADType.PLANTFORM_AD_SH -> {
//                callback.onAdFail()
//            }
            ZXADType.PLANTFORM_AD_SIGNMOB -> {
                SMADUtils.playCacheRewardAd(activity, listener, callback)
            }
//            ZXADType.PLANTFORM_AD_BD -> {
//                callback.onAdFail()
//            }
            //优量宝
            ZXADType.PLANTFORM_SH_YLB -> {
                //code:60008 -- message:激励视频请求合法，广告暂时无填充
                WNManager.playCacheRewardAd(activity, newsEntity, listener, callback)
            }
            //快手
            ZXADType.PLANTFORM_AD_KUS -> {
                KSADUtils.playCacheRewardAd(activity, newsEntity, listener, callback)
            }
//            //汇量
//            ZXADType.PLANTFORM_AD_HL -> {
//                HLAdUtils.playCacheRewardAd(newsEntity, listener, callback)
//            }
            ZXADType.PLANTFORM_AD_NEWS -> {
                NewsUtils.showReward(activity, listener, callback)
            }
            //风行
            ZXADType.PLANTFORM_AD_FENGXING -> {
                FunShionUtils.playReward(activity, newsEntity, listener, callback)
            }

            else -> {
                callback.onAdFail()
                listener.onError("没有广告")
            }
        }
    }


    fun setTimeOut(time: Long) {
        TIME_OUT = time
    }

    //检查缓存是否超时 广告类型
    fun checkTimeOut(type: String): Boolean {
        if (AdCache.adCacheTimeOutList != null && AdCache.adCacheTimeOutList.size > 0) {
            if ((System.currentTimeMillis() - AdCache.adCacheTimeOutList[type]!!) >= TIME_OUT) {
                return true
            }
        }
        return false
    }

    /**
     *播放广告
     */
    fun playRewardAd(
        slotName: String,
        actionName: String,
        activity: Activity,
        listener: ZXADVideoListener
    ) {
        if (!isInit) {
            listener.onError("sdk没有初始化")
            return
        }
        var entity = AdCache.cacheAdMap[AdCache.cacheAdMapKey]
        var entityB = AdCache.cacheAdMapB[AdCache.cacheAdMapKey]
        var targetEntity: NewsEntity? = null

        if (entity != null && entityB != null) {
            LogUtils.d(TAG, "竞价：A:" + entity.codePrice + " --- B:" + entityB.codePrice)
            if (entity.codePrice > entityB.codePrice) {
                targetEntity = entity
            } else {
                targetEntity = entityB
            }
        } else if (entity == null) {
            LogUtils.d(TAG, "竞价：A is null")
            targetEntity = entityB
        } else if (entityB == null) {
            LogUtils.d(TAG, "竞价：B is null")
            targetEntity = entity
        }

        MainLooper.get()?.post(Runnable {
            if (targetEntity != null && !checkTimeOut(AdEventUtils.AD_MODEL_REWARD)) {
                targetEntity?.actionName = actionName
                //有缓存数据
                var callback: ZXADCallback1 = object : ZXADCallback1 {
                    override fun onAdSuccess() {

                    }

                    override fun onAdFail() {
                        AdCache.cacheAdMap.clear()
                        AdCache.cacheAdMapB.clear()
                        LogUtils.e(
                            "huang",
                            "播放失败   播放失败走原始流程" + "    ${targetEntity?.codeId}   ${targetEntity?.adPlatform}"
                        )
                        loadRewardVideoAd(slotName, actionName, activity, listener);
                    }
                }
                playCacheRewardAd(activity, targetEntity, listener, callback)
                if (entityB != null) {
                    LogUtils.e("huang", "有缓存的数据，走缓存:" + targetEntity.codeGroup + "组")
                    if ("A".equals(targetEntity.codeGroup)) {
                        AdCache.cacheAdMap.remove(AdCache.cacheAdMapKey)
                        LogUtils.e("huang", "有B组策略 清除缓存:A组")
                    } else {
                        AdCache.cacheAdMapB.remove(AdCache.cacheAdMapKey)
                        LogUtils.e("huang", "有B组策略 清除缓存:B组")
                    }
                } else {
                    LogUtils.e("huang", "有缓存的数据，走正常缓存 无B组策略 清除")
                    AdCache.cacheAdMap.remove(AdCache.cacheAdMapKey)
                }
            } else {
                AdCache.cacheAdMap.remove(AdCache.cacheAdMapKey)
                AdCache.cacheAdMapB.remove(AdCache.cacheAdMapKey)
                LogUtils.e("huang", "超时   没有缓存数据走原始流程")
                loadRewardVideoAd(slotName, actionName, activity, listener);
            }

        })
    }


}