using System.Collections.Generic;
using System.Globalization;
using AppsFlyerSDK;
using IgnoreOPS;
using SGModule.Common.Extensions;
using SGModule.Net;
using SGModule.NetKit;
using UnityEngine;

namespace RedHotRoast
{
    public class RainPlayUICtrl : BaseUICtrl
    {
        private RainPlayUI ui;
        private RainPlayModel model;

        private uint openUIMsg = UICtrlMsg.RainPlayUI_Open;
        private uint closeUIMsg = UICtrlMsg.RainPlayUI_Close;

        #region 生命周期
        protected override void OnInit()
        {
            //model = ModuleManager.Instance.GetModel(ModelConst.RainPlayModel) as RainPlayModel;
        }

        protected override void OnDispose()
        {
        }

        public override void OpenUI(object args = null)
        {
            if (ui == null)
            {
                ui = new RainPlayUI(this);
                ui.Open(args);
            }
        }

        public override void CloseUI(object args = null)
        {
            if (ui != null && !ui.isClose)
            {
                ui.Close();
            }
            ui = null;
        }
        #endregion

        #region 消息
        public override uint GetOpenUIMsg(string uiName)
        {
            return openUIMsg;
        }
        public override uint GetCloseUIMsg(string uiName)
        {
            return closeUIMsg;
        }

        protected override void AddListener()
        {
            uiCtrlDispatcher.AddListener(openUIMsg, OpenUI);
            uiCtrlDispatcher.AddListener(closeUIMsg, CloseUI);
            GameDispatcher.Instance.AddListener(GameMsg.apple_pay_success, pay_success);

        }
        protected override void RemoveListener()
        {
            uiCtrlDispatcher.RemoveListener(openUIMsg, OpenUI);
            uiCtrlDispatcher.RemoveListener(closeUIMsg, CloseUI);
            GameDispatcher.Instance.RemoveListener(GameMsg.apple_pay_success, pay_success);

        }

        protected override void AddServerListener()
        {

        }
        protected override void RemoveServerListener()
        {

        }

        private void GetPayReward(decimal goldNum)
        {
            if (goldNum == 0) return;

            var start = new Vector2(540, 960);
            var end = new Vector2(236, 62);
            var rewardData = new RewardData();
            var rewardSingleData = new RewardSingleData(101, goldNum, RewardOrigin.AdTask)
            {
                startPosition = start,
            };
            rewardData.AddReward(rewardSingleData);
            rewardData.displayType = RewardDisplayType.RewardFly | RewardDisplayType.ValueChange;

            GameDispatcher.Instance.Dispatch(GameMsg.GetReward, rewardData);
        }

