package com.ym.admodule.csj


import android.R.attr.orientation
import android.R.attr.tag
import android.app.Activity
import android.content.Context
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import com.bytedance.sdk.openadsdk.*
import com.bytedance.sdk.openadsdk.TTAdNative.*
import com.bytedance.sdk.openadsdk.TTFullScreenVideoAd.FullScreenVideoAdInteractionListener
import com.bytedance.sdk.openadsdk.TTNativeExpressAd.ExpressAdInteractionListener
import com.bytedance.sdk.openadsdk.TTRewardVideoAd.RewardAdInteractionListener
import com.ym.admodule.config.*
import com.ym.admodule.gdt.GDTAdUtils
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.widget.DislikeDialog
import com.ym.modulecommon.module.NewsEntity
import com.ym.modulecommon.utils.AdEventUtils
import com.ym.modulecommon.utils.LogUtils
import com.ym.modulecommon.utils.PhoneUtils
import com.ym.modulecommon.utils.Utils
import okhttp3.internal.Util
import java.util.HashMap
import java.util.concurrent.ConcurrentLinkedQueue


/**
 * 穿山甲广告
 */
object TTADUtils {
    private val TAG = "TTAdUtils"

    //插屏
    fun loadInteractionAd(
        activity: Activity,
        newsEntity: NewsEntity,
        zxadModelConfig: ZXADSizeConfig?,
        callback: ZXADCallback
    ) {
        val width = Utils.px2dip(PhoneUtils.getScreenWidth(activity).toFloat() - Utils.dip2px(20))
        val heigt = (width*3)/2
        var mTTAdNative = TTAdSdk.getAdManager().createAdNative(activity)//baseContext建议为activity
        var adSlot = AdSlot.Builder()
            .setCodeId(newsEntity.codeId)
            .setImageAcceptedSize(zxadModelConfig?.width?:width, zxadModelConfig?.height?:heigt)
            .setExpressViewAcceptedSize(
                zxadModelConfig?.width?.toFloat()?:width.toFloat(),
                zxadModelConfig?.height?.toFloat()?:heigt.toFloat()
            )
            .setSupportDeepLink(true)
            .build();

        mTTAdNative.loadInteractionExpressAd(adSlot, object : NativeExpressAdListener {
            override fun onNativeExpressAdLoad(ttInteractionAd: MutableList<TTNativeExpressAd>?) {
                if (ttInteractionAd == null || ttInteractionAd.size <= 0) {
                    return
                }
                val ttNativeExpressAd = ttInteractionAd[0]
                ttNativeExpressAd.render()
                ttNativeExpressAd.setExpressInteractionListener(object :
                    ExpressAdInteractionListener {
                    override fun onAdClicked(p0: View?, p1: Int) {
                        AdEventUtils.onEventClick(newsEntity, "")
                    }

                    override fun onAdShow(p0: View?, p1: Int) {
                        AdEventUtils.onEventShow(newsEntity)

                    }

                    override fun onRenderSuccess(p0: View?, p1: Float, p2: Float) {
                        ttNativeExpressAd.showInteractionExpressAd(activity)
                        AdEventUtils.onEventPullSuccess(newsEntity, "")
                        callback?.onAdSuccess()
                    }

                    override fun onRenderFail(p0: View?, p1: String?, p2: Int) {
                        callback.onAdFail()
                        AdEventUtils.onEvent(newsEntity, p2, p1)
                    }

                })
            }

            override fun onError(code: Int, message: String?) {
                callback.onAdFail()
            }
        })
    }


