package com.duben.microtribe.ad.video;

import android.app.Activity;
import android.os.Bundle;

import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdConstant;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTAdSdk;
import com.bytedance.sdk.openadsdk.TTRewardVideoAd;
import com.bytedance.sdk.openadsdk.mediation.ad.MediationAdSlot;
import com.duben.microtribe.BuildConfig;
import com.duben.microtribe.ad.AdManager;
import com.duben.microtribe.ad.AdStatusListener;
import com.duben.microtribe.common.Constant;
import com.duben.microtribe.utils.AppPreferencesManager;
import com.duben.microtribe.utils.LogUtil;
import com.duben.microtribe.utils.TimeRender;

import java.lang.ref.WeakReference;
import java.util.HashMap;

/**
 * GroMore激励视频广告
 * <p>
 * 注意*****这个类有预加载逻辑，不能复用
 */
public class InMoneyVideo {

    private static final String TAG = InMoneyVideo.class.getSimpleName();

    private static InMoneyVideo _inst;

    public static InMoneyVideo getInstance() {
        if (_inst == null) {
            _inst = new InMoneyVideo();
        }
        return _inst;
    }

    private InMoneyVideo() {
    }

    private String carrierType = "";

    // 当前播放的广告
    private String nowAdcode = "";
    private String nowEcpm = "";
    private String nowAdSource = "";

    private int isLoadSuccess = 0;  // 0-加载失败/未加载 1-加载中 2-加载成功
    private long adLoadTime = 0;    // 广告展示时间，45分钟后当前广告失效，重新预加载广告
    private long adPreingTime = 0;  // 防止预加载超时 2分钟

    private TTRewardVideoAd mttRewardAd;

    private WeakReference<Activity> weakActivity;

    private boolean isPreLoad = false;//是否是预加载调用，需要躲避监听

    private AdStatusListener adStatusListener;

    /**
     * 激励视频
     */
    public void preLoadAd(Activity activity, boolean isPreLoad) {
        this.isPreLoad = isPreLoad;

        boolean isOversped = TimeRender.INSTANCE.isOverspedMin(adLoadTime, AdManager.AD_NO_SHOWTIME_OUT);
        boolean isPreingOversped = TimeRender.INSTANCE.isOverspedMin(adPreingTime, AdManager.AD_REQUEST_TIME_OUT);

        this.weakActivity = new WeakReference(activity);

        LogUtil.d(TAG, "gromore预加载 激励视频广告-> 1、进入预加载  isPreLoad[为true是预加载调用]=" + isPreLoad);

        if ((isLoadSuccess == 0 // 加载失败
                || (adLoadTime > 0 && isOversped)  // 超过45分钟
                || (adPreingTime > 0 && isPreingOversped
                && isLoadSuccess == 1)) // 预加载超时
                && this.weakActivity.get() != null) {
            adPreingTime = System.currentTimeMillis();
            isLoadSuccess = 1;

            LogUtil.d(TAG, "gromore预加载 激励视频广告-> 2、执行预加载去了=" + isLoadSuccess);

            preLoadAd(activity);
        }
    }

    public void showRewardAd(Activity _activity, AdStatusListener adStatusListener
            , String carrier) {
        this.carrierType = carrier;
        this.adStatusListener = adStatusListener;
        this.weakActivity = new WeakReference(_activity);

        if (isLoadSuccess == 0) {
            LogUtil.e(TAG, "gromore预加载 激励视频广告--> showRewardAd  isLoadSuccess=" + isLoadSuccess);
            if (this.adStatusListener != null)
                this.adStatusListener.adFail();

            return;
        }

        // 请求未超过1分钟且上一个广告还在异步加载中，这次触发展示广告回调还没回来则返回
        boolean isPreingOversped = TimeRender.INSTANCE.isOverspedMin(adPreingTime, AdManager.AD_REQUEST_TIME_OUT);
        if (isLoadSuccess == 1 && isPreingOversped) {
            LogUtil.e(TAG, "gromore预加载 激励视频广告-->请求未超过1分钟且上一个广告还在异步加载中  isLoadSuccess=" + isLoadSuccess + "   isPreingOversped=" + isPreingOversped);
            if (this.adStatusListener != null)
                this.adStatusListener.adFail();
            return;
        }

        // 预加载广告成功 且 预加载广告时长未超过45分钟
        boolean isOversped = TimeRender.INSTANCE.isOverspedMin(adLoadTime, AdManager.AD_NO_SHOWTIME_OUT);
        if (isLoadSuccess == 2 && !isOversped && mttRewardAd != null
                && mttRewardAd.getMediationManager().isReady()
                && this.weakActivity.get() != null) {
            mttRewardAd.showRewardVideoAd(weakActivity.get());
            mttRewardAd.setRewardAdInteractionListener(mTTRewardedAdListener);
        } else {
            if (this.adStatusListener != null)
                this.adStatusListener.adFail();

            LogUtil.e(TAG, "gromore预加载 激励视频广告--> 5、展示广告时失败了，广告可能超时45分钟 onError ");
        }

        // 广告加载完成状态重置
        isLoadSuccess = 0;
    }

