using System;
using UnityEngine;
using UnityEngine.Events;
using BingoBrain.Core;
using System.Collections.Generic;
using AppsFlyerSDK;

namespace BingoBrain.Core
{
    public class MaxADKit
    {
        public static string SDKKey =
            "LHx_tPFslZpTTiIPABmS24T7Ev1QEVOUVOzirpkxLUuTwJTVZGCKAk9L3Tm3FwuM5LxHK3q1EIbAemJB5sNpX2";

        public static string interstitialADUnitID = "af1076054c8eb56f";


        public static string rewardedADUnitID = "d79c2aa7b6ad055d";

        private const float RevenueThreshold = 0.1f;

        public static Dictionary<string, string> adCallbackInfo;

        public static void Init()
        {
            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>();
        }

        #region 插屏广告相关
        public static UnityAction<bool> onInterstitialAdCompleted = null;
        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 += OnAdRevenuePaidEvent;


            LoadInterstitial();
        }

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

        private static void OnInterstitialLoadedEvent(string adUnitId, MaxSdkBase.AdInfo adInfo)
        {
            retryAttemptInterstitial = 0;
        }

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

            IsfvKit.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)
        {
            OnInterstitialAdRevenuePaidEvent(adUnitId, adInfo);
            LoadInterstitial();
            onInterstitialAdCompleted?.Invoke(true);
            onInterstitialAdCompleted = null;
        }

        private static void OnInterstitialAdRevenuePaidEvent(string adUnitId, MaxSdkBase.AdInfo adInfo)
        {
            string countryCode = "USD";//MaxSdk.GetSdkConfiguration().CountryCode; // "US" for the United States, etc - Note: Do not confuse this with currency code which is "USD"
                                       //  //string networkName = adInfo.NetworkName; // Display name of the network that showed the ad
                                       // // string adUnitIdentifier = adInfo.AdUnitIdentifier; // The MAX Ad Unit ID
                                       //  //string placement = adInfo.Placement; // The placement this ad's postbacks are tied to
                                       // // string networkPlacement = adInfo.NetworkPlacement; // The placement ID from the network that showed the ad
            adCallbackInfo.Clear();
            var loginModel = GameHelper.GetLoginModel();
            adCallbackInfo.Add("customer_user_id", loginModel.uid.ToString());
            adCallbackInfo.Add("af_revenue", adInfo.Revenue.ToString());
            adCallbackInfo.Add("af_currency", countryCode);
            adCallbackInfo.Add("eventValue", "");
            // AppsFlyer.sendEvent("af_pay", adCallbackInfo);

            double revenue = Convert.ToDouble(PlayerPrefs.GetString($"adInfoRevenue_{loginModel.uid}", "0")); revenue += adInfo.Revenue;

            // if (revenue >= RevenueThreshold)
            // {
            //     adCallbackInfo["af_revenue"] = revenue.ToString();
            //     AppsFlyer.sendEvent("af_revenue", adCallbackInfo);
            //     PlayerPrefs.SetString($"adInfoRevenue_{loginModel.uid}", "0");

            //     bool isToday = GameHelper.IsToday(loginModel.reg_time);
            //     if (isToday)
            //     {
            //         adCallbackInfo["af_new_revenue"] = revenue.ToString();
            //         AppsFlyer.sendEvent("af_purchase", adCallbackInfo);
            //     }
            // }
            // else
            // {
            //     PlayerPrefs.SetString($"adInfoRevenue_{loginModel.uid}", revenue.ToString());
            // }
        }

        #endregion

        #region 激励视频广告相关

        public static UnityAction<bool> onVideoAdCompleted = null;
        public static void ShowVideo(string placement = "DefaultVideo", UnityAction<bool> onCompleted = null)
        {
#if UNITY_EDITOR
            SaveData.GetSaveobject().look_ad_numbers++;
            onCompleted?.Invoke(true);

#else
            if (MaxSdk.IsRewardedAdReady(rewardedADUnitID))
            {
                MaxSdk.ShowRewardedAd(rewardedADUnitID, placement);
                onVideoAdCompleted=onCompleted;
            }
            else
            {
                onCompleted?.Invoke(false);
            }
#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 += OnAdRevenuePaidEvent;


            LoadRewardedAd();
        }

        private static void LoadRewardedAd()
        {
            MaxSdk.LoadRewardedAd(rewardedADUnitID);
        }
        public static string user_id = "";
        private static void OnAdRevenuePaidEvent(string adUnitId, MaxSdkBase.AdInfo adInfo)
        {
            //string countryCode = MaxSdk.GetSdkConfiguration().CountryCode; // "US" for the United States, etc - Note: Do not confuse this with currency code which is "USD"
            //  //string networkName = adInfo.NetworkName; // Display name of the network that showed the ad
            // // string adUnitIdentifier = adInfo.AdUnitIdentifier; // The MAX Ad Unit ID
            //  //string placement = adInfo.Placement; // The placement this ad's postbacks are tied to
            // // string networkPlacement = adInfo.NetworkPlacement; // The placement ID from the network that showed the ad
            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;

            // Debug.Log($"revenue:  {revenue}  \n adInfo.Revenue: {adInfo.Revenue}");

            if (revenue >= RevenueThreshold)
            {
                adCallbackInfo.Add("af_revenue", revenue.ToString());
                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();
                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));

            IsfvKit .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();
            SaveData.GetSaveobject().look_ad_numbers++;
            onVideoAdCompleted?.Invoke(true);
            onVideoAdCompleted = null;
            if (GameHelper.IsGiftSwitch() && !SaveData.GetSaveobject().is_get_removead && (UnityEngine.Random.Range(0, 100) < GameHelper.GetCommonModel().rewardinsertion))
            {
                NetworkKit.BuriedPoint(BuriedPointEvent.Apple_pay_event, BuriedPointEvent.afterRewardAdShow, 1);
                Debug.Log("bofanggggggggggggggreward");
                GameHelper.ShowInterstitial("AfterReward");
            }
        }

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


        }

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

        #endregion
    }
}