    //预加载
    fun loadInteraction2Ad(
        activity: Activity,
        newsEntity: NewsEntity,
        zxadModelConfig: ZXADSizeConfig?,
        callback: ZXADCallback
    ) {
        LogUtils.e("hloadInterstitialAd    穿山甲开始与加载" + System.currentTimeMillis())
        val width = Utils.px2dip(PhoneUtils.getScreenWidth(activity).toFloat() - Utils.dip2px(20))
        val heigt = (width*3)/2

        var mTTAdNative = TTAdSdk.getAdManager().createAdNative(activity)//baseContext建议为activity
        var adSlot = AdSlot.Builder()
            .setCodeId(newsEntity.codeId)
            .setImageAcceptedSize(zxadModelConfig?.width?:width, zxadModelConfig?.height?:heigt)
            .setExpressViewAcceptedSize(
                zxadModelConfig?.width?.toFloat()?:width.toFloat(),
                zxadModelConfig?.height?.toFloat()?:heigt.toFloat()
            )
            .setSupportDeepLink(true)
            .build();

        mTTAdNative.loadInteractionExpressAd(adSlot, object : NativeExpressAdListener {
            override fun onNativeExpressAdLoad(ttInteractionAd: MutableList<TTNativeExpressAd>?) {
                if (ttInteractionAd == null || ttInteractionAd.size <= 0) {
                    return
                }
                val ttNativeExpressAd = ttInteractionAd[0]

                if (mInterAdCacheMap.size > AdCache.interAdNumber) {
                    val get = mInterAdCacheMap[0]
                    if (get != null) {
                        get?.destroy()
                    }
                }

                LogUtils.e("hloadInterstitialAd    穿山甲开始与加载 成功" + System.currentTimeMillis())
                mInterAdCacheMap.add(ttNativeExpressAd)
                callback.onAdSuccess()
            }

            override fun onError(code: Int, message: String?) {
                callback.onAdFail()
            }
        })

//
    }

    private  var interactionAd :TTNativeExpressAd? = null
    fun destroyInteractionAd(){
        if(interactionAd!=null){
            interactionAd?.expressAdView?.visibility = View.GONE
            interactionAd?.destroy()
        }
    }


    fun showInteractionAd(
        activity: Activity,
        newsEntity: NewsEntity,
        zxadModelConfig: ZXADSizeConfig,
        callback: ZXADCallback
    ) {

        LogUtils.d(TAG, "run 穿山甲 信息流 showFeedAd ")
        if (activity == null || newsEntity.codeId == null) return
        if (mInterAdCacheMap != null && mInterAdCacheMap.isNotEmpty() && mInterAdCacheMap[mInterAdCacheMap.size - 1] != null) {
            val mTTad = mInterAdCacheMap[mInterAdCacheMap.size - 1]
            if (mTTad != null) {


                mTTad.setExpressInteractionListener(object :
                    ExpressAdInteractionListener {
                    override fun onAdClicked(p0: View?, p1: Int) {



                        AdEventUtils.onEventClick(newsEntity, "")
                        LogUtils.e(TAG," 插屏  onAdClicked")
                    }

                    override fun onAdShow(p0: View?, p1: Int) {
                        AdEventUtils.onEventShow(newsEntity)
                        LogUtils.e(TAG," 插屏  onAdShow")
                    }

                    override fun onRenderSuccess(p0: View?, p1: Float, p2: Float) {
                        mTTad.showInteractionExpressAd(activity)
                        AdEventUtils.onEventPullSuccess(newsEntity, "")
                        callback?.onAdSuccess()
                        LogUtils.e(TAG," 插屏  onRenderSuccess")
                    }

                    override fun onRenderFail(p0: View?, p1: String?, p2: Int) {
                        callback.onAdFail()
                        AdEventUtils.onEvent(newsEntity, p2, p1)
                        LogUtils.e(TAG," 插屏  onRenderFail")
                    }

                })
                startTime = System.currentTimeMillis()
                mTTad.render()

                this.interactionAd = mTTad
                LogUtils.d(TAG, "run 穿山甲 插屏 render 渲染")
            }
        }else{
            loadInteractionAd(activity,newsEntity,zxadModelConfig,callback)
        }

    }

    /**
     * 开屏广告
     */
    fun loadSplashAd(
        data: NewsEntity,
        activity: Activity,
        views: ViewGroup,
        zxadListener: ZXADSplashListener, zxadCallback: ZXADCallback
    ) {

        var mTTAdNative = TTAdSdk.getAdManager().createAdNative(activity)//baseContext建议为activity
        val adSlot = AdSlot.Builder()
            .setCodeId(data.codeId)
            .setSupportDeepLink(true)
            .setImageAcceptedSize(720, 1280)
            .build()
        mTTAdNative?.loadSplashAd(adSlot, object : TTAdNative.SplashAdListener {
            override fun onError(i: Int, s: String) {
                AdEventUtils.onEventPullFail(data, AdEventUtils.AD_MODEL_SPLAH)
                AdEventUtils.onEvent(data, i?.toString(), s)
                zxadCallback.onAdFail()
            }

            override fun onTimeout() {
                AdEventUtils.onEventShowFail(data, AdEventUtils.AD_MODEL_SPLAH)
                zxadCallback.onAdFail()
            }

            override fun onSplashAdLoad(ad: TTSplashAd) {
                AdEventUtils.onEventPullSuccess(data, AdEventUtils.AD_MODEL_SPLAH)
                zxadCallback.onAdSuccess()
                zxadListener.onAdShow()
                val view = ad.splashView
                views?.removeAllViews()
                views?.addView(view)
                ad.setSplashInteractionListener(object : TTSplashAd.AdInteractionListener {
                    override fun onAdClicked(view: View, i: Int) {
                        AdEventUtils.onEventClick(data, AdEventUtils.AD_MODEL_SPLAH)
                    }

                    override fun onAdShow(view: View, i: Int) {
                        zxadListener.onAdShow()
                        AdEventUtils.onEventShow(data)
                    }

                    override fun onAdSkip() {
                        zxadListener.onAdSkip()
                    }

                    override fun onAdTimeOver() {
                        zxadListener.onAdSkip()
                    }
                })
            }
        }, 3000)
    }


