using System;
using System.Collections.Generic;
using System.Globalization;
using AppsFlyerSDK;
using DG.Tweening;
using IgnoreOPS;
using SGModule.Net;
using SGModule.NetKit;
using UnityEngine;
using UnityEngine.Events;
using Random = UnityEngine.Random;
// using AppsFlyerSDK;

// using AppsFlyerSDK;


namespace ChillConnect
{
    public class MaxADKit
    {
        public static string SDKKey =
            "mmVXU9O_ESeur52h0VwzCGfbI4wB8LxeBfydReplRMm2JmN8eNMVgSuiKy2bmTJ00m4DHSKFxhaH1pnpEME5bB";

        public static string interstitialADUnitID = "bb957e86a7b5ae7c";


        public static string rewardedADUnitID = "100870cb72cf50ca";
        public static string AppOpenAdUnitId = "b8a4fccf2f151b0d";

        private const float RevenueThreshold = 0.1f;

        public static Dictionary<string, string> adCallbackInfo;

        public static void Init()
        {
            // MaxSdkCallbacks.OnSdkInitializedEvent += sdkConfiguration =>
            // {


            //     if (PlayerPrefs.GetInt("OpenAD", 1) == 1) InitOpenAds();
            //     else GameDispatcher.Instance.Dispatch(GameMsg.CloseMask);

            //     DOVirtual.DelayedCall(7, () =>
            //     {
            //         InitializeRewardedAds();
            //         InitializeInterstitialAds();
            //     });

            // };
            MaxSdkCallbacks.OnSdkInitializedEvent += sdkConfiguration =>
            {
                InitializeRewardedAds();
                InitializeInterstitialAds();
            };

            MaxSdk.SetSdkKey(SDKKey);

            // var loginModel = GameHelper.GetLoginModel();
            // user_id = loginModel.uid.ToString();
            // MaxSdk.SetUserId(loginModel.uid.ToString());
            // MaxSdk.SetIsAgeRestrictedUser(false);
            MaxSdk.SetHasUserConsent(true);
            MaxSdk.SetDoNotSell(false);

            MaxSdk.InitializeSdk();

            // MaxSdk.ShowMediationDebugger();

            adCallbackInfo = new Dictionary<string, string>();
        }

        public static void SetUserID(string userID)
        {
            user_id = userID;
            MaxSdk.SetUserId(user_id);
        }

        #region 插屏广告相关
        public static UnityAction<bool> onInterstitialAdCompleted;
        public static void ShowInterstitial(string placement = "DefaultInterstitial",
            UnityAction<bool> onCompleted = null)
        {
            if (MaxSdk.IsInterstitialReady(interstitialADUnitID))
            {
                // Debug.Log($"广告已经准备好，播放");
                MaxSdk.ShowInterstitial(interstitialADUnitID, placement);
                onInterstitialAdCompleted = onCompleted;

            }
            else
            {
                // Debug.Log($"广告未准备好，不播放");

                onCompleted?.Invoke(false);
            }
        }

        static int retryAttemptInterstitial;

        public static void InitializeInterstitialAds()
        {

            MaxSdkCallbacks.Interstitial.OnAdLoadedEvent += OnInterstitialLoadedEvent;
            MaxSdkCallbacks.Interstitial.OnAdLoadFailedEvent += OnInterstitialLoadFailedEvent;
            MaxSdkCallbacks.Interstitial.OnAdDisplayedEvent += OnInterstitialDisplayedEvent;
            MaxSdkCallbacks.Interstitial.OnAdClickedEvent += OnInterstitialClickedEvent;
            MaxSdkCallbacks.Interstitial.OnAdHiddenEvent += OnInterstitialHiddenEvent;
            MaxSdkCallbacks.Interstitial.OnAdDisplayFailedEvent += OnInterstitialAdFailedToDisplayEvent;
            MaxSdkCallbacks.Interstitial.OnAdRevenuePaidEvent += OnRewardedAdRevenueEvent;


            LoadInterstitial();
        }

        private static void LoadInterstitial()
        {
            MaxSdk.LoadInterstitial(interstitialADUnitID);
        }

        private static void OnInterstitialLoadedEvent(string adUnitId, MaxSdkBase.AdInfo adInfo)
        {
            retryAttemptInterstitial = 0;
            TrackKit.SendEvent(Property.video_Event, Property.InterstitialVideosFillNumber);
        }

