/*********************************************************************
* 版权所有 (C)2016, DYSPACE。
* 
* 文件名称： // UnionAdManager.cs
* 内容摘要： // 该文件是 穿山甲广告
* 其它说明： // 
* 当前版本： // V0.1
* 作    者： // Will.Wang
* 创建日期： // 
* 
* 修改记录1：// 修改历史记录，包括修改日期、修改者及修改内容
*    修改日期：
*    版 本 号：
*    修 改 人：
*    修改内容： 
* 修改记录2：…
**********************************************************************/

#if ByteDanceAd
using UnityEngine;
using ByteDance.Union;
using System;

public partial class UnionAdManager : MonoBehaviour// MonoSingleton<UnionAdManager>
{
    private static UnionAdManager _instance;
    public static UnionAdManager instance
    {
        get
        {
            if(_instance == null)
                _instance = new GameObject("UnionAdManager").AddComponent<UnionAdManager>();
            return _instance;
        }
    }

    public bool isVideoReady => this.rewardAd != null && rewardAd.IsDownloaded;

    //账号id
    const string UserID = "41523";
    //BannerID
    const string BannerID = "945468876";//"945447369";
    //rectangle banner
    const string RectangleID = "945469524";//"945447369";
    //奖励视频广告
    const string RewardAdID = "945446674";
    //全屏视频广告
    const string FullAdID = "945469579";
    //插页广告
    const string InterID = "945446736";
    //期望模板广告view的size,单位dp，//高度设置为0,则高度会自适应
    const int InterWidth = 350;
    //展示方向
    const AdOrientation adOrientation = AdOrientation.Vertical;

    internal Action OnRewardVideoFinish;
    internal Action OnRewardVideoError;
    internal Action onRewardVideoClose;

    internal Action OnFullVideoFinish;
    internal Action<string> OnFullVideoError;
    internal Action onFullVideoClose;

    #region VIDEO

    private bool showRewardVideoSuc;
    /// <summary>
    /// 加载视频广告
    /// </summary>
    public void LoadRewardAd()
    {
        
        if (this.rewardAd != null)
        {
            Debug.LogError("广告已经加载");
            return;
        }
        var adSlot = new AdSlot.Builder()
            .SetCodeId(RewardAdID)
            .SetSupportDeepLink(true)
            //.SetImageAcceptedSize(1080, 1920)
            .SetRewardName("金币") // 奖励的名称
            .SetRewardAmount(3) // 奖励的数量
            .SetUserID(UserID) // 用户id,必传参数
            .SetMediaExtra("media_extra") // 附加参数，可选
            .SetOrientation(adOrientation) // 必填参数，期望视频的播放方向
            .Build();

        this.AdNative.LoadRewardVideoAd(
            adSlot, new RewardVideoAdListener(this));
        
    }
    /// <summary>
    /// 展示视频广告
    /// </summary>
    public void ShowRewardAd(Action onRewardVideoFinish,Action onRewardVideoError)
    {
        if (this.rewardAd == null)
        {
            Debug.Log("请先加载广告");
            return;
        }

        showRewardVideoSuc = false;
        if (this.rewardAd.IsDownloaded == true)
        {
            OnRewardVideoFinish = ()=>
            {
                showRewardVideoSuc = true;
                
                onRewardVideoFinish?.Invoke();
            };
            OnRewardVideoError = onRewardVideoError;
            onRewardVideoClose = () =>
            {
                if (!showRewardVideoSuc)
                {
                    onRewardVideoError?.Invoke();
                }
                else
                {
                    GameDebug.Log("已播放成功，忽略关闭事件");
                }
            };
            this.rewardAd.ShowRewardVideoAd();
            
            Debug.Log("播放广告");
        }
        else
        {
            onRewardVideoError?.Invoke();
        }
    }

    public void ResetVideoAd()
    {
#if UNITY_IOS

        this.rewardAd.Dispose();
        this.rewardAd = null;

#else
        if (this.rewardAd != null)
        {
            this.rewardAd = null;
        }
#endif
    }
    
    #endregion

    public bool showFullScreenSuc;

    #region 全屏视频广告
    /// <summary>
    /// 加载全屏视频广告
    /// </summary>
    public void LoadFullScreenVideoAd()
    {

        if (this.fullScreenVideoAd != null)
        {
            Debug.LogError("广告已经加载");
            return;
        }
        var adSlot = new AdSlot.Builder()
                             .SetCodeId(FullAdID)
                             .SetSupportDeepLink(true)
                             .SetImageAcceptedSize(1080, 1920)
                             .SetOrientation(adOrientation)
                             .Build();
        this.AdNative.LoadFullScreenVideoAd(adSlot, new FullScreenVideoAdListener(this));

    }
    /// <summary>
    /// 展示全屏视频广告
    /// </summary>
    public void ShowFullScreenVideoAd(Action onSuc,Action<string> onFail)
    {

        if (this.fullScreenVideoAd == null)
        {
            Debug.LogError("请先加载广告");
            return;
        }

        showFullScreenSuc = false;
        if (this.fullScreenVideoAd.IsDownloaded == true)
        {
            OnFullVideoFinish = () =>
            {
                showFullScreenSuc = true;
                onSuc?.Invoke();
            };
            
            OnFullVideoError = onFail;
            onFullVideoClose = () =>
            {
                if (!showFullScreenSuc)
                {
                    onFail?.Invoke("user close");
                }
            };
            
            this.fullScreenVideoAd.ShowFullScreenVideoAd();
        }
        else
        {
            onFail?.Invoke("广告尚未准备好");
        }
    }
    
