package com.zx.ad.platform.csj

import android.app.Activity
import android.content.Context
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.FrameLayout
import com.bytedance.sdk.openadsdk.*
import com.zx.ad.callback.AdLoadCallBack
import com.zx.ad.callback.InterertionAdListener
import com.zx.ad.callback.RewardVideoAdListener
import com.zx.ad.callback.SplashAdListener
import com.zx.ad.modulecommon.module.NewsEntity
import com.zx.ad.platform.ADType
import com.zx.ad.utils.AdEventUtils
import com.zx.ad.utils.LogUtils
import com.zx.ad.utils.UIUtils


/**
 * @author (wangXuewei)
 * @datetime 2022-06-13 19:06 GMT+8
 * @detail :穿山甲广告平台
 */
object CSJAdManager {


    private var mTTAdNative: TTAdNative? = null
    private var context: Context? = null
    fun init(context: Context) {
        this.context = context
        mTTAdNative = TTAdSdk.getAdManager().createAdNative(context)//baseContext建议为activity
    }

    fun adInit(context: Context, appId: String, initCallback: TTAdSdk.InitCallback?) {
        TTAdManagerHolder.init(context, appId, initCallback)
        //TTAdManagerHolder.init(context, "5335826", initCallback)
    }

    private var splashAd: TTSplashAd? = null

    /**
     *  加载开屏广告
     */
    fun loadSplashAd(context: Context, entity: NewsEntity, loadCallBack: AdLoadCallBack) {
        //本次针对穿山甲处理，当加入其它平台时需要测试未初始化的情况下，是否有error回调
        if (!TTAdSdk.isInitSuccess()) {
            Log.e("MXL", "TTAdSdk.isInitSuccess")
            adInit(context, entity.codeAppId, object : TTAdSdk.InitCallback {
                override fun success() {
                    loadSplashAd2(context, entity, loadCallBack)
                }

                override fun fail(p0: Int, p1: String?) {
                    loadCallBack.OnAdLoadFail("CSJ Ad Init Fail  p0${p0} p1${p1}")
                }
            })
            return
        } else {
            loadSplashAd2(context, entity, loadCallBack)
        }
    }

    private fun loadSplashAd2(context: Context, entity: NewsEntity, loadCallBack: AdLoadCallBack) {
        mTTAdNative = TTAdManagerHolder.get().createAdNative(context)
        if (mTTAdNative == null) {
            loadCallBack.OnAdLoadFail("loadSplashAd mTTAdNative is null")
            return
        }
        val splashWidthPx = UIUtils.getScreenWidthInPx(context)
        val screenHeightPx = UIUtils.getScreenHeight(context)
        val splashWidthDp = UIUtils.getScreenWidthDp(context)
        val screenHeightDp = UIUtils.px2dip(context, screenHeightPx.toFloat()).toFloat()
        var adSlot = AdSlot.Builder()
            .setCodeId(entity.codeId)
            .setImageAcceptedSize(splashWidthPx, screenHeightPx)
            .setExpressViewAcceptedSize(splashWidthDp, screenHeightDp)
            .build()
        mTTAdNative?.loadSplashAd(adSlot, object : TTAdNative.SplashAdListener {
            override fun onError(p0: Int, p1: String?) {
                Log.d("AdManager", "p0" + p0)
                AdEventUtils.onEventPullFail(entity)
                loadCallBack.OnAdLoadFail("CSJ p0:${p0} p1:${p1}")
            }

            override fun onTimeout() {
                loadCallBack.OnAdLoadFail("CSJ onTimeout")
            }

            override fun onSplashAdLoad(p0: TTSplashAd?) {
                AdEventUtils.onEventPullSuccess(entity)
                splashAd = p0;
                loadCallBack.OnAdLoadSuccess(ADType.PLATFORM_AD_TT, entity)
            }
        })
    }

    /**
     *  展示开屏广告
     */
    fun showSplashAd(
        context: Activity,
        entity: NewsEntity,
        mSplashContainer: FrameLayout?,
        listener: SplashAdListener
    ) {
        if (splashAd == null) {
            listener.onError("CSJ splashAd is Null")
            return
        }
        //获取SplashView
        var view = splashAd?.splashView
        if (view != null && mSplashContainer != null && !context.isFinishing) {
            mSplashContainer.removeAllViews()
            //把SplashView 添加到ViewGroup中,注意开屏广告view：width =屏幕宽；height >=75%屏幕高
            mSplashContainer.addView(view)
            //设置不开启开屏广告倒计时功能以及不显示跳过按钮,如果这么设置，您需要自定义倒计时逻辑
            //ad.setNotAllowSdkCountdown();
        } else {
            AdEventUtils.onEventShowFail(entity)
            listener.onError("CSJ view Exception")
            return
        }

        splashAd?.setSplashInteractionListener(object : TTSplashAd.AdInteractionListener {
            override fun onAdClicked(p0: View?, p1: Int) {

            }

            override fun onAdShow(p0: View?, p1: Int) {
                AdEventUtils.onEventShowSuccess(entity)
                listener.onAdShow()
            }

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

            override fun onAdTimeOver() {
                AdEventUtils.onEventComplete(entity)
                listener.onAdSkip()
            }
        })
    }