        private static void OnInterstitialLoadFailedEvent(string adUnitId, MaxSdkBase.ErrorInfo errorInfo)
        {
            retryAttemptInterstitial++;
            double retryDelay = Math.Pow(2, Math.Min(6, retryAttemptInterstitial));

            CrazyAsyKit.StartAction("LoadInterstitial", LoadInterstitial, (float)retryDelay);
        }

        private static void OnInterstitialDisplayedEvent(string adUnitId, MaxSdkBase.AdInfo adInfo)
        {
        }

        private static void OnInterstitialAdFailedToDisplayEvent(string adUnitId, MaxSdkBase.ErrorInfo errorInfo,
            MaxSdkBase.AdInfo adInfo)
        {
            LoadInterstitial();
        }

        private static void OnInterstitialClickedEvent(string adUnitId, MaxSdkBase.AdInfo adInfo)
        {
        }

        private static void OnInterstitialHiddenEvent(string adUnitId, MaxSdkBase.AdInfo adInfo)
        {
            LoadInterstitial();
            onInterstitialAdCompleted?.Invoke(true);
            onInterstitialAdCompleted = null;
        }

        #endregion
        //开屏相关
        public static UnityAction<bool> onAppOpenAdCompleted;
        private static void LoadAppOpenAd()
        {
            Debug.Log("LOAD APP. AD");
            MaxSdk.LoadAppOpenAd(AppOpenAdUnitId);
        }


        public static void ShowOpenAdIfReady(UnityAction<bool> onCompleted = null)
        {
            // #if UNITY_EDITOR
            //             onCompleted?.Invoke(true);
            // #else
            onAppOpenAdCompleted = onCompleted;
            if (!IsLoaded)
            {
                MaxSdkCallbacks.AppOpen.OnAdLoadedEvent += ShowOpenAd;


            }
            else
            {
                // bool isFinished = NetworkManager.isWatchedAD;
                // onCompleted?.Invoke(isFinished);
                ShowOpenAd(null, null);
            }
            // #endif
        }
        public static void ShowOpenAd(string adUnitId, MaxSdkBase.AdInfo adInfo)
        {
            MaxSdk.ShowAppOpenAd(AppOpenAdUnitId);
        }


        public static void InitOpenAds()
        {

            MaxSdkCallbacks.AppOpen.OnAdLoadedEvent += OnAppOpenLoadedEvent;
            MaxSdkCallbacks.AppOpen.OnAdLoadFailedEvent += OnOpendAdLoadFailedEvent;
            // MaxSdkCallbacks.AppOpen.OnAdDisplayedEvent += OnInterstitialDisplayedEvent;
            MaxSdkCallbacks.AppOpen.OnAdClickedEvent += OnOpenClickedEvent;
            MaxSdkCallbacks.AppOpen.OnAdHiddenEvent += OnOpenAdHiddenEvent;
            // MaxSdkCallbacks.AppOpen.OnAdDisplayFailedEvent += OnInterstitialAdFailedToDisplayEvent;
            MaxSdkCallbacks.AppOpen.OnAdRevenuePaidEvent += OnOpenAdRevenueEvent;
            LoadAppOpenAd();
        }
        private static void OnOpenClickedEvent(string adUnitId, MaxSdkBase.AdInfo adInfo)
        {
            TrackKit.SendEvent(Property.adEvent, Property.open_show);
            TrackKit.SendEvent(Property.adEvent, Property.open_show_people);
        }
        private static bool IsLoaded = false;
        private static void OnAppOpenLoadedEvent(string adUnitId, MaxSdkBase.AdInfo adInfo)
        {
            IsLoaded = true;
        }
        private static void OnOpendAdLoadFailedEvent(string adUnitId, MaxSdkBase.ErrorInfo errorInfo)
        {
            // retryAttempt++;
            // double retryDelay = Math.Pow(2, Math.Min(6, retryAttempt));

            // CrazyAsyKit.StartAction("LoadRewardedAd", LoadRewardedAd, (float)retryDelay);
            GameDispatcher.Instance.Dispatch(GameMsg.CloseMask);
            InitializeRewardedAds();
            InitializeInterstitialAds();
        }
        private static void OnOpenAdHiddenEvent(string adUnitId, MaxSdkBase.AdInfo adInfo)
        {
            // LoadAppOpenAd();
            onAppOpenAdCompleted?.Invoke(true);
            onAppOpenAdCompleted = null;
            // if (GameHelper.IsGiftSwitch() && !SaveData.GetSaveObject().is_get_removead && (Random.Range(0, 100) < GameHelper.GetCommonModel().rewardinsertion))
            // {
            //     TrackKit.SendEvent(Property.AfterRewardAdShow);

            //     GameHelper.ShowInterstitial("AfterReward");
            // }
        }