    /**
     * 信息流广告
     */
    fun loadFeedAd(
        activity: Activity,
        newsEntity: NewsEntity,
        zxadModelConfig: ZXADSizeConfig,
        container: FrameLayout,
        callback: ZXADCallback
    ) {
        val mTTAdNative = TTAdSdk.getAdManager().createAdNative(activity) //baseContext建议为activity
        var adSlot = AdSlot.Builder()
            .setCodeId(newsEntity.codeId)
            .setExpressViewAcceptedSize(
                zxadModelConfig.width.toFloat(),
                zxadModelConfig.height.toFloat()
            )
            .setSupportDeepLink(true)
            .setAdCount(1)
            .build();
        mTTAdNative.loadNativeExpressAd(adSlot, object : NativeExpressAdListener {
            override fun onNativeExpressAdLoad(p0: MutableList<TTNativeExpressAd>?) {
                if (p0 == null || p0.isEmpty()) {
                    AdEventUtils.onEventPullFail(newsEntity, AdEventUtils.AD_MODEL_BIGIMG)
                    callback.onAdFail()
                    return
                }
                AdEventUtils.onEventPullSuccess(newsEntity, AdEventUtils.AD_MODEL_BIGIMG)
                val mTTAd = p0[0]
                bindAdListener(newsEntity, mTTAd, container, callback)
                startTime = System.currentTimeMillis()
                mTTAd.render()
            }

            override fun onError(p0: Int, p1: String?) {
                AdEventUtils.onEventPullFail(newsEntity, AdEventUtils.AD_MODEL_BIGIMG)
                AdEventUtils.onEvent(newsEntity, p0?.toString(), p1)
                callback.onAdFail()
                container.removeAllViews()

            }

        })
    }

    /**
     * 加载大图
     */
    fun loadFeedAd(
        activity: Activity,
        newsEntity: NewsEntity,
        zxadModelConfig: ZXADSizeConfig,
        callback: ZXADCallback
    ) {

        val mTTAdNative = TTAdSdk.getAdManager().createAdNative(activity) //baseContext建议为activity
        var adSlot = AdSlot.Builder()
            .setCodeId(newsEntity.codeId)
            .setExpressViewAcceptedSize(
                zxadModelConfig.width.toFloat(),
                zxadModelConfig.height.toFloat()
            )
            .setSupportDeepLink(true)
            .setAdCount(1)
            .build();

        mTTAdNative.loadNativeExpressAd(adSlot, object : NativeExpressAdListener {
            override fun onNativeExpressAdLoad(p0: MutableList<TTNativeExpressAd>?) {
                if (p0 == null || p0.isEmpty()) {
                    AdEventUtils.onEventPullFail(newsEntity, AdEventUtils.AD_MODEL_BIGIMG)
                    callback.onAdFail()
                    return
                }

                AdEventUtils.onEventPullSuccess(newsEntity, AdEventUtils.AD_MODEL_BIGIMG)
                val mTTAd = p0[0]
                if (mTTAd != null) {
                    if (mFeedAdCacheMap.size > AdCache.feedAdNumber) {
                        val get = mFeedAdCacheMap[0]
                        if (get != null) {
                            get?.destroy()
                        }
                    }
                    mFeedAdCacheMap.add(mTTAd)
                    callback?.onAdSuccess()
                }
            }

            override fun onError(p0: Int, p1: String?) {
                AdEventUtils.onEventPullFail(newsEntity, AdEventUtils.AD_MODEL_BIGIMG)
                AdEventUtils.onEvent(newsEntity, p0, p1)
                callback.onAdFail()
            }
        })
    }

