package com.mints.goodmoney.ad.video;

import android.app.Activity;

import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdConstant;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTRewardVideoAd;
import com.mints.goodmoney.BuildConfig;
import com.mints.goodmoney.common.Constant;
import com.mints.goodmoney.manager.TTNativeExpressManager;
import com.mints.goodmoney.manager.TrackManager;
import com.mints.goodmoney.manager.TtCsjAdManager;
import com.mints.goodmoney.manager.UserManager;
import com.mints.goodmoney.mvp.presenters.CsjVedioAdPresenter;
import com.mints.goodmoney.mvp.views.VedioAdManagerView;
import com.mints.goodmoney.utils.LogUtil;
import com.mints.goodmoney.utils.MD5;
import com.mints.goodmoney.utils.SPUtil;
import com.mints.library.utils.json.JsonUtil;

import java.util.HashMap;

/**
 * 穿山甲激励视频广告
 */
public class CsjVedioAdManager extends BaseVideoAd {

    private static CsjVedioAdManager _inst;
    private SPUtil spUtil;
    private int curCoin;
    private String extraId;
    private CsjVedioAdPresenter csjVedioAdPresenter;
    private CsjVedioAdListener csjVedioAdListener;

    Activity activity;
    private TTAdNative ttAdNative;
    private TTRewardVideoAd mttRewardVideoAd;
    private UserManager userManager;

    private boolean isClickScreen = true; // 是否点击屏幕跳转广告

    public static CsjVedioAdManager getInstance(Activity activity) {
        if (_inst != null) {
            return _inst;
        } else {
            _inst = new CsjVedioAdManager(activity);
            return _inst;
        }
    }

    private CsjVedioAdManager(Activity activity) {
        super(activity);
        init(activity);
        return;
    }

    private void init(Activity activity) {
        this.activity = activity;
        spUtil = SPUtil.getInstance();
        userManager = UserManager.getInstance();

        TTNativeExpressManager ttNativeExpressManager = new TTNativeExpressManager();
        ttAdNative = ttNativeExpressManager.initTTAd(false);

//        csjVedioAdPresenter = new CsjVedioAdPresenter();
//        csjVedioAdPresenter.attachView(this);
    }

    @Override
    public void onDestory() {
        if (mttRewardVideoAd != null) {
            mttRewardVideoAd.setRewardAdInteractionListener(null);
        }

//        if (csjVedioAdPresenter != null) {
//            csjVedioAdPresenter.dispose();
//            csjVedioAdPresenter.detachView();
//        }

        activity = null;
    }