    private var innterstitialAd: TTFullScreenVideoAd? = null

    //加载插屏广告
    fun loadIntertialAd(context: Context, entity: NewsEntity, loadCallBack: AdLoadCallBack) {
        mTTAdNative = TTAdManagerHolder.get().createAdNative(context)
//        val adSlot = AdSlot.Builder()
//            .setCodeId("949814576")
//            .setSupportDeepLink(true)
//            .setAdCount(2) //请求广告数量为1到3条
//            //  .setExpressViewAcceptedSize(300f, 300f) //期望模板广告view的size,单位dp
//            .setAdLoadType(TTAdLoadType.LOAD) //推荐使用，用于标注此次的广告请求用途为预加载（当做缓存）还是实时加载，方便后续为开发者优化相关策略
//            .build()

        //step4:创建广告请求参数AdSlot,具体参数含义参考文档
        val adSlot = AdSlot.Builder()
            .setCodeId(entity.codeId) //此次加载广告的用途是实时加载，当用来作为缓存时，请使用：TTAdLoadType.PRELOAD
            //.setCodeId("949814576") //此次加载广告的用途是实时加载，当用来作为缓存时，请使用：TTAdLoadType.PRELOAD
            .setAdLoadType(TTAdLoadType.LOAD)
            //  .setExpressViewAcceptedSize(200f,200f)
            .build()
        mTTAdNative?.loadFullScreenVideoAd(adSlot, object : TTAdNative.FullScreenVideoAdListener {
            override fun onError(p0: Int, p1: String?) {
                AdEventUtils.onEventPullFail(entity)
                Log.e("MXL", "CSJ Interaction Ad Fail" + p1)
                loadCallBack.OnAdLoadFail("CSJ Interaction error p0:${p0} p1:${p1}")
            }

            override fun onFullScreenVideoAdLoad(ad: TTFullScreenVideoAd?) {
                AdEventUtils.onEventPullSuccess(entity)
                innterstitialAd = ad
                loadCallBack.OnAdLoadSuccess(ADType.PLATFORM_AD_TT, entity)

            }

            override fun onFullScreenVideoCached() {
            }

            override fun onFullScreenVideoCached(p0: TTFullScreenVideoAd?) {
            }
        })
    }

    fun showIntereiAd(context: Activity, entity: NewsEntity, listener: InterertionAdListener) {
        if (innterstitialAd == null) {
            listener.onAdError("CSJ innterstitialAd Is Null")
            return
        }

        //step6:在获取到广告后展示
        //该方法直接展示广告
        //mttFullVideoAd.showFullScreenVideoAd(FullScreenVideoActivity.this);

        innterstitialAd?.showFullScreenVideoAd(
            context,
            TTAdConstant.RitScenes.GAME_GIFT_BONUS,
            null
        )
        innterstitialAd = null
        innterstitialAd?.setFullScreenVideoAdInteractionListener(object :
            TTFullScreenVideoAd.FullScreenVideoAdInteractionListener {
            override fun onAdShow() {
                AdEventUtils.onEventShowSuccess(entity)
                listener.onAdShow()
            }

            override fun onAdVideoBarClick() {

            }

            override fun onAdClose() {
                listener.onAdClose()
            }

            override fun onVideoComplete() {

            }

            override fun onSkippedVideo() {

            }
        })


    }

    private var rewardVideoAd: TTRewardVideoAd? = null