    //展示大图
    fun showFeedAd(activity: Activity, newsEntity: NewsEntity, container: FrameLayout) {
        LogUtils.d(TAG, "run 穿山甲 信息流 showFeedAd ")
        if (activity == null || newsEntity.codeId == null) return
        if (mFeedAdCacheMap != null && mFeedAdCacheMap.isNotEmpty() && mFeedAdCacheMap[mFeedAdCacheMap.size - 1] != null) {
            val mTTad = mFeedAdCacheMap[mFeedAdCacheMap.size - 1]
            if (mTTad != null) {
                bindAdListener(newsEntity, mTTad, container, object : ZXADCallback {
                    override fun onAdSuccess() {
                    }

                    override fun onAdFail() {
                    }
                })
                startTime = System.currentTimeMillis()
                mTTad.render()
                LogUtils.d(TAG, "run 穿山甲 信息流 render 渲染")
            }
        }

    }


    private var startTime: Long = 0


    private fun bindAdListener(
        entity: NewsEntity,
        ad: TTNativeExpressAd,
        container: FrameLayout,
        callback: ZXADCallback
    ) {
        ad.setExpressInteractionListener(object : ExpressAdInteractionListener {
            override fun onAdClicked(view: View, type: Int) {
                AdEventUtils.onEventClick(entity, AdEventUtils.AD_MODEL_BIGIMG)
            }

            override fun onAdShow(view: View, type: Int) {
                callback.onAdSuccess()
                AdEventUtils.onEventShow(entity)
            }

            override fun onRenderFail(
                view: View,
                msg: String,
                code: Int
            ) {
                AdEventUtils.onEventShowFail(entity, AdEventUtils.AD_MODEL_BIGIMG)
                callback.onAdFail()
                container.visibility = View.GONE
            }

            override fun onRenderSuccess(
                view: View,
                width: Float,
                height: Float
            ) {
                container.removeAllViews()
                container.addView(view)
                container.visibility = View.VISIBLE
                LogUtils.d(TAG, "run 穿山甲 信息流 显示")
            }

        })
        bindDislike(container.context, ad, true, container)
        if (ad.interactionType != TTAdConstant.INTERACTION_TYPE_DOWNLOAD) {
            return
        }
    }

    /**
     * 设置广告的不喜欢，注意：强烈建议设置该逻辑，如果不设置dislike处理逻辑，则模板广告中的 dislike区域不响应dislike事件。
     * @param ad
     * @param customStyle 是否自定义样式，true:样式自定义
     */
    private fun bindDislike(
        context: Context,
        ad: TTNativeExpressAd,
        customStyle: Boolean,
        container: FrameLayout
    ) {
        if (customStyle) {
            val words = ad.filterWords
            if (words == null || words.isEmpty()) {
                return
            }
            val dislikeDialog = DislikeDialog(context, words)
            dislikeDialog.setOnDislikeItemClick(object : DislikeDialog.OnDislikeItemClick {
                override fun onItemClick(filterWord: FilterWord) {
                    container.removeAllViews()
                    container.visibility = View.GONE
                }
            })
            ad.setDislikeDialog(dislikeDialog)
            return
        }
    }