        #region 激励视频广告相关

        public static UnityAction<bool> onVideoAdCompleted;
        public static void ShowVideo(string placement = "DefaultVideo", UnityAction<bool> onCompleted = null)
        {
#if UNITY_EDITOR
            onCompleted?.Invoke(true);
#else
            TrackKit.SendEvent(Property.adEvent,Property.watch_ad_people);
            // NetworkKit.BuriedPoint(BuriedPointEvent.video_behavior,BuriedPointEvent.watch_ad_people,1);
            // NetworkKit.BuriedPoint(BuriedPointEvent.video_type,BuriedPointEvent.Rewarded_videos_trigger_number,1);
            TrackKit.SendEvent(Property.adEvent,Property.Rewarded_videos_trigger_number);

            if (MaxSdk.IsRewardedAdReady(rewardedADUnitID))
            {
                MaxSdk.ShowRewardedAd(rewardedADUnitID, placement);
                onVideoAdCompleted=onCompleted;
            }
            else
            {
                bool isFinished = NetworkManager.isWatchedAD;
                onCompleted?.Invoke(isFinished);
            }
#endif
        }

        static int retryAttempt;

        public static void InitializeRewardedAds()
        {
            MaxSdkCallbacks.Rewarded.OnAdLoadedEvent += OnRewardedAdLoadedEvent;
            MaxSdkCallbacks.Rewarded.OnAdLoadFailedEvent += OnRewardedAdLoadFailedEvent;
            MaxSdkCallbacks.Rewarded.OnAdDisplayedEvent += OnRewardedAdDisplayedEvent;
            MaxSdkCallbacks.Rewarded.OnAdClickedEvent += OnRewardedAdClickedEvent;
            MaxSdkCallbacks.Rewarded.OnAdRevenuePaidEvent += OnRewardedAdRevenuePaidEvent;
            MaxSdkCallbacks.Rewarded.OnAdHiddenEvent += OnRewardedAdHiddenEvent;
            MaxSdkCallbacks.Rewarded.OnAdDisplayFailedEvent += OnRewardedAdFailedToDisplayEvent;
            MaxSdkCallbacks.Rewarded.OnAdReceivedRewardEvent += OnRewardedAdReceivedRewardEvent;
            MaxSdkCallbacks.Rewarded.OnAdRevenuePaidEvent += OnInterstitialAdRevenueEvent;


            LoadRewardedAd();
        }
        private static void OnInterstitialAdRevenueEvent(string adUnitId, MaxSdkBase.AdInfo adInfo)
        {
            OnAdRevenuePaidEvent(adUnitId, adInfo, 2);
        }

