package com.ym.admodule.sm

import android.app.Activity
import android.content.EntityIterator
import android.os.Handler
import android.os.Message
import android.view.ViewGroup
import com.bytedance.sdk.openadsdk.TTNativeExpressAd
import com.sigmob.windad.Splash.WindSplashAD
import com.sigmob.windad.Splash.WindSplashADListener
import com.sigmob.windad.Splash.WindSplashAdRequest
import com.sigmob.windad.WindAdError
import com.sigmob.windad.WindAds
import com.sigmob.windad.interstitial.WindInterstitialAd
import com.sigmob.windad.interstitial.WindInterstitialAdListener
import com.sigmob.windad.interstitial.WindInterstitialAdRequest
import com.sigmob.windad.rewardedVideo.WindRewardAdRequest
import com.sigmob.windad.rewardedVideo.WindRewardInfo
import com.sigmob.windad.rewardedVideo.WindRewardedVideoAd
import com.sigmob.windad.rewardedVideo.WindRewardedVideoAdListener
import com.ym.admodule.config.AdCache
import com.ym.admodule.config.AdInfo
import com.ym.admodule.config.ZXADCallback
import com.ym.admodule.csj.TTADUtils
import com.ym.admodule.gdt.GDTAdUtils
import com.ym.admodule.listener.ZXADFullVideoListener
import com.ym.admodule.listener.ZXADSplashListener
import com.ym.admodule.listener.ZXADVideoListener
import com.ym.modulecommon.module.NewsEntity
import com.ym.modulecommon.utils.AdEventUtils
import com.ym.modulecommon.utils.AdEventUtils.onEventPullFail
import com.ym.modulecommon.utils.AdPreference
import com.ym.modulecommon.utils.LogUtils
import java.util.concurrent.ConcurrentLinkedQueue


//signmob 广告
object SMADUtils {

    private val TAG = "SMADUtils"

    //开屏
    fun loadSplashAd(
        newsEntity: NewsEntity, activity: Activity, container: ViewGroup,
        zxadListener: ZXADSplashListener,
        zxadCallback: ZXADCallback
    ) {
        val splashAdRequest = WindSplashAdRequest(newsEntity?.codeId, "", null)
        splashAdRequest.isDisableAutoHideAd = true
        splashAdRequest.fetchDelay = 3
        var mWindSplashAD =
            WindSplashAD(activity, container, splashAdRequest, object : WindSplashADListener {
                override fun onSplashAdSuccessPresent() {
                    AdEventUtils.onEventPullSuccess(newsEntity, AdEventUtils.AD_MODEL_SPLAH)
                    AdEventUtils.onEventShow(newsEntity)
                    zxadListener.onAdShow()
                    zxadCallback.onAdSuccess()
                }

                override fun onSplashAdClicked() {
                    AdEventUtils.onEventClick(newsEntity, AdEventUtils.AD_MODEL_SPLAH)
                }

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

                override fun onSplashAdSuccessLoad() {

                }

                override fun onSplashAdFailToLoad(p0: WindAdError?, p1: String?) {
                    onEventPullFail(newsEntity, AdEventUtils.AD_MODEL_SPLAH)
                    AdEventUtils.onEvent(newsEntity,p0?.errorCode,p0?.message)
                    zxadCallback.onAdFail()
                }

            })
    }