    private void preLoadAd(Activity activity) {

        TTAdNative adNativeLoader = TTAdSdk.getAdManager().createAdNative(activity);

        AdSlot adSlot = new AdSlot.Builder()
                .setCodeId(BuildConfig.GROMORE_VIDEO_CODE)
                .setUserID("")
                .setOrientation(TTAdConstant.VERTICAL)
                .setMediationAdSlot(
                        new MediationAdSlot.Builder()
                                .setRewardAmount(2000)
                                .setRewardName("")
                                .build()
                ).build();
        adNativeLoader.loadRewardVideoAd(adSlot, new TTAdNative.RewardVideoAdListener() {
            @Override
            public void onError(int i, String s) {
                isLoadSuccess = 0;

                LogUtil.e(TAG, "gromore预加载 激励视频广告-->onError  " + i + s + "isPreLoad[为true是预加载调用]=" + isPreLoad);

                // isPreLoad=true 表示是预加载调用  不需要调用监听回调
                if (!isPreLoad) {
                    if (adStatusListener != null) {
                        adStatusListener.adFail();
                    }
                }
                isPreLoad = false;
            }

            @Override
            public void onRewardVideoAdLoad(TTRewardVideoAd ttRewardVideoAd) {

            }

            @Override
            public void onRewardVideoCached() {

            }

            @Override
            public void onRewardVideoCached(TTRewardVideoAd ttRewardVideoAd) {
                LogUtil.d(TAG, "gromore预加载 激励视频广告--> 4、onRewardVideoCached ");
                isLoadSuccess = 2;
                adLoadTime = System.currentTimeMillis();

                if (adStatusListener != null) {
                    adStatusListener.adSuccess();
                }

                mttRewardAd = ttRewardVideoAd;
            }
        });

    }

    private final TTRewardVideoAd.RewardAdInteractionListener mTTRewardedAdListener = new TTRewardVideoAd.RewardAdInteractionListener() {
        @Override
        public void onAdShow() {
            if (mttRewardAd != null) {
                if (mttRewardAd.getMediationManager().getShowEcpm() != null) {
                    nowAdcode = mttRewardAd.getMediationManager().getShowEcpm().getSlotId();
                    nowEcpm = mttRewardAd.getMediationManager().getShowEcpm().getEcpm();
                    nowAdSource = mttRewardAd.getMediationManager().getShowEcpm().getSdkName();
                }
            }
            LogUtil.d(TAG, "gromore预加载 激励视频广告-->onAdShow");

            if (weakActivity.get() != null) {
                LogUtil.d(TAG, "gromore预加载 激励视频广告->onAdShow  触发预加载下次广告");
                AdManager.Companion.getInstance().preLoadAd(weakActivity.get(), true);
            }
        }

        @Override
        public void onAdVideoBarClick() {
            LogUtil.d(TAG, "gromore预加载 激励视频广告-->onAdVideoBarClick");
        }

        @Override
        public void onAdClose() {
            LogUtil.d(TAG, "gromore预加载 激励视频广告-->onAdClose");

            int adCount = AppPreferencesManager.INSTANCE.get().getInt(Constant.VEDIO_AD_COUNT, 0);
            if (adCount < 50) {
                AppPreferencesManager.INSTANCE.get().put(Constant.VEDIO_AD_COUNT, adCount+1);
            }

            HashMap<String, Object> vo = new HashMap<>();
            vo.put("adcode", nowAdcode);
            vo.put("ecpm", nowEcpm);
            vo.put("adSource", nowAdSource);
            vo.put("carrierType", carrierType);
            vo.put("adid", BuildConfig.GROMORE_VIDEO_CODE);
            if (adStatusListener != null) {
                adStatusListener.adClose(vo);
            }

            adStatusListener = null;
        }

        @Override
        public void onVideoComplete() {
            LogUtil.d(TAG, "gromore预加载 激励视频广告-->onVideoComplete");
        }

        @Override
        public void onVideoError() {
            isLoadSuccess = 0;
            LogUtil.e(TAG, "gromore预加载 激励视频广告-->onVideoError");

            if (adStatusListener != null) {
                adStatusListener.adFail();
            }
        }

        @Override
        public void onRewardVerify(boolean b, int i, String s, int i1, String s1) {

        }

        @Override
        public void onRewardArrived(boolean b, int i, Bundle bundle) {

        }

        @Override
        public void onSkippedVideo() {

        }
    };

}
