using System.Collections.Generic;
using System.Globalization;
using AppsFlyerSDK;
using IgnoreOPS;
using UnityEngine;

namespace ChillConnect
{
    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 bool CheckIsOpen(string name)
        {
            var isOpen = UIManager.Instance.IsExistUI(name);

            return isOpen;
        }

        void pay_success(object str)
        {
            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<PaidcoinsModel>().DataList[suffix_num].Payment_amount2.ToString();

                    if (!CheckIsOpen(UIConst.BuygoldUI))
                    {
                        List<Paidcoins> list = ConfigSystem.GetConfig<PaidcoinsModel>().DataList;
                        // GetPayReward(gold_num);
                        DataMgr.Coin.Value += list[suffix_num].Actual_coins;
                        SaveData.GetSaveObject().gold_shop_time[suffix_num] = (int)GameHelper.GetNowTime();
                        SaveData.saveDataFunc();
                        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 successful");
                GameHelper.IsTemporaryEnd = false;
                purch_number = ConfigSystem.GetConfig<CommonModel>().addspace2.ToString();
            }
            else if (type == PurchasingManager.GetPaySku(PayType.buy_one_off))
            {
                purch_number = GameHelper.GetCommonModel().AddDiscount2.ToString();
                if (!CheckIsOpen(UIConst.AddViewoffUI))
                {
                    UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.AddViewoffUI_Close);
                    SaveData.GetSaveObject().have_slot = true;
                    SaveData.saveDataFunc();
                    GameDispatcher.Instance.Dispatch(GameMsg.Slot_refresh);
                }
                GameHelper.IsTemporaryEnd = false;
                GameHelper.ShowTips("Purchase successful");
            }
            else if (type == PurchasingManager.GetPaySku(PayType.remove_ad))
            {
                SaveData.GetSaveObject().remove_ad_time = (int)GameHelper.GetNowTime() + ConfigSystem.GetConfig<CommonModel>().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);
                GameDispatcher.Instance.Dispatch(GameMsg.noads_refresh);
                GameDispatcher.Instance.Dispatch(GameMsg.UpdateNoads);
                GameHelper.ShowTips("Purchase successful");
                purch_number = ConfigSystem.GetConfig<PaidgiftModel>().DataList[1].Paid_price2.ToString();
            }
            else if (type == PurchasingManager.GetPaySku(PayType.pack_reward))
            {
                List<Paidgift> list = ConfigSystem.GetConfig<PaidgiftModel>().DataList;
                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.AddGoldNumber(gold_num);
                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.noads_refresh);
                GameDispatcher.Instance.Dispatch(GameMsg.Gold_refresh);
                GameDispatcher.Instance.Dispatch(GameMsg.Sheep_item_refresh);
                GameDispatcher.Instance.Dispatch(GameMsg.UpdateNoads);
                GameHelper.ShowTips("Purchase successful");
                purch_number = ConfigSystem.GetConfig<PaidgiftModel>().DataList[0].Paid_price2.ToString();
            }
            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<PassportrewardsModel>().DataList;
                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;
                }

                GameHelper.AddItemNumber(0, out_);
                GameHelper.AddItemNumber(1, back_);
                GameHelper.AddItemNumber(2, refresh_);
                GameDispatcher.Instance.Dispatch(GameMsg.Sheep_item_refresh);
                SaveData.saveDataFunc();
                purch_number = ConfigSystem.GetConfig<CommonModel>().Passportgift2.ToString();

                if (!CheckIsOpen(UIConst.PassViewUI))
                {
                    // DataMgr.Coin.Value += gold;
                    GetPayReward(gold);
                    GameDispatcher.Instance.Dispatch(GameMsg.Gold_refresh);
                }
            }
            else if (type == PurchasingManager.GetPaySku(PayType.fail_pack))
            {
                List<Paidgift> list = ConfigSystem.GetConfig<PaidgiftModel>().DataList;
                purch_number = ConfigSystem.GetConfig<PaidgiftModel>().DataList[2].Paid_price2.ToString();
                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<MultigiftModel>().DataList[0].Paid_price2.ToString();
            }
            UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PayloadingUI_Close);

            if (!GameHelper.IsAdModelOfPay() && !string.IsNullOrEmpty(purch_number) && decimal.TryParse(purch_number, out decimal revenue))
            {
                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);

                GameHelper.SendRevenueToServer(Property.Af_purchase, "af_revenue", (int)(revenue * 10000));

                RankSystemMgr.Instance.addGameExp(addPointType.buy, revenue);
            }
        }

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

            var start = new Vector2(540, 960);
            var end = new Vector2(75, 25);
            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);
        }
        public static Dictionary<string, string> adCallbackInfo = new Dictionary<string, string>();

        #endregion
    }
}