    //激励视频
    fun loadRewardVideoAd(
        activity: Activity,
        entity: NewsEntity,
        listener: ZXADVideoListener?,
        callback: ZXADCallback?
    ) {
        val startTime = System.currentTimeMillis()
        WindAds.requestPermission(activity);
        val windRewardedVideoAd = WindRewardedVideoAd.sharedInstance()
        val request = WindRewardAdRequest(entity.codeId, AdPreference.getUid() ?: "", null)
        windRewardedVideoAd.loadAd(request)
        windRewardedVideoAd.setWindRewardedVideoAdListener(object : WindRewardedVideoAdListener {
            override fun onVideoAdPlayError(p0: WindAdError?, p1: String?) {
                AdEventUtils.onEventShowFail(entity, AdEventUtils.AD_MODEL_REWARD)

            }

            override fun onVideoAdPreLoadFail(p0: String?) {
                AdEventUtils.onEventPullFail(entity, AdEventUtils.AD_MODEL_REWARD)
                AdEventUtils.onEvent(entity,"",p0)
            }

            override fun onVideoAdPlayStart(p0: String?) {
                listener?.onAdShow()
                callback?.onAdSuccess()
                AdEventUtils.onEventShow(entity)

            }

            override fun onVideoAdClosed(p0: WindRewardInfo?, p1: String?) {
                listener?.onAdClose(AdInfo(entity.codeId))
            }

            override fun onVideoAdPlayEnd(p0: String?) {
                AdEventUtils.onEventComplete(entity, AdEventUtils.AD_MODEL_REWARD)
            }

            override fun onVideoAdLoadSuccess(p0: String?) {
                AdEventUtils.onEventPullSuccess(entity, AdEventUtils.AD_MODEL_REWARD)
            }

            override fun onVideoAdPreLoadSuccess(p0: String?) {
            }

            override fun onVideoAdClicked(p0: String?) {
                listener?.onAdVideoBarClick()
                AdEventUtils.onEventClick(entity, AdEventUtils.AD_MODEL_REWARD)
            }

            override fun onVideoAdLoadError(p0: WindAdError?, p1: String?) {
                AdEventUtils.onEventPullFail(entity, AdEventUtils.AD_MODEL_REWARD)
                AdEventUtils.onEvent(entity,p0?.errorCode,p0?.message)
                callback?.onAdFail()
            }
        })

        val handler: Handler = object : Handler() {
            override fun handleMessage(msg: Message) {
                super.handleMessage(msg)
                if (System.currentTimeMillis() - startTime > 6000) {
                    removeCallbacksAndMessages(null)
                    return
                }
                if (windRewardedVideoAd.isReady(request.placementId)) {
                    windRewardedVideoAd.show(activity, request)
                    removeCallbacksAndMessages(null)
                } else {
                    sendEmptyMessageDelayed(1, 20)
                }
            }
        }
        handler.sendEmptyMessageDelayed(1, 20)

    }

    //=============================================预加载===========================================
    private val mSgmAdCache: ConcurrentLinkedQueue<Map<WindRewardAdRequest, WindRewardedVideoAd>> =
        ConcurrentLinkedQueue()

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

    private var zxVideoListener: ZXADVideoListener? = null
//    private var zxPlayListener: ZXADCallback? = null

    //只能在播放完之后缓存
    fun loadCacheRewardAd(
        activity: Activity,
        entity: NewsEntity,
        callback: ZXADCallback
    ) {
        var windRewardedVideoAd = WindRewardedVideoAd.sharedInstance()
        var request = WindRewardAdRequest(entity.codeId, AdPreference.getUid() ?: "", null)
        if (activity != null) {
            activity?.runOnUiThread {
                windRewardedVideoAd.loadAd(request)
                windRewardedVideoAd.setWindRewardedVideoAdListener(object :
                    WindRewardedVideoAdListener {
                    override fun onVideoAdPlayError(p0: WindAdError?, p1: String?) {
                        AdEventUtils.onEventShowFail(entity, AdEventUtils.AD_MODEL_REWARD)
                        zxVideoListener?.onError("${entity?.adPlatform},errorMsg:${p0?.message},errorCode:${p0?.errorCode}")
                        callback?.onAdFail()
                        LogUtils.e(TAG, p1.toString() + p0?.errorCode)
                    }

                    override fun onVideoAdPreLoadFail(p0: String?) {
                        AdEventUtils.onEventPullFail(entity, AdEventUtils.AD_MODEL_REWARD)
                        AdEventUtils.onEvent(entity,"",p0)
                        LogUtils.e(TAG, p0.toString())

                    }

                    override fun onVideoAdPlayStart(p0: String?) {
                        AdEventUtils.onEventShow(entity)
                        zxVideoListener?.onAdShow()
                    }

                    override fun onVideoAdClosed(p0: WindRewardInfo?, p1: String?) {
                        zxVideoListener?.onAdClose(AdInfo(entity.codeId))
                        zxVideoListener = null
                    }

                    override fun onVideoAdPlayEnd(p0: String?) {
                        AdEventUtils.onEventComplete(entity, AdEventUtils.AD_MODEL_REWARD)

                    }

                    override fun onVideoAdLoadSuccess(p0: String?) {
                        AdEventUtils.onEventPullSuccess(entity, AdEventUtils.AD_MODEL_REWARD)
                        zxVideoListener?.onSuccess()
                        callback.onAdSuccess()
                        var map: Map<WindRewardAdRequest, WindRewardedVideoAd> =
                            mapOf(request to windRewardedVideoAd)
                        mSgmAdCache.offer(map)
                    }

                    override fun onVideoAdPreLoadSuccess(p0: String?) {
                    }

                    override fun onVideoAdClicked(p0: String?) {
                        AdEventUtils.onEventClick(entity, AdEventUtils.AD_MODEL_REWARD)
                    }

                    override fun onVideoAdLoadError(p0: WindAdError?, p1: String?) {
                        AdEventUtils.onEventPullFail(entity, AdEventUtils.AD_MODEL_REWARD)
                        AdEventUtils.onEvent(entity,p0?.errorCode,p0?.message)
                        callback.onAdFail()
                        LogUtils.e(TAG, p1.toString() + p0?.errorCode)

                    }
                })
            }
        }
    }
//TODO ======================================插屏，全屏  start======================================================================