    /**
     *加载 激励视频
     */
    fun loadRewardVideoAd(
        activity: Activity,
        entity: NewsEntity,
        listener: ZXADVideoListener,
        callback: ZXADCallback
    ) {

        val mTTAdNative =
            TTAdSdk.getAdManager().createAdNative(activity)
        val adSlot = AdSlot.Builder()
            .setCodeId(entity?.codeId ?: "")
            .setSupportDeepLink(true)
            .setAdCount(2)
            .setImageAcceptedSize(1080, 1920)
            .setRewardName("金币")
            .setRewardAmount(3)
            .setUserID("")
            .setOrientation(TTAdConstant.VERTICAL)
            .setMediaExtra("media_extra")
            .build()

        var mttRewardVideoAd: TTRewardVideoAd? = null
        mTTAdNative.loadRewardVideoAd(adSlot, object : RewardVideoAdListener {
            override fun onError(code: Int, message: String) {
                AdEventUtils.onEventPullFail(entity, AdEventUtils.AD_MODEL_REWARD)
                AdEventUtils.onEvent(entity, code, message)
                callback.onAdFail()
                LogUtils.d(
                    TAG,
                    "${entity.adPlatform}: errorCode:" + code + " -- errorMsg:" + message
                )
            }

            //视频广告加载后的视频文件资源缓存到本地的回调
            override fun onRewardVideoAdLoad(ad: TTRewardVideoAd) {
                mttRewardVideoAd = ad
            }

            //视频广告素材加载到，如title,视频url等，不包括视频文件
            override fun onRewardVideoCached() {
                AdEventUtils.onEventPullSuccess(entity, AdEventUtils.AD_MODEL_REWARD)
                callback.onAdSuccess()
                mttRewardVideoAd?.setRewardAdInteractionListener(object :
                    RewardAdInteractionListener {
                    override fun onAdShow() {
                        listener.onAdShow()
                        AdEventUtils.onEventShow(entity)
                    }

                    override fun onAdVideoBarClick() {
                        AdEventUtils.onEventClick(entity, AdEventUtils.AD_MODEL_REWARD)
                        listener.onAdVideoBarClick()
                    }

                    override fun onAdClose() {
                        listener.onAdClose(AdInfo(entity?.codeId))
                    }

                    override fun onVideoError() {
                        AdEventUtils.onEventShowFail(entity, AdEventUtils.AD_MODEL_REWARD)
                        callback.onAdFail()
                    }

                    override fun onVideoComplete() {
                    }

                    override fun onRewardVerify(
                        rewardVerify: Boolean,
                        rewardAmount: Int,
                        rewardName: String
                    ) {
                        AdEventUtils.onEventComplete(entity, AdEventUtils.AD_MODEL_REWARD)
                    }

                    override fun onSkippedVideo() {
                    }
                })
                mttRewardVideoAd?.showRewardVideoAd(activity)
            }
        })
    }

    private var isSkippedVideo = false

    //全屏视频 (目前和gdt插屏保持一种类型)
    fun loadFullVideoAd(
        activity: Activity,
        entity: NewsEntity,
        listener: ZXADFullVideoListener,
        callback: ZXADCallback
    ) {
        val mTTAdNative = TTAdSdk.getAdManager().createAdNative(activity) //baseContext建议为activity
        //设置广告参数
        val adSlot = AdSlot.Builder()
            .setCodeId(entity.codeId)
            .setSupportDeepLink(true) //个性化模板广告需要设置期望个性化模板广告的大小,单位dp,全屏视频场景，只要设置的值大于0即可
            .setExpressViewAcceptedSize(500f, 500f)
            .setImageAcceptedSize(1080, 1920)
            .setOrientation(orientation)
            .build()
        //加载全屏视频
        mTTAdNative.loadFullScreenVideoAd(adSlot, object : FullScreenVideoAdListener {
            override fun onError(code: Int, message: String) {
                AdEventUtils.onEvent(entity, code, message)
                callback?.onAdFail()
                LogUtils.d(
                    TAG,
                    "CSJ 全屏 : errorCode:" + code + " -- errorMsg:" + message
                )
            }

            override fun onFullScreenVideoAdLoad(ad: TTFullScreenVideoAd) {
                LogUtils.d(TAG, "CSJ 全屏 加载成功")
                AdEventUtils.onEventPullSuccess(entity, "")
                callback?.onAdSuccess()
                var mttFullVideoAd = ad
                mttFullVideoAd.setFullScreenVideoAdInteractionListener(object :
                    FullScreenVideoAdInteractionListener {
                    override fun onAdShow() {
                        isSkippedVideo = false
                        listener.onAdShow()
                        AdEventUtils.onEventShow(entity)
                        LogUtils.d(TAG, "CSJ 全屏 onAdShow")
                    }

                    override fun onAdVideoBarClick() {
                        LogUtils.d(TAG, "CSJ 全屏 onAdClick")
                        listener.onAdVideoBarClick()
                        AdEventUtils.onEventClick(entity, AdEventUtils.AD_MODEL_SCREEN)
                    }

                    override fun onAdClose() {
                        listener.onAdClose(isSkippedVideo,AdInfo(entity?.codeId))
                        LogUtils.d(TAG, "CSJ 全屏 onAdClose isSkippedVideo=" + isSkippedVideo)
                    }

                    override fun onVideoComplete() {
                        isSkippedVideo = false
                        AdEventUtils.onEventComplete(entity, "")
                        LogUtils.d(TAG, "CSJ 全屏 onVideoComplete")
                    }

                    override fun onSkippedVideo() {
                        isSkippedVideo = true
                        LogUtils.d(TAG, "CSJ 全屏 onSkippedVideo")
//                        listener.onAdClose()
                    }
                })
                mttFullVideoAd.showFullScreenVideoAd(activity)
            }

            override fun onFullScreenVideoCached() {
            }
        })
    }