    /**
     * 激励视频
     *
     * @param carrierType
     */
    @Override
    public void loadAd(Activity activity, int curCoin, String carrierType, String extraId) {
        this.activity = activity;
        isClickScreen = true;
        this.curCoin = curCoin;
        this.extraId = extraId;

        String codeId = TtCsjAdManager.TT_AD_VEDIO_MAIN_DEV;
        if (!BuildConfig.DEBUG) {
            switch (carrierType) {
                case Constant.CARRIER_VERSUS_VIDEO:// 每日任务视频
                    codeId = TtCsjAdManager.TT_AD_VEDIO_MAIN;
                    break;
                case Constant.CARRIER_OFFLINE_DOUBLE:// 离线收益翻倍
                case Constant.CARRIER_SIGNIN_HOMEPAGE_CARD:// 签到翻倍
                case Constant.CARRIER_WALK_BUBBLE:// 汽泡
                    codeId = TtCsjAdManager.TT_AD_VEDIO_MOREDIALOG;
                    break;
                case Constant.CARRIER_HOMEWATER:// 喝水
                    codeId = TtCsjAdManager.TT_AD_VEDIO_DRINK;
                    break;
                case Constant.CARRIER_CHALLENGE_TURN:// 大转盘
                    codeId = TtCsjAdManager.TT_AD_VEDIO_TURNABLE;
                    break;
                case Constant.CARRIER_CHALLENGE_CARD:// 刮刮乐
                    codeId = TtCsjAdManager.TT_AD_VEDIO_ERASE;
                    break;
                default:// 在线收益翻倍
                    codeId = TtCsjAdManager.TT_AD_VEDIO_MOREDIALOG;
                    break;
            }
        }
        String userID = userManager.getUserID();
        String tid = MD5.GetMD5Code(System.currentTimeMillis() + userID);

        if (mttRewardVideoAd != null) {
            mttRewardVideoAd.setRewardAdInteractionListener(null);
        }

        AdSlot adSlot = new AdSlot.Builder()
                .setCodeId(codeId)
                .setSupportDeepLink(true)
                //个性化模板广告需要设置期望个性化模板广告的大小,单位dp,激励视频场景，只要设置的值大于0即可。仅模板广告需要设置此参数
                .setExpressViewAcceptedSize(500, 500)
                .setImageAcceptedSize(1080, 1920)
                .setUserID(userID)//用户id,必传参数
                .setMediaExtra(JsonUtil.toJson(getAdMapVO(carrierType, tid)))
                .setOrientation(TTAdConstant.VERTICAL)
                .build();
        ttAdNative.loadRewardVideoAd(adSlot, new TTAdNative.RewardVideoAdListener() {
            @Override
            public void onError(int code, String message) {
                TrackManager.getInstance().addCallImp(Constant.AD_SOURCE_CSJ, Constant.EVENT_TYPE_ONE, String.valueOf(code), message);


                LogUtil.d("CsjVedioAdManager", "onError  " + code + message);
                if (csjVedioAdListener != null) {
                    csjVedioAdListener.csjVedioAdFail();
                }
            }

            //视频广告加载后，视频资源缓存到本地的回调，在此回调后，播放本地视频，流畅不阻塞。
            @Override
            public void onRewardVideoCached() {
                if (mttRewardVideoAd != null) {
                    mttRewardVideoAd.showRewardVideoAd(activity);
                    mttRewardVideoAd = null;
                } else {
                    TrackManager.getInstance().addCallImp(Constant.AD_SOURCE_CSJ, Constant.EVENT_TYPE_ONE, "999999", "Cached Fail");

                    if (csjVedioAdListener != null) {
                        csjVedioAdListener.csjVedioAdFail();
                    }
                }
            }

            //视频广告的素材加载完毕，比如视频url等，在此回调后，可以播放在线视频，网络不好可能出现加载缓冲，影响体验。
            @Override
            public void onRewardVideoAdLoad(TTRewardVideoAd ad) {
                mttRewardVideoAd = ad;
                mttRewardVideoAd.setRewardAdInteractionListener(new TTRewardVideoAd.RewardAdInteractionListener() {

                    @Override
                    public void onAdShow() {//视频广告展示回调
                        TrackManager.getInstance().addCallImp(Constant.AD_SOURCE_CSJ, Constant.EVENT_TYPE_ZERO, "", "");
                    }

                    @Override
                    public void onAdVideoBarClick() {//广告的下载bar点击回调
                        TrackManager.getInstance().addCallImp(Constant.AD_SOURCE_CSJ, Constant.EVENT_TYPE_TWO, "", "");

                        if (isClickScreen) {
                            // 防止重复
                            TrackManager.getInstance().addCallImp(Constant.AD_SOURCE_CSJ, Constant.EVENT_TYPE_FOUR, "", "");
                            isClickScreen = false;
                        }
                        if (csjVedioAdListener != null) {
                            csjVedioAdListener.csjVedioDownload();
                        }
                    }

                    @Override
                    public void onAdClose() {
                        TrackManager.getInstance().addCallImp(Constant.AD_SOURCE_CSJ, Constant.EVENT_TYPE_THREE, "", "");

                        if (csjVedioAdListener != null) {
                            csjVedioAdListener.csjVedioAdSuccess();
                        }
                    }

                    @Override
                    public void onVideoComplete() {
                    }

                    @Override
                    public void onVideoError() {
                        TrackManager.getInstance().addCallImp(Constant.AD_SOURCE_CSJ, Constant.EVENT_TYPE_ONE, "999999", "VideoError");

                        if (csjVedioAdListener != null) {
                            csjVedioAdListener.csjVedioAdFail();
                        }
                    }

                    @Override
                    public void onRewardVerify(boolean var1, int var2, String var3, int var4, String var5) {
                    }

                    @Override
                    public void onSkippedVideo() {
                    }
                });
            }
        });
    }

    /**
     * 封装广告数据，请求服务器
     *
     * @param carrierType
     * @param tid
     * @return
     */
    private HashMap<String, Object> getAdMapVO(String carrierType, String tid) {
        HashMap<String, Object> vo = new HashMap<>();
        vo.put("carrierType", carrierType);
        vo.put("adtype", Constant.ADTYPE_VEDIO);
        vo.put("tid", tid);
        vo.put("adsource", Constant.AD_SOURCE_CSJ);
        if (spUtil != null) {
            vo.put("ip", spUtil.getString(Constant.CSJ_VEDIO_APPIP));
        }

        switch (carrierType) {
            case Constant.CARRIER_VERSUS_VIDEO:// 每日任务-视频
                vo.put("coin", curCoin);
                break;
            case Constant.CARRIER_HOMEWATER:// 首页喝水汽泡
                vo.put("waterCoin", curCoin);
                break;
            case Constant.CARRIER_OFFLINE_DOUBLE:// 离线收益翻倍
                vo.put("offline_income", curCoin);
            case Constant.CARRIER_CHALLENGE_TURN:// 挑战大转盘
            case Constant.CARRIER_CHALLENGE_CARD:// 挑战刮刮乐
                vo.put("turntableKey", extraId);
                break;
        }
        return vo;
    }

    public void setCsjVedioAdListener(CsjVedioAdListener csjVedioAdListener) {
        this.csjVedioAdListener = csjVedioAdListener;
    }

    public interface CsjVedioAdListener {
        void csjVedioAdFail();

        void csjVedioAdSuccess();

        void csjVedioDownload();
    }
}
