package com.ym.admodule.ylb

import android.app.Activity
import android.util.Log
import com.wannuosili.sdk.*
import com.ym.admodule.config.AdCache
import com.ym.admodule.config.AdInfo
import com.ym.admodule.config.AdManager
import com.ym.admodule.config.ZXADCallback
import com.ym.admodule.listener.ZXADVideoListener
import com.ym.modulecommon.module.NewsEntity
import com.ym.modulecommon.utils.AdEventUtils
import com.ym.modulecommon.utils.LogUtils
import java.util.concurrent.ConcurrentLinkedQueue

/**
 * 优量宝
 */
object WNManager {
    private const val TAG = "WNManager"

    /**
     * 显示激励视频广告
     * @param slotId 代码位ID
     * @param orientation 0:横屏, 1:竖屏
     */
    fun loadRewardVideoAd(
        activity: Activity,
        entity: NewsEntity,
        listener: ZXADVideoListener,
        callback: ZXADCallback
    ) {
        val slot = WNAdSlot.Builder()
            .setSlotId(entity?.codeId ?: "")
            .setOrientation(WNAdConstant.REWARD_VIDEO_AD_PORTRAIT)
            .build()
        var startTime = System.currentTimeMillis()
        WNAdSdk.getAdManager()
            .loadRewardVideoAd(slot, object : WNRewardVideoAd.RewardVideoAdListener {
                override fun onError(code: Int, message: String) {
                    AdEventUtils.onEventPullFail(entity, AdEventUtils.AD_MODEL_REWARD)
                    AdEventUtils.onEvent(entity,code,message)
                    callback.onAdFail()
                }

                override fun onLoad(ad: WNRewardVideoAd) {
                    AdEventUtils.onEventPullSuccess(entity, AdEventUtils.AD_MODEL_REWARD)
                    ad.interactionListener = object : WNRewardVideoAd.InteractionListener {
                        override fun onAdShow() {
                            listener.onAdShow()
                            callback.onAdSuccess()
                            AdEventUtils.onEventShow(entity)
                        }

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

                        override fun onAdClose() {
                            listener.onAdClose(AdInfo(entity.codeId))
                            LogUtils.e(TAG,"优良宝 onAdClose")
                        }

                        override fun onVideoComplete() {
                        }

                        override fun onRewardVerify(
                            rewardVerify: Boolean,
                            rewardAmount: Int,
                            rewardName: String
                        ) {
                            AdEventUtils.onEventComplete(entity, AdEventUtils.AD_MODEL_REWARD)
                        }
                    }
                    if (ad.type == WNAdConstant.AD_TYPE_DOWNLOAD) {
                        ad.downloadListener = object : WNAdDownloadListener {
                            override fun onDownloadStarted(
                                totalBytes: Long,
                                fileName: String,
                                appName: String
                            ) {
                            }

                            override fun onDownloadFinished(
                                totalBytes: Long,
                                fileName: String,
                                appName: String
                            ) {
                            }

                            override fun onDownloadFailed(
                                fileName: String,
                                appName: String
                            ) {
                            }
                        }
                    }
                    ad.showRewardVideoAd(activity)
                }
            })
    }

    //=============================================预加载===========================================
    //预加载
    fun loadCacheRewardAd(
        activity: Activity,
        entity: NewsEntity,
        callback: ZXADCallback
    ) {
        if (mRewardCacheMap[entity.codeId] != null) {
            if (mRewardCacheMap[entity.codeId]?.size!! >= AdCache.AdCacheNum) {
                return
            }
        }
        val slot = WNAdSlot.Builder()
            .setSlotId(entity.codeId)
            .setOrientation(WNAdConstant.REWARD_VIDEO_AD_PORTRAIT)
            .build()
        if (activity != null) {
            activity?.runOnUiThread {
                WNAdSdk.getAdManager()
                    .loadRewardVideoAd(slot, object : WNRewardVideoAd.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, "codeId=" + entity.codeId)
                            LogUtils.d(TAG, "code=" + code + "--- message=" + message)
                        }

                        override fun onLoad(ad: WNRewardVideoAd) {
                            AdEventUtils.onEventPullSuccess(entity, AdEventUtils.AD_MODEL_REWARD)
                            callback.onAdSuccess()
                            setRewardVideo(entity.codeId, ad)
                        }
                    })
            }
        }

    }

    //播放缓存
    fun playCacheRewardAd(
        activity: Activity,
        newsEntity: NewsEntity,
        listener: ZXADVideoListener,
        callback: ZXADCallback
    ) {
        var ad = getRewardVideo(activity, newsEntity.codeId)
        if (ad != null) {
            ad.interactionListener = object : WNRewardVideoAd.InteractionListener {
                override fun onAdShow() {
                    AdEventUtils.onEventShow(newsEntity)
                    callback.onAdSuccess()
                    listener.onAdShow()
                }

                override fun onAdClick() {
                    listener.onAdVideoBarClick()
                    AdEventUtils.onEventClick(newsEntity, AdEventUtils.AD_MODEL_REWARD)

                }

                override fun onAdClose() {
                    listener.onAdClose(AdInfo(newsEntity.codeId))
                    LogUtils.e(TAG,"优良宝 onAdClose")
                }

                override fun onVideoComplete() {

                }

                override fun onRewardVerify(
                    rewardVerify: Boolean,
                    rewardAmount: Int,
                    rewardName: String
                ) {
                    listener.onSuccess()
                    AdEventUtils.onEventComplete(newsEntity, AdEventUtils.AD_MODEL_REWARD)
                }
            }
            ad.showRewardVideoAd(activity)
        } else {
            callback.onAdFail()
        }
    }

    private val mRewardCacheMap = HashMap<String, ConcurrentLinkedQueue<WNRewardVideoAd>>()
    private fun setRewardVideo(codeId: String?, ksRewardAD: WNRewardVideoAd) {
        if (codeId == null)
            return
        if (mRewardCacheMap[codeId] != null) {
            var ksRewardVideoAds = mRewardCacheMap[codeId]
            if (ksRewardVideoAds == null) {
                ksRewardVideoAds = ConcurrentLinkedQueue()
            }
            ksRewardVideoAds.offer(ksRewardAD)
            mRewardCacheMap[codeId] = ksRewardVideoAds
        } else {
            val concurrentLinkedQueue = ConcurrentLinkedQueue<WNRewardVideoAd>()
            concurrentLinkedQueue.offer(ksRewardAD)
            mRewardCacheMap[codeId] = concurrentLinkedQueue
        }
    }

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

    fun cleanRewardCache() {
        mRewardCacheMap.clear()
    }


}