    fun loadDrawFeedVideoAd(activity: Activity, entity: NewsEntity, listener: ZXADDrawListener) {
        val mTTAdNative =
            TTAdSdk.getAdManager().createAdNative(activity) //baseContext建议为activity
        //设置广告参数
        var adSlot = AdSlot.Builder()
            .setCodeId(entity.codeId) //开发者申请的广告位
            .setSupportDeepLink(true)
            .setImageAcceptedSize(1080, 1920)
            .setAdCount(1)
            .build();
        //加载广告
        mTTAdNative.loadDrawFeedAd(adSlot, object : TTAdNative.DrawFeedAdListener {
            override fun onDrawFeedAdLoad(ads: MutableList<TTDrawFeedAd>?) {
                if (ads == null || ads.isEmpty()) {
                    listener.onError()
                    return;
                }
                for (ad in ads) {
                    ad.setActivityForDownloadApp(activity);
                    ad.setDrawVideoListener(object : TTDrawFeedAd.DrawVideoListener {
                        override fun onClick() {
                            AdEventUtils.onEventClick(entity, AdEventUtils.AD_MODEL_REWARD)
                        }

                        override fun onClickRetry() {

                        }
                    });
                }
                ads.get(0).setCanInterruptVideoPlay(true);
                listener.onDrawFeedAdLoad(ads[0])
            }

            override fun onError(p0: Int, p1: String?) {
            }
        });
    }


    fun loadDrawFeedSpecialVideoAd(
        activity: Activity,
        entity: NewsEntity,
        listener: ZXADDrawListener,
        zxadModelConfig: ZXADSizeConfig
    ) {
        val mTTAdNative =
            TTAdSdk.getAdManager().createAdNative(activity) //baseContext建议为activity
        var adSlot = AdSlot.Builder()
            .setCodeId(entity.codeId) //广告位id
            .setSupportDeepLink(true)
            .setAdCount(1) //请求广告数量为1到3条
            .setExpressViewAcceptedSize(
                zxadModelConfig.width.toFloat(),
                zxadModelConfig.height.toFloat()
            )
            .setImageAcceptedSize(640, 320)//这个参数设置即可，不影响个性化模板广告的size
            .build();
        mTTAdNative.loadExpressDrawFeedAd(adSlot, object : NativeExpressAdListener {
            override fun onNativeExpressAdLoad(ads: MutableList<TTNativeExpressAd>?) {
                if (ads == null || ads.size == 0) {
                    return;
                }
                listener.onNativeExpressAdLoad(ads[0])
            }

            override fun onError(p0: Int, p1: String?) {
                listener.onError()
            }
        })
    }

    //=============================================预加载===========================================
    fun loadCacheRewardAd(
        activity: Activity,
        entity: NewsEntity,
        callback: ZXADCallback
    ) {
        var tempAd: TTRewardVideoAd? = null
        val mTTAdNative =
            TTAdSdk.getAdManager().createAdNative(activity) //baseContext建议为activity
        val adSlot = AdSlot.Builder()
            .setCodeId(entity.codeId)
            .setSupportDeepLink(true)
            .setAdCount(2)
            .setImageAcceptedSize(1080, 1920)
            .setRewardName("金币") //奖励的名称
            .setRewardAmount(3) //奖励的数量
            .setUserID("")//userId
            .setOrientation(TTAdConstant.VERTICAL) //设置期望视频播放的方向，为TTAdConstant.HORIZONTAL或TTAdConstant.VERTICAL
            .setMediaExtra("media_extra") //用户透传的信息，可不传
            .build()

        if (activity != null) {
            activity?.runOnUiThread {
                mTTAdNative.loadRewardVideoAd(adSlot, object : RewardVideoAdListener {
                    override fun onError(code: Int, message: String) {
                        AdEventUtils.onEventPullFail(entity, AdEventUtils.AD_MODEL_REWARD)
                        AdEventUtils.onEvent(entity, code, message)
                        callback.onAdFail()
                        LogUtils.d(
                            TAG,
                            "预加载:${entity.adPlatform}: errorCode:" + code + " -- errorMsg:" + message
                        )
                    }

                    override fun onRewardVideoCached() {
                        LogUtils.d(TAG,"onRewardVideoCached")
                        if (tempAd != null) {
                            AdEventUtils.onEventPullSuccess(entity, AdEventUtils.AD_MODEL_REWARD)
                            callback.onAdSuccess()
                            setRewardVideo(entity.codeId, tempAd!!)
                        } else {
                            callback.onAdFail()
                        }
                    }

                    override fun onRewardVideoAdLoad(ad: TTRewardVideoAd) {
                        LogUtils.d(TAG,"onRewardVideoAdLoad")
                        tempAd = ad
                    }
                })
            }
        }

    }