        void pay_success(object str)
        {
            bool is_maxPay = false; // 第三方支付
            string type = (string)str;
            string purch_number = "";
            if (type.Contains("buy_gold"))
            {
                if (type.StartsWith("buy_gold"))
                {
                    int startIndex = "buy_gold".Length;
                    string suffix = type[startIndex..]; // 截取 "gold" 后的所有字符
                    int suffix_num = int.Parse(suffix);

                    purch_number = ConfigSystem.GetConfig<Paidcoins>()[suffix_num].Payment_amount2.ToString();

                    if (!UIManager.Instance.IsExistUI(UIConst.BuygoldUI))
                    {
                        List<Paidcoins> list = ConfigSystem.GetConfig<Paidcoins>();
                        // GameHelper.AddGoldNumber(list[suffix_num].Actual_coins);
                        int gold_num = list[suffix_num].Actual_coins;
                        GetPayReward(gold_num);
                        SaveData.GetSaveObject()._goldtime[suffix_num] = (int)GameHelper.GetNowTime();
                        SaveData.SaveDataFunc();
                        GameDispatcher.Instance.Dispatch(GameMsg.Gold_refresh);
                    }
                }

            }
            else if (type == PurchasingManager.GetPaySku(PayType.battle_pass))
            {
                SaveData.GetSaveObject().is_get_battlepass = true;
                int gold = 0;
                int out_ = 0;
                int back_ = 0;
                int refresh_ = 0;
                List<Passportrewards> Passportrewards_list = ConfigSystem.GetConfig<Passportrewards>();
                for (int i = 0; i < Passportrewards_list.Count; i++)
                {
                    if (GameHelper.GetBattleLv() > i || (GameHelper.GetGameExp() >= Passportrewards_list[Passportrewards_list.Count - 1].Eliminating_quantity))
                    {
                        if (Passportrewards_list[i].Paid_rewards_type == 0) gold += Passportrewards_list[i].Paid_rewards_num;
                        else if (Passportrewards_list[i].Paid_rewards_type == 1) out_ += Passportrewards_list[i].Paid_rewards_num;
                        else if (Passportrewards_list[i].Paid_rewards_type == 2) back_ += Passportrewards_list[i].Paid_rewards_num;
                        else if (Passportrewards_list[i].Paid_rewards_type == 3) refresh_ += Passportrewards_list[i].Paid_rewards_num;
                        SaveData.GetSaveObject().battle_pass_paylist.Add(i + 1);
                    }
                    else break;
                }
                var purch = ConfigSystem.GetCommonConf().Passportgift2;
                purch_number = purch.ToString();
                if (UIManager.Instance.IsExistUI(UIConst.PassViewUI))
                {
                    GameHelper.AddItemNumber(0, out_);
                    GameHelper.AddItemNumber(1, back_);
                    GameHelper.AddItemNumber(2, refresh_);
                    GameDispatcher.Instance.Dispatch(GameMsg.Sheep_item_refresh);
                    // DataMgr.Coin.Value += gold;
                    GetPayReward(gold);
                    GameDispatcher.Instance.Dispatch(GameMsg.Gold_refresh);
                }
            }
            else if (type == PurchasingManager.GetPaySku(PayType.buy_one))
            {
                SaveData.GetSaveObject().have_slot = true;
                SaveData.SaveDataFunc();
                GameDispatcher.Instance.Dispatch(GameMsg.Slot_refresh);
                GameHelper.ShowTips("purchase_succ", true);

                purch_number = GameHelper.GetCommonModel().addspace2.ToString();
            }
            else if (type == PurchasingManager.GetPaySku(PayType.remove_ad))
            {
                SaveData.GetSaveObject().remove_ad_time = (int)GameHelper.GetNowTime() + GameHelper.GetCommonModel().RemoveADsPackDuration * 3600;
                SaveData.GetSaveObject().is_get_removead = true;
                SaveData.SaveDataFunc();
                // GameHelper.AddGoldNumber(ConfigSystem.GetConfig<PaidgiftModel>().DataList[1].coins_quantity);
                // GameDispatcher.Instance.Dispatch(GameMsg.Gold_refresh);
                ui?.setBtnAds();
                GameDispatcher.Instance.Dispatch(GameMsg.UpdateNoads);
                GameHelper.ShowTips("purchase_succ", true);
                purch_number = ConfigSystem.GetConfig<Paidgift>()[1].Paid_price2.ToString();
            }
            else if (type == PurchasingManager.GetPaySku(PayType.pack_reward))
            {
                List<Paidgift> list = ConfigSystem.GetConfig<Paidgift>();
                int gold_num = list[0].coins_quantity;
                int back_num = list[0].props_quantity[1];
                int out_num = list[0].props_quantity[0];
                int refresh_num = list[0].props_quantity[2];

                GameHelper.AddItemNumber(0, out_num);
                GameHelper.AddItemNumber(1, back_num);
                GameHelper.AddItemNumber(2, refresh_num);
                SaveData.GetSaveObject().is_get_packreward = true;
                SaveData.SaveDataFunc();
                GameDispatcher.Instance.Dispatch(GameMsg.Gold_refresh);
                GameDispatcher.Instance.Dispatch(GameMsg.Sheep_item_refresh);
                ui?.setBtnAds();
                GameDispatcher.Instance.Dispatch(GameMsg.UpdateNoads);
                GameHelper.ShowTips("purchase_succ", true);
                purch_number = ConfigSystem.GetConfig<Paidgift>()[0].Paid_price2.ToString();
            }
            else if (type == PurchasingManager.GetPaySku(PayType.fail_pack))
            {
                List<Paidgift> list = ConfigSystem.GetConfig<Paidgift>();
                purch_number = ConfigSystem.GetConfig<Paidgift>()[2].Paid_price2.ToString();
                //ui?.setBtnAds();
                GameDispatcher.Instance.Dispatch(GameMsg.resurgence);

                // DataMgr.Coin.Value += ConfigSystem.GetConfig<PaidgiftModel>().DataList[1].coins_quantity;
                // GameDispatcher.Instance.Dispatch(GameMsg.Gold_refresh);
                int back_num = list[2].props_quantity[1];
                int out_num = list[2].props_quantity[0];
                int refresh_num = list[2].props_quantity[2];
                //GameHelper.addGoldNumber(gold_num);
                int gold_num = list[2].coins_quantity;
                if (!UIManager.Instance.IsExistUI(UIConst.ResurgenceUI)) DataMgr.Coin.Value += gold_num;
                GameHelper.AddItemNumber(0, out_num);
                GameHelper.AddItemNumber(1, back_num);
                GameHelper.AddItemNumber(2, refresh_num);
                GameDispatcher.Instance.Dispatch(GameMsg.Sheep_item_refresh);
                SaveData.SaveDataFunc();

            }
            else if (type == PurchasingManager.GetPaySku(PayType.three_days_gift))
            {
                SaveData.GetSaveObject().is_get_ThreeDaysGift = true;
                SaveData.SaveDataFunc();
                purch_number = ConfigSystem.GetConfig<Multigift>()[0].Paid_price2.ToString();
            }
            else if (type.StartsWith("vip_club"))
            {
                is_maxPay = true;
                int startIndex = "vip_club".Length;
                string suffix = type[startIndex..]; // 截取 "gold" 后的所有字符
                int suffixNum = int.Parse(suffix);

                if (!MaxPayManager.isIOSPay)
                {
                    var days = 0;
                    switch (suffixNum)
                    {
                        case 0:
                            days = (int)VipDay.Week;
                            break;
                        case 1:
                            days = (int)VipDay.Month;
                            break;
                        case 2:
                            days = (int)VipDay.Year;
                            break;
                    }

                    if (days > 0)
                    {
                        // 设置 VIP 到期时间（当前时间戳 + VIP 天数对应的秒数）
                        if (DataMgr.VipExpirationTime.Value > ServerClock.GetCurrentServerTime())
                        {
                            DataMgr.VipExpirationTime.Value = DataMgr.VipExpirationTime.Value + days * 24 * 60 * 60;
                        }
                        else DataMgr.VipExpirationTime.Value = ServerClock.GetCurrentServerTime() + days * 24 * 60 * 60;
                    }
                    DataMgr.VipLevel.Value = suffixNum + 1;
                }
                purch_number = ConfigSystem.GetConfig<VipClub>()[suffixNum].DiscountPrice.ToString();
                GameDispatcher.Instance.Dispatch(GameMsg.BuyVip);
            }
            else if (type.StartsWith("secret_albnums"))
            {
                is_maxPay = true;
                int startIndex = "secret_albnums".Length;
                string suffix = type[startIndex..]; // 截取 "gold" 后的所有字符
                int suffix_num = int.Parse(suffix);
                var model = ConfigSystem.GetConfig<SecretAlbums>()[suffix_num];
                if (model.PayType == (int)UnlockPayType.Pay && !GameHelper.isVipUnlock)
                {
                    purch_number = ConfigSystem.GetConfig<SecretAlbums>()[suffix_num].DiscountPrice.ToString();
                }
                GameHelper.isVipUnlock = false;
            }
            UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PayloadingUI_Close);
            