    /**
     *  加载激励视频广告
     */
    fun loadRewardVideoAd(context: Context, entity: NewsEntity, loadCallBack: AdLoadCallBack) {
        mTTAdNative = TTAdManagerHolder.get().createAdNative(context)
        var adSlot = AdSlot.Builder()
           .setCodeId(entity.codeId)
          //  .setCodeId("950127903")
            .setExpressViewAcceptedSize(500f, 500f)
            .setOrientation(TTAdConstant.VERTICAL) //必填参数，期望视频的播放方向：TTAdConstant.HORIZONTAL 或 TTAdConstant.VERTICAL
            .setAdLoadType(TTAdLoadType.UNKNOWN)//推荐使用，用于标注此次的广告请求用途为预加载（当做缓存）还是实时加载，方便后续为开发者优化相关策略
            .build()

        mTTAdNative?.loadRewardVideoAd(adSlot, object : TTAdNative.RewardVideoAdListener {
            override fun onError(p0: Int, p1: String?) {
                AdEventUtils.onEventPullFail(entity)
                Log.e("MXL","loadRewardVideoAdError:"+p1)
                loadCallBack.OnAdLoadFail("CSJ RewardVideoAd error p0:${p0} p1:${p1}")
            }

            override fun onRewardVideoAdLoad(p0: TTRewardVideoAd?) {
                AdEventUtils.onEventPullSuccess(entity)
            }

            override fun onRewardVideoCached() {

            }

            override fun onRewardVideoCached(p0: TTRewardVideoAd?) {
                rewardVideoAd = p0
                loadCallBack.OnAdLoadSuccess(ADType.PLATFORM_AD_TT, entity)
            }
        })
    }

    private var isSkipRewardVideoAd = false

    /**
     *  展示激励视频广告
     */
    fun showRewardVideoAd(
        context: Activity,
        entity: NewsEntity,
        listener: RewardVideoAdListener
    ) {
        if (rewardVideoAd == null) {
            listener.onRewardVideoAdError("CSJ rewardVideoAd Is Null")
            return
        }
        if (!context.isFinishing) {
            isSkipRewardVideoAd = false
            rewardVideoAd?.setRewardAdInteractionListener(object :
                TTRewardVideoAd.RewardAdInteractionListener {
                override fun onAdShow() {
                    AdEventUtils.onEventShowSuccess(entity)
                    LogUtils.d("onAdShow")
                    listener.onRewardVideoAdShow()
                }

                override fun onAdVideoBarClick() {
                    LogUtils.d("onAdVideoBarClick")
                }

                override fun onAdClose() {
                    LogUtils.d("onAdClose")
                    listener.onRewardVideoAdClose()
                }

                override fun onVideoComplete() {
                    AdEventUtils.onEventComplete(entity)
                    LogUtils.d("onVideoComplete")
                }

                override fun onVideoError() {
                    AdEventUtils.onEventShowFail(entity)
                    LogUtils.d("onVideoError")
                    Log.e("MXL","onVideoError")
                    listener.onRewardVideoAdError("Csj RewardVideoAd PlayError")
                }

                override fun onRewardVerify(
                    p0: Boolean,
                    p1: Int,
                    p2: String?,
                    p3: Int,
                    p4: String?
                ) {
                    LogUtils.d("onRewardVerify")
                    listener.onRewardVideoAdReward()
                }

                override fun onRewardArrived(p0: Boolean, p1: Int, p2: Bundle?) {
                    LogUtils.d("onRewardArrived")
                }

                override fun onSkippedVideo() {
                    LogUtils.d("onSkippedVideo")
                    isSkipRewardVideoAd = true
                }
            })

            rewardVideoAd?.showRewardVideoAd(context)
        } else {
            listener.onRewardVideoAdError("context is finish")
        }
    }

    fun onDestroy() {
        splashAd = null
        rewardVideoAd = null
    }

    fun requestByteDailyActiveBigImgFeed(
        codeId: String,
        expressViewWidth: Float,
        expressViewHeight: Float,
        callBack: TTAdNative.NativeExpressAdListener
    ) {

        val adSlot = AdSlot.Builder()
            .setCodeId(codeId)
            .setSupportDeepLink(false)
            .setExpressViewAcceptedSize(expressViewWidth, expressViewHeight)
//            .setImageAcceptedSize(640, 0)
            //     .setAdLoadType(TTAdLoadType.PRELOAD)
            .setAdCount(1)
            .build()
        //调用feed广告异步请求接口
//        mTTAdNative?.loadFeedAd(adSlot,callBack)
        mTTAdNative?.loadNativeExpressAd(adSlot, object : TTAdNative.NativeExpressAdListener {
            override fun onNativeExpressAdLoad(p0: MutableList<TTNativeExpressAd>?) {
                if (p0 != null && p0.size > 0) {
                    callBack.onNativeExpressAdLoad(p0)
                } else {
                    callBack?.onError(1000, "没有拉取到广告")
                }
            }

            override fun onError(p0: Int, p1: String?) {
                Log.e("MXL", "loadNativeExpressAdonError" + p1)
                callBack?.onError(p0, p1)
            }
        })
    }
}