    //直接加载signmob广告
    fun showFuccessAd(activity: Activity,
                      entity: NewsEntity,
                      listener: ZXADFullVideoListener,
                      callback: ZXADCallback){

        val windInterstitialAd = WindInterstitialAd.sharedInstance()
        //placementId 必填,USER_ID,OPTIONS可不填，
        val request = WindInterstitialAdRequest(
            entity.codeId,
            AdPreference.getUid() ?: "",
            null
        )
        windInterstitialAd?.setWindInterstitialAdListener(object : WindInterstitialAdListener {
            //仅sigmob渠道有回调，聚合其他平台无次回调
            override fun onInterstitialAdPreLoadSuccess(placementId: String) {
                //Toast.makeText(mContext, "插屏广告数据返回成功", Toast.LENGTH_SHORT).show()
            }

            //仅sigmob渠道有回调，聚合其他平台无次回调
            override fun onInterstitialAdPreLoadFail(placementId: String) {
                //Toast.makeText(mContext, "插屏广告数据返回失败", Toast.LENGTH_SHORT).show()
                callback.onAdFail()
            }

            override fun onInterstitialAdLoadSuccess(placementId: String) {
                //Toast.makeText(mContext, "插屏广告缓存加载成功", Toast.LENGTH_SHORT).show()
                try {
                    //检查广告是否准备完毕
                    if (windInterstitialAd.isReady(request.getPlacementId())) {
                        //广告播放
                        windInterstitialAd.show(activity, request)
                    }
                } catch (e: IllegalArgumentException) {
                    e.printStackTrace()
                }

            }

            override fun onInterstitialAdPlayStart(placementId: String) {
                AdEventUtils.onEventShow(entity)
                listener?.onAdShow()
            }

            override fun onInterstitialAdPlayEnd(placementId: String) {
            }

            override fun onInterstitialAdClicked(placementId: String) {
                listener?.onAdVideoBarClick()
                AdEventUtils.onEventClick(entity, AdEventUtils.AD_MODEL_SCREEN)
            }

            //成功的回调
            override fun onInterstitialAdClosed(placementId: String) {
                listener?.onAdClose(AdInfo(entity.codeId))
                AdEventUtils.onEventComplete(entity, AdEventUtils.AD_MODEL_SCREEN)
            }

            /**
             * 加载广告错误回调
             * WindAdError 插屏错误内容
             * placementId 广告位
             */
            override fun onInterstitialAdLoadError(
                windAdError: WindAdError,
                placementId: String
            ) {
                listener?.onError(windAdError.message)
            }

            /**
             * 播放错误回调
             * WindAdError 插屏错误内容
             * placementId 广告位
             */
            override fun onInterstitialAdPlayError(
                windAdError: WindAdError,
                placementId: String
            ) {
                listener?.onError(windAdError.message)
                AdEventUtils.onEventShowFail(entity, AdEventUtils.AD_MODEL_SCREEN)
            }
        })


        windInterstitialAd?.loadAd(activity, request)


    }