    fun playCacheRewardAd(
        activity: Activity,
        entity: NewsEntity,
        listener: ZXADVideoListener,
        callback: ZXADCallback
    ) {
        var ttCacheRewardAd = getRewardVideo(activity, entity.codeId)
        if (ttCacheRewardAd != null) {
            ttCacheRewardAd.setRewardAdInteractionListener(object :
                RewardAdInteractionListener {
                override fun onAdShow() {
                    listener.onAdShow()
                    AdEventUtils.onEventShow(entity)
                }

                override fun onAdVideoBarClick() {
                    listener.onAdVideoBarClick()
                    AdEventUtils.onEventClick(entity, AdEventUtils.AD_MODEL_SPLAH)
                }

                override fun onAdClose() {
                    listener.onAdClose(AdInfo(entity.codeId))
                }

                override fun onVideoError() {
                    AdEventUtils.onEventShowFail(entity, AdEventUtils.AD_MODEL_REWARD)
                }

                override fun onVideoComplete() {
                }

                override fun onRewardVerify(
                    rewardVerify: Boolean,
                    rewardAmount: Int,
                    rewardName: String
                ) {
                    AdEventUtils.onEventComplete(entity, AdEventUtils.AD_MODEL_REWARD)
                }

                override fun onSkippedVideo() {
                }
            })
            ttCacheRewardAd.showRewardVideoAd(activity)
        } else {
            callback.onAdFail()
        }
    }

    private val mRewardCacheMap = HashMap<String, ConcurrentLinkedQueue<TTRewardVideoAd>>()
    private val mFeedAdCacheMap = arrayListOf<TTNativeExpressAd>()

    private val mInterAdCacheMap = arrayListOf<TTNativeExpressAd>()//插屏广告

    private fun setRewardVideo(codeId: String?, ttRewardAD: TTRewardVideoAd) {
        if (codeId == null)
            return
        if (mRewardCacheMap[codeId] != null) {
            var ksRewardVideoAds = mRewardCacheMap[codeId]
            if (ksRewardVideoAds == null) {
                ksRewardVideoAds = ConcurrentLinkedQueue()
            }
            ksRewardVideoAds.offer(ttRewardAD)
            mRewardCacheMap[codeId] = ksRewardVideoAds
        } else {
            val concurrentLinkedQueue = ConcurrentLinkedQueue<TTRewardVideoAd>()
            concurrentLinkedQueue.offer(ttRewardAD)
            mRewardCacheMap[codeId] = concurrentLinkedQueue
        }
        LogUtils.d("MingZhong", "TT${codeId} 缓存数量" + mRewardCacheMap[codeId]?.size)
    }

    private fun getRewardVideo(activity: Activity, codeId: String?): TTRewardVideoAd? {
        if (mRewardCacheMap[codeId] != null) {
            val ttRewardVideoAds = mRewardCacheMap[codeId]
            if (ttRewardVideoAds != null && ttRewardVideoAds.size > 0) {
                LogUtils.d("MingZhong", "播放TT${codeId}")
                return ttRewardVideoAds.poll();
            }
        }
        LogUtils.d("MingZhong", "播放TT失败${codeId}")
        return null
    }