        private static void OnRewardedAdRevenueEvent(string adUnitId, MaxSdkBase.AdInfo adInfo)
        {
            OnAdRevenuePaidEvent(adUnitId, adInfo, 1);
#if !GAME_RELEASE
            GameHelper.AdOverRevenueEvent(2, 0.1f);
#endif
        }
        private static void OnOpenAdRevenueEvent(string adUnitId, MaxSdkBase.AdInfo adInfo)
        {
            OnAdRevenuePaidEvent(adUnitId, adInfo, 3);
#if !GAME_RELEASE
            GameHelper.AdOverRevenueEvent(3, 0.1f);
#endif
        }
        private static void LoadRewardedAd()
        {
            MaxSdk.LoadRewardedAd(rewardedADUnitID);
        }
        public static string user_id = "";
        private static void OnAdRevenuePaidEvent(string adUnitId, MaxSdkBase.AdInfo adInfo, int adType)
        {

            string countryCode = "USD";

            adCallbackInfo.Clear();
            adCallbackInfo.Add("appsflyer_id", AppsFlyer.getAppsFlyerId());
            adCallbackInfo.Add("customer_user_id", user_id);
            adCallbackInfo.Add("af_currency", countryCode);

            //广告收益上传（扣量）（（用户累计收益大于0.1上报50%，50%可配置））
            double revenue = Convert.ToDouble(PlayerPrefs.GetString($"adInfoRevenue_{user_id}", "0"));
            revenue += adInfo.Revenue;
            if (adInfo.Revenue > 0)
            {
                GameHelper.AdOverRevenueEvent(adType, (float)adInfo.Revenue);
            }
            // Debug.Log($"revenue:  {revenue}  \n adInfo.Revenue: {adInfo.Revenue}");

            // if (revenue >= RevenueThreshold)
            // {
            adCallbackInfo.Add("af_revenue", revenue.ToString(CultureInfo.InvariantCulture));
            AppsFlyer.sendEvent("af_ad_revenue", adCallbackInfo);
            PlayerPrefs.SetString($"adInfoRevenue_{user_id}", "0");

            int adrate = ConfigSystem.GetConfig<CommonModel>().adrate / 100;
            double revenueAdrate = revenue * adrate;
            adCallbackInfo["af_revenue"] = revenueAdrate.ToString(CultureInfo.InvariantCulture);
            AppsFlyer.sendEvent("Af_new_ad_revenue", adCallbackInfo);
            // }
            // else
            // {
            //     PlayerPrefs.SetString($"adInfoRevenue_{user_id}", revenue.ToString());
            // }

            int highSend;
            if (!PlayerPrefs.HasKey($"sendHighRevenue_{user_id}"))
            {
                highSend = 0; // 如果不存在，则初始化为 0
            }
            else
            {
                highSend = PlayerPrefs.GetInt($"sendHighRevenue_{user_id}", 0); // 从 PlayerPrefs 中获取
            }
            // 判断是否需要发送高收入事件
            // Debug.Log($"highSend=====: {highSend}");
            if (highSend == 0)
            {
                float limitNum = GameHelper.GetCommonModel().afSendLimit;
                var totalNum = Convert.ToDouble(PlayerPrefs.GetString($"adRevenueTotal_{user_id}", "0"));
                totalNum += adInfo.Revenue;
                // Debug.Log($"totalNum=====: {totalNum}  {limitNum}");
                if (totalNum >= limitNum)
                {
                    GameHelper.sendHighRevenueToAF(); // 发送高收入事件
                    PlayerPrefs.SetInt($"sendHighRevenue_{user_id}", 1); // 标记已发送
                }
                else
                {
                    PlayerPrefs.SetString($"adRevenueTotal_{user_id}", totalNum.ToString());
                }
            }
        }
        private static void OnRewardedAdLoadedEvent(string adUnitId, MaxSdkBase.AdInfo adInfo)
        {
            retryAttempt = 0;
        }

        private static void OnRewardedAdLoadFailedEvent(string adUnitId, MaxSdkBase.ErrorInfo errorInfo)
        {
            retryAttempt++;
            double retryDelay = Math.Pow(2, Math.Min(6, retryAttempt));

            CrazyAsyKit.StartAction("LoadRewardedAd", LoadRewardedAd, (float)retryDelay);
        }

        private static void OnRewardedAdDisplayedEvent(string adUnitId, MaxSdkBase.AdInfo adInfo)
        {
        }

        private static void OnRewardedAdFailedToDisplayEvent(string adUnitId, MaxSdkBase.ErrorInfo errorInfo,
            MaxSdkBase.AdInfo adInfo)
        {
            LoadRewardedAd();
        }

        private static void OnRewardedAdClickedEvent(string adUnitId, MaxSdkBase.AdInfo adInfo)
        {
        }

        private static void OnRewardedAdHiddenEvent(string adUnitId, MaxSdkBase.AdInfo adInfo)
        {
            LoadRewardedAd();
            onVideoAdCompleted?.Invoke(true);
            onVideoAdCompleted = null;
            if (GameHelper.IsGiftSwitch() && !SaveData.GetSaveObject().is_get_removead && (Random.Range(0, 100) < GameHelper.GetCommonModel().rewardinsertion))
            {
                TrackKit.SendEvent(Property.adEvent, Property.AfterRewardAdShow);

                GameHelper.ShowInterstitial("AfterReward");
            }
        }

        private static void OnRewardedAdReceivedRewardEvent(string adUnitId, MaxSdkBase.Reward reward,
            MaxSdkBase.AdInfo adInfo)
        {

#if !GAME_RELEASE
            GameHelper.AdOverRevenueEvent(1, 0.1f);
#endif
        }

        private static void OnRewardedAdRevenuePaidEvent(string adUnitId, MaxSdkBase.AdInfo adInfo)
        {
        }

        #endregion
    }
}