    public void ResetFullVideoAd()
    {
#if UNITY_IOS
        this.fullScreenVideoAd = null;
#else
   
        this.fullScreenVideoAd = null;
        
#endif
    }
    #endregion

    #region Banner
    public void LoadExpressBannerAd()
    {

        float width = UnityEngine.Screen.width;
        float height = 50;//float.Parse(UnityEngine.Screen.width.ToString()) / 640 * 40;
        var adSlot = new AdSlot.Builder()
                             .SetCodeId(BannerID)
                             ////期望模板广告view的size,单位dp，//高度按照实际rit对应宽高传入
                             //.SetExpressViewAcceptedSize(UnityEngine.Screen.width, float.Parse(UnityEngine.Screen.width.ToString()) / 600 * 90)
                             .SetExpressViewAcceptedSize(width, height)
                             .SetSupportDeepLink(true)
                             .SetImageAcceptedSize(1080, 1920)
                             .SetAdCount(1)
                             .SetOrientation(AdOrientation.Vertical)
                             .Build();

        Debug.LogError("LoadExpressBannerAd SetExpressViewAcceptedSize:" + height);
        this.AdNative.LoadExpressBannerAd(adSlot, new ExpressAdListener(this, 1));

    }
    /// <summary>
    /// 展示banner
    /// </summary>
    public void ShowExpressBannerAd()
    {
#if UNITY_IOS
        if (this.iExpressBannerAd == null)
        {
            Debug.LogError("请先加载广告");
            this.information.text = "请先加载广告";
            return;
        }

        int x;
        int y;

        if (y == 0)
        {
            y = 100; // 防止刘海遮挡
        }

        this.iExpressBannerAd.ShowExpressAd(x, y);
#else
        if (this.mExpressBannerAd == null)
        {
            Debug.LogError("请先加载Banner广告");
            return;
        }
        //设置轮播间隔 30s--120s;不设置则不开启轮播
        this.mExpressBannerAd.SetSlideIntervalTime(30 * 1000);
        ExpressAdInteractionListener expressAdInteractionListener = new ExpressAdInteractionListener(this, 1);
        ExpressAdDislikeCallback dislikeCallback = new ExpressAdDislikeCallback(this, 1);
        this.mExpressBannerAd.SetDownloadListener(
            new AppDownloadListener(this));
        NativeAdManager.Instance().ShowExpressBannerAd(GetActivity(), mExpressBannerAd.handle, expressAdInteractionListener, dislikeCallback);
#endif
    }
    #endregion

    #region Rectangle
    public void LoadExpressRectangleAd()
    {
        float width = 300;//(int)(Screen.width * 5 / 6);
        float height = 250;//(int)(width * 5 / 6);
        
        var adSlot = new AdSlot.Builder()
                             .SetCodeId(RectangleID)
                             ////期望模板广告view的size,单位dp，//高度按照实际rit对应宽高传入
                             //.SetExpressViewAcceptedSize(UnityEngine.Screen.width, float.Parse(UnityEngine.Screen.width.ToString()) / 600 * 90)
                             .SetExpressViewAcceptedSize(width, height)
                             .SetSupportDeepLink(true)
                             .SetImageAcceptedSize(1080, 1920)
                             .SetAdCount(1)
                             .SetOrientation(AdOrientation.Vertical)
                             .Build();

        Debug.LogError($"SetExpressViewAcceptedSize:({width},{height})") ;
        this.AdNative.LoadExpressBannerAd(adSlot, new RectangleAdListener(this, 1));

    }
    /// <summary>
    /// 展示banner
    /// </summary>
    public void ShowExpressRectangleAd()
    {
#if UNITY_IOS
        if (this.iExpressRectangleAd == null)
        {
            Debug.LogError("请先加载广告");
            this.information.text = "请先加载广告";
            return;
        }

        this.iExpressRectangleAd.ShowExpressAd(x, y);
#else
        if (this.mExpressRectangleAd == null)
        {
            Debug.LogError("请先加载Rectangle广告");
            return;
        }
        //设置轮播间隔 30s--120s;不设置则不开启轮播
        //this.mExpressRectangleAd.SetSlideIntervalTime(30 * 1000);
        RectangleAdInteractionListener expressAdInteractionListener = new RectangleAdInteractionListener(this, 1);
        RectangleAdDislikeCallback dislikeCallback = new RectangleAdDislikeCallback(this, 1);
        this.mExpressRectangleAd.SetDownloadListener(
            new AppDownloadListener(this));
        NativeAdManager.Instance().ShowRectangleAd(GetActivity(), mExpressRectangleAd.handle, expressAdInteractionListener, dislikeCallback);
#endif
    }