    //预加载全屏视屏 (目前和gdt插屏保持一种类型)
    fun loadCacheFullVideoAd(
        activity: Activity,
        entity: NewsEntity,
        callback: ZXADCallback
    ) {
        val mTTAdNative = TTAdSdk.getAdManager().createAdNative(activity) //baseContext建议为activity
        //设置广告参数
        val adSlot = AdSlot.Builder()
            .setCodeId(entity.codeId)
            .setSupportDeepLink(true) //个性化模板广告需要设置期望个性化模板广告的大小,单位dp,全屏视频场景，只要设置的值大于0即可
            .setExpressViewAcceptedSize(500f, 500f)
            .setImageAcceptedSize(1080, 1920)
            .setOrientation(orientation)
            .build()
        //加载全屏视频
        mTTAdNative.loadFullScreenVideoAd(adSlot, object : FullScreenVideoAdListener {
            override fun onError(code: Int, message: String) {
                AdEventUtils.onEvent(entity, code, message)
                callback?.onAdFail()
                LogUtils.d(
                    TAG,
                    "CSJ 全屏 : errorCode:" + code + " -- errorMsg:" + message
                )
            }

            override fun onFullScreenVideoAdLoad(ad: TTFullScreenVideoAd) {
                LogUtils.d(TAG, "CSJ 全屏 加载成功")
                callback?.onAdSuccess()
                setFullVideo(entity?.codeId, ad)
                AdEventUtils.onEventPullSuccess(entity, "")
            }

            override fun onFullScreenVideoCached() {
            }
        })
    }


    fun playCacheFullAd(
        activity: Activity,
        entity: NewsEntity,
        listener: ZXADFullVideoListener,
        callback: ZXADCallback
    ) {
        var ttCacheRewardAd = getFullVideo(activity, entity.codeId)
        if (ttCacheRewardAd != null) {
            ttCacheRewardAd.setFullScreenVideoAdInteractionListener(object :
                FullScreenVideoAdInteractionListener {
                override fun onAdShow() {
                    isSkippedVideo = false
                    listener.onAdShow()
                    AdEventUtils.onEventShow(entity)
                    LogUtils.d(TAG, "CSJ 全屏 onAdShow")
                }

                override fun onAdVideoBarClick() {
                    LogUtils.d(TAG, "CSJ 全屏 onAdClick")
                    listener.onAdVideoBarClick()
                    AdEventUtils.onEventClick(entity, AdEventUtils.AD_MODEL_SCREEN)
                }

                override fun onAdClose() {
                    listener.onAdClose(isSkippedVideo, AdInfo((entity.codeId)))
                    LogUtils.d(TAG, "CSJ 全屏 onAdClose")
                }

                override fun onVideoComplete() {
                    isSkippedVideo = false
                    AdEventUtils.onEventComplete(entity, "")
                    LogUtils.d(TAG, "CSJ 全屏 onVideoComplete")
                }

                override fun onSkippedVideo() {
                    isSkippedVideo = true
                    LogUtils.d(TAG, "CSJ 全屏 onSkippedVideo")
                }
            })
            ttCacheRewardAd.showFullScreenVideoAd(activity)
        } else {
            callback.onAdFail()
        }
    }

    private val mFullCacheMap = HashMap<String, ConcurrentLinkedQueue<TTFullScreenVideoAd>>()

    private fun setFullVideo(codeId: String?, ttFullAD: TTFullScreenVideoAd) {
        if (codeId == null)
            return
        if (mFullCacheMap[codeId] != null) {
            var ttFullVideoAds = mFullCacheMap[codeId]
            if (ttFullVideoAds == null) {
                ttFullVideoAds = ConcurrentLinkedQueue()
            }
            ttFullVideoAds.offer(ttFullAD)
            mFullCacheMap[codeId] = ttFullVideoAds
        } else {
            val concurrentLinkedQueue = ConcurrentLinkedQueue<TTFullScreenVideoAd>()
            concurrentLinkedQueue.offer(ttFullAD)
            mFullCacheMap[codeId] = concurrentLinkedQueue
        }
        LogUtils.d("MingZhong", "TT${codeId} 缓存数量" + mRewardCacheMap[codeId]?.size)
    }

    private fun getFullVideo(activity: Activity, codeId: String?): TTFullScreenVideoAd? {
        if (mFullCacheMap[codeId] != null) {
            val ttFullVideoAds = mFullCacheMap[codeId]
            if (ttFullVideoAds != null && ttFullVideoAds.size > 0) {
                LogUtils.d("MingZhong", "播放TT${codeId}")
                return ttFullVideoAds.poll();
            }
        }
        LogUtils.d("MingZhong", "播放TT失败${codeId}")
        return null
    }

    fun cleanRewardCache() {
        mRewardCacheMap.clear()
    }

}