            if ((!GameHelper.IsAdModelOfPay() || is_maxPay) && !string.IsNullOrEmpty(purch_number) && decimal.TryParse(purch_number, out decimal revenue))
            {
                var revenueNum = (int)(purch_number.As<decimal>() * 10000);
                var payType = MaxPayManager.isIOSPay ? 0 : 1;

                // 付费上报BI
                BIManager.Instance.TrackPurchase(purch_number.As<double>(), "USD", payType.ToString(), type, "paid");

                Debug.Log("付费收益上报AF----------- " + revenue);
                adCallbackInfo.Clear();
                adCallbackInfo.Add("appsflyer_id", AppsFlyer.getAppsFlyerId());
                adCallbackInfo.Add("customer_user_id", GameHelper.GetLoginModel().Uid.ToString());
                adCallbackInfo.Add("af_currency", "USD");
                adCallbackInfo.Add("af_revenue", revenue.ToString(CultureInfo.InvariantCulture));
                AppsFlyer.sendEvent("af_purchase", adCallbackInfo);

                TrackKit.SendEvent(AfPurchaseTrack.Event, AfPurchaseTrack.Property.af_revenue, (int)(purch_number.As<decimal>() * 10000));

            }
        }

        #endregion

        public static Dictionary<string, string> adCallbackInfo = new Dictionary<string, string>();

    }
}