    #endregion
    #region 插页
    /// <summary>
    /// 加载插页广告
    /// </summary>
    public void LoadExpressInterstitialAd()
    {
        var adSlot = new AdSlot.Builder()
                             .SetCodeId(InterID)
                             .SetExpressViewAcceptedSize(InterWidth, 0)
                             .SetSupportDeepLink(true)
                             .SetAdCount(1)
                             .SetImageAcceptedSize(1080, 1920)
                             .Build();
        this.AdNative.LoadExpressInterstitialAd(adSlot, new ExpressAdListener(this, 2));
    }
    /// <summary>
    /// 展示插页广告
    /// </summary>
    public void ShowExpressInterstitialAd()
    {
#if UNITY_IOS
        if (this.iExpressInterstitialAd == null)
        {
            Debug.LogError("请先加载广告");
            this.information.text = "请先加载广告";
            return;
        }
        if (y == 0)
        {
            y = 100; // 防止Demo里刘海遮挡
        }

        this.iExpressInterstitialAd.ShowExpressAd(x, y);
#else
        if (this.mExpressInterstitialAd == null)
        {
            Debug.LogError("请先加载广告");
            return;
        }
        ExpressAdInteractionListener expressAdInteractionListener = new ExpressAdInteractionListener(this, 1);
        this.mExpressInterstitialAd.SetDownloadListener(
            new AppDownloadListener(this));
        NativeAdManager.Instance().ShowExpressInterstitialAd(GetActivity(), mExpressInterstitialAd.handle, expressAdInteractionListener);
#endif
    }
    #endregion

    #region 广告清理
    
    public void CloseRectangelAd()
    {
        if (mExpressRectangleAd != null)
        {
            NativeAdManager.Instance().DestoryExpressAd(mExpressRectangleAd.handle);
            mExpressRectangleAd = null;
        }
    }

    public void CloseBanner()
    {
#if UNITY_IOS

        this.bannerAd.Dispose();
        this.bannerAd = null;
#else

        if (this.mExpressBannerAd != null)
        {
            NativeAdManager.Instance().DestoryExpressAd(mExpressBannerAd.handle);
            mExpressBannerAd = null;
        }
#endif
    }
    public void CloseInterstitial()
    {
#if UNITY_IOS

        this.intersititialAd.Dispose();
        this.intersititialAd = null;
#else
      
        if (this.mIntersititialAd != null)
        {
            mIntersititialAd.Dispose();
            this.mIntersititialAd = null;
        }
      
        if (this.mExpressInterstitialAd != null)
        {
            mExpressInterstitialAd.Dispose();
            NativeAdManager.Instance().DestoryExpressAd(mExpressInterstitialAd.handle);
            mExpressInterstitialAd = null;
        }

#endif
    
    }

    /*public void CloseFullScreenVideo()
    {
        if (fullScreenVideoAd != null)
        {
            //fullScreenVideoAd.Dispose();
            this.fullScreenVideoAd = null;
        }
    }*/
    
    public void DisposeAds()
    {
#if UNITY_IOS

        this.rewardAd.Dispose();
        this.rewardAd = null;

        this.fullScreenVideoAd.Dispose();
        this.fullScreenVideoAd = null;

        this.bannerAd.Dispose();
        this.bannerAd = null;

        this.intersititialAd.Dispose();
        this.intersititialAd = null;

        this.expressRewardAd.Dispose();
        this.expressRewardAd = null;

        this.expressFullScreenVideoAd.Dispose();
        this.expressFullScreenVideoAd = null;

        this.iExpressBannerAd.Dispose();
        this.iExpressBannerAd = null;

        this.feedAd.Dispose();
        this.feedAd = null;

        this.splashAd.Dispose();
        this.splashAd = null;

        this.expressSplashAd.Dispose();
        this.expressSplashAd = null;

#else
        if (this.rewardAd != null)
        {
            this.rewardAd = null;
        }
        if (this.fullScreenVideoAd != null)
        {
            this.fullScreenVideoAd = null;
        }
        if (this.mBannerAd != null)
        {
            this.mBannerAd = null;
        }
        if (this.mIntersititialAd != null)
        {
            this.mIntersititialAd = null;
        }
        if (this.mExpressFeedad != null)
        {
            NativeAdManager.Instance().DestoryExpressAd(mExpressFeedad.handle);
            mExpressFeedad = null;
        }
        if (this.mExpressBannerAd != null)
        {
            NativeAdManager.Instance().DestoryExpressAd(mExpressBannerAd.handle);
            mExpressBannerAd = null;
        }
       
        if (this.mExpressInterstitialAd != null)
        {
            NativeAdManager.Instance().DestoryExpressAd(mExpressInterstitialAd.handle);
            mExpressInterstitialAd = null;
        }

        if (this.splashAd != null)
        {
            this.splashAd = null;
        }
#endif
    }
    #endregion

    /// <summary>
    /// 所有广告种类都初始化
    /// </summary>
    public void AllADsInit()
    {
        LoadExpressBannerAd();
        LoadFullScreenVideoAd();
        LoadRewardAd();
        LoadExpressInterstitialAd();
    }
}
#endif