    //TODO 加载插屏，或者全屏视频
    fun loadFullScreenAd( activity: Activity,
                          entity: NewsEntity,
                          callback: ZXADCallback){

        val windInterstitialAd = WindInterstitialAd.sharedInstance()
        //placementId 必填,USER_ID,OPTIONS可不填，
        val request = WindInterstitialAdRequest(
            entity.codeId,
            AdPreference.getUid() ?: "",
            null
        )
        windInterstitialAd?.setWindInterstitialAdListener(object : WindInterstitialAdListener {
            //仅sigmob渠道有回调，聚合其他平台无次回调
            override fun onInterstitialAdPreLoadSuccess(placementId: String) {
                AdEventUtils.onEventPullSuccess(entity, AdEventUtils.AD_MODEL_SCREEN)
                //Toast.makeText(mContext, "插屏广告数据返回成功", Toast.LENGTH_SHORT).show()
                mInterAdCacheMap.add(request)
                callback.onAdSuccess()
                LogUtils.e(TAG, "与加载成功")

            }

            //仅sigmob渠道有回调，聚合其他平台无次回调
            override fun onInterstitialAdPreLoadFail(placementId: String) {
                AdEventUtils.onEventPullFail(entity, AdEventUtils.AD_MODEL_SCREEN)
                LogUtils.e(TAG, "与加载失败")

                callback.onAdFail()
                //Toast.makeText(mContext, "插屏广告数据返回失败", Toast.LENGTH_SHORT).show()
            }

            override fun onInterstitialAdLoadSuccess(placementId: String) {
                //Toast.makeText(mContext, "插屏广告缓存加载成功", Toast.LENGTH_SHORT).show()
                LogUtils.e(TAG, "缓存  加载成功")
            }

            override fun onInterstitialAdPlayStart(placementId: String) {
                AdEventUtils.onEventShow(entity)
                listenerFull?.onAdShow()
            }

            override fun onInterstitialAdPlayEnd(placementId: String) {
            }

            override fun onInterstitialAdClicked(placementId: String) {
                listenerFull?.onAdVideoBarClick()
                AdEventUtils.onEventClick(entity, AdEventUtils.AD_MODEL_SCREEN)
            }

            //成功的回调
            override fun onInterstitialAdClosed(placementId: String) {
                listenerFull?.onAdClose(AdInfo(entity.codeId))
                AdEventUtils.onEventComplete(entity, AdEventUtils.AD_MODEL_SCREEN)
            }

            /**
             * 加载广告错误回调
             * WindAdError 插屏错误内容
             * placementId 广告位
             */
            override fun onInterstitialAdLoadError(
                windAdError: WindAdError,
                placementId: String
            ) {
                listenerFull?.onError(windAdError.message)
                callback.onAdFail()
            }

            /**
             * 播放错误回调
             * WindAdError 插屏错误内容
             * placementId 广告位
             */
            override fun onInterstitialAdPlayError(
                windAdError: WindAdError,
                placementId: String
            ) {
                listenerFull?.onError(windAdError.message)
                AdEventUtils.onEventShowFail(entity, AdEventUtils.AD_MODEL_SCREEN)
            }
        })


        windInterstitialAd?.loadAd(activity, request)
    }


    private var listenerFull:ZXADFullVideoListener? = null
    //播放全屏视频
    fun playCacheFullAd(activity: Activity,
                        entity: NewsEntity, listener: ZXADFullVideoListener, callback: ZXADCallback){

        if (mInterAdCacheMap != null && mInterAdCacheMap.isNotEmpty() && mInterAdCacheMap[mInterAdCacheMap.size - 1] != null) {
            val windInterstitialAd = WindInterstitialAd.sharedInstance()
            val request = mInterAdCacheMap[mInterAdCacheMap.size - 1]
            try {
                //检查广告是否准备完毕
                if (windInterstitialAd.isReady(request.getPlacementId())) {
                    //广告播放
                    LogUtils.e(TAG, "有缓存，展示全屏视频")
                    listenerFull = listener
                    windInterstitialAd.show(activity, request)
                }
            } catch (e: IllegalArgumentException) {
                e.printStackTrace()
            }
        }else{
            //直接加载
            LogUtils.e(TAG, "直接加载全屏视频")

            showFuccessAd(activity,entity,listener,callback)
        }
    }


//TODO ======================================插屏，全屏   end======================================================================


    fun playCacheRewardAd(
        activity: Activity,
        listener: ZXADVideoListener,
        callback: ZXADCallback
    ) {
        zxVideoListener = listener
        if (mSgmAdCache.size > 0) {
            var rewardVideoADMap = mSgmAdCache.poll()
            rewardVideoADMap.forEach {
                it.key
                it.value
                if (it.value.isReady(it.key.placementId)) {
                    LogUtils.d("MingZhong", "播放SM")
                    it.value.show(activity, it.key)
                } else {
                    LogUtils.d("MingZhong", "播放SM失败")
                    callback.onAdFail()
                }
            }
        } else {
            LogUtils.d("MingZhong", "播放SM失败")
            callback.onAdFail()
        }
    }

    fun cleanRewardCache() {
        mSgmAdCache.clear()
    }


}