using System.Collections.Generic;
using UnityEngine;
using FGUI.G012_openReward;
using System;
using DG.Tweening;
using FairyGUI;

namespace ScrewsMaster
{
    public class BuygoldUI : BaseUI
    {
        private BuygoldUICtrl ctrl;
        private BuygoldModel model;
        private FGUI.G012_openReward.com_buygold ui;



        public BuygoldUI(BuygoldUICtrl ctrl) : base(ctrl)
        {
            uiName = UIConst.BuygoldUI;
            this.ctrl = ctrl;
        }

        protected override void SetUIInfo(UIInfo uiInfo)
        {
            uiInfo.packageName = "G012_openReward";
            uiInfo.assetName = "com_buygold";
            uiInfo.layerType = UILayerType.Popup;
            uiInfo.isNeedOpenAnim = false;
            uiInfo.isNeedCloseAnim = false;
            uiInfo.isNeedUIMask = true;
        }

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

        protected override void OnClose()
        {
            GameHelper.showGameUI = true;
            HallManager.Instance.UpdateSecondEvent -= InitList;
        }

        protected override void OnBind()
        {
            ui = baseUI as FGUI.G012_openReward.com_buygold;
        }

        protected override void OnOpenBefore(object args)
        {
            NetworkKit.BuriedPoint(BuriedPointEvent.Apple_pay_event, BuriedPointEvent.gold_show, 1);
            ui.pay_type.selectedIndex = GameHelper.IsAdModelOfPay() ? 0 : 1;
            InitView();
        }

        protected override void OnOpen(object args)
        {
        }

        protected override void OnHide()
        {
        }

        protected override void OnDisplay(object args)
        {
        }
        #endregion

        #region 消息
        protected override void AddListener()
        {
            GameDispatcher.Instance.AddListener(GameMsg.apple_pay_success, pay_success);
            GameDispatcher.Instance.AddListener(GameMsg.AdRewardClaimed, OnAdRewardClaimed);
            GameDispatcher.Instance.AddListener(GameMsg.AdWatchCountUpdated, OnAdWatchCountUpdated);
        }
        protected override void RemoveListener()
        {
            GameDispatcher.Instance.RemoveListener(GameMsg.apple_pay_success, pay_success);
            GameDispatcher.Instance.RemoveListener(GameMsg.AdRewardClaimed, OnAdRewardClaimed);
            GameDispatcher.Instance.RemoveListener(GameMsg.AdWatchCountUpdated, OnAdWatchCountUpdated);
        }

        private void OnAdRewardClaimed(object args)
        {
            InitList();
        }
        private void OnAdWatchCountUpdated(object args)
        {
            InitList();
        }
        #endregion
        void pay_success(object str)
        {
            string type = (string)str;
            if (type.StartsWith("buy_gold"))
            {
                int startIndex = "buy_gold".Length;
                string suffix = type[startIndex..]; // 截取 "gold" 后的所有字符
                int suffix_num = int.Parse(suffix);


                switch (suffix_num)
                {
                    case 0:
                        SaveData.GetSaveobject()._goldtime0 = (int)GameHelper.GetNowTime();
                        break;
                    case 1:
                        SaveData.GetSaveobject()._goldtime1 = (int)GameHelper.GetNowTime();
                        break;
                    case 2:
                        SaveData.GetSaveobject()._goldtime2 = (int)GameHelper.GetNowTime();
                        break;
                    case 3:
                        SaveData.GetSaveobject()._goldtime3 = (int)GameHelper.GetNowTime();
                        break;
                    case 4:
                        SaveData.GetSaveobject()._goldtime4 = (int)GameHelper.GetNowTime();
                        break;
                    case 5:
                        SaveData.GetSaveobject()._goldtime5 = (int)GameHelper.GetNowTime();
                        break;
                    case 6:
                        SaveData.GetSaveobject()._goldtime6 = (int)GameHelper.GetNowTime();
                        break;
                    default:
                        return;
                }

                SaveData.saveDataFunc();

                var start = GameHelper.GetUICenterPosition((ui.list_item.GetChildAt(suffix_num) as buygold_item).coin_text);
                var end = GameHelper.GetUICenterPosition(ui.top_gold.GetChild("number_text"));

                reward_data temp = new reward_data() { start = start, end = end, change = list[suffix_num].Actual_coins, type = 101 };
                UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.CoinWnd_newUI_Open, temp);
                GameHelper.AddGoldNumber(list[suffix_num].Actual_coins);
                GameDispatcher.Instance.Dispatch(GameMsg.Gold_refresh);
                DOVirtual.DelayedCall(1, () =>
                {
                    DOVirtual.Float(0, (float)GameHelper.GetGoldNumber(), 1f,
                value => { ui.top_gold.GetChild("number_text").text = ((int)value).ToString(); });
                });
                InitList();
            }


        }

        //初始化页面逻辑
        private void InitView()
        {
            if (Screen.safeArea.y != 0)
            {//刘海屏
                ui.top_gold.y += Screen.safeArea.y;
            }

            ui.top_gold.GetChild("number_text").text = GameHelper.GetGoldNumber().ToString();
            ui.btn_close.SetClick(() => { UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.BuygoldUI_Close); });
            // item_list.Add(ui.item4);
            InitList();
            //
            //Debug.Log(ConfigSystem.GetConfig<PaidcoinsModel>().dataList);
            HallManager.Instance.UpdateSecondEvent += InitList;
        }
        void InitList()
        {
            ui.text_hasADsCount.text = $"Owner ADs:{GameHelper.GetAdWatchCount()}";
            ui.list_item.itemRenderer = setRemaintime;
            ui.list_item.numItems = list.Count;

            // for (int i = 0; i < item_list.Count; i++)
            // {
            //     item_list[i].index.selectedIndex = i;
            //     setRemaintime(i, item_list[i]);
            // }

        }
        private List<Paidcoins> list = ConfigSystem.GetConfig<PaidcoinsModel>().dataList;

        // void setPayClick(int index, buygold_item item)
        // {
        //     var start = GameHelper.GetUICenterPosition(item.gold_bg);
        //     var end = GameHelper.GetUICenterPosition(ui.top_gold.GetChild("number_text"));


        //     reward_data temp = new reward_data() { start = start, end = end, change = 3, type = 101 };
        //     UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.CoinWnd_newUI_Open, temp);
        //     GameHelper.addGoldNumber(3);
        //     GameDispatcher.Instance.Dispatch(GameMsg.Gold_refresh);
        //     DOVirtual.DelayedCall(1, () =>
        //     {
        //         DOVirtual.Float(0, (float)GameHelper.getGoldNumber(), 1f,
        //     value => { ui.top_gold.GetChild("number_text").text = ((int)value).ToString(); });
        //     });


        // }



        void setRemaintime(int index, GObject obj)
        {
            int time = 0;
            if (index == 0) time = SaveData.GetSaveobject()._goldtime0;
            else if (index == 1) time = SaveData.GetSaveobject()._goldtime1;
            else if (index == 2) time = SaveData.GetSaveobject()._goldtime2;
            else if (index == 3) time = SaveData.GetSaveobject()._goldtime3;
            else if (index == 4) time = SaveData.GetSaveobject()._goldtime4;
            else if (index == 5) time = SaveData.GetSaveobject()._goldtime5;
            else if (index == 6) time = SaveData.GetSaveobject()._goldtime6;
            buygold_item item = obj as buygold_item;
            if (index <= 4) item.index.selectedIndex = index;
            else item.index.selectedIndex = 4;
            item.btn_buy.img_saveingpot.visible = false;
            var needWatchAds = false;
            item.coin_text.text = "x" + list[index].Actual_coins.ToString();
            item.pay_type.selectedIndex = GameHelper.IsAdModelOfPay() ? 0 : 1;
            if (list[index].Discount_rate != 0)
            {
                item.off_text.text = list[index].Discount_rate + "%";
                item.show_off.selectedIndex = 1;
            }
            else item.show_off.selectedIndex = 0;


            decimal price = 0;
            price = Mathf.RoundToInt(list[index].Payment_amount);
            if (time + list[index].receive_CD < GameHelper.GetNowTime())    //没在冷却
            {

                if (!GameHelper.IsAdModelOfPay())
                {
                    price = (decimal)list[index].Payment_amount2;
                    item.btn_buy.btn_text.text = "$ "+price;

                    if (index == 0)
                    {
                        item.btn_buy.btn_text.text = "Free";
                        item.btn_buy.SetClick(() =>
                      {
                          PaySuccess(0);
                      });
                    }
                    else
                    {
                        if (GameHelper.IsGiftSwitch() && ConfigSystem.GetConfig<CommonModel>().PiggyBankSwitch == 1)
                        {
                            item.btn_buy.img_saveingpot.visible = true;
                        }
                        item.btn_buy.SetClick(() =>
                        {
                            ApplePayClass maxPayData = new ApplePayClass()
                            {
                                amount = (int)Math.Round(price * 100),
                                sku = getShopName(index),
                                currency = "USD",
                                shopName = $"buy_gold{index}"
                            };
                            MaxPayManager.Instance.Buy(maxPayData);
                        });
                        item.btn_buy.y = 330;
                    }
                }
                else
                {

                    if (index == 0)
                    {
                        item.btn_buy.btn_text.text = "Free";
                    }
                    // else item.btn_buy.btn_text.text = GameHelper.GetPaymentTypeVO().payicon + list[index].Payment_amount;
                    else
                    {

                        item.btn_buy.touchable = true;
                        item.btn_buy.grayed = false;
                        if (GameHelper.IsGiftSwitch() && ConfigSystem.GetConfig<CommonModel>().PiggyBankSwitch == 1)
                        {
                            item.btn_buy.img_saveingpot.visible = true;
                        }
                        if (GameHelper.CheckAdWatchCount((int)price))
                        {
                            item.btn_buy.btn_text.text = "Claim";
                            item.btn_buy.img_saveingpot.visible = false;
                        }
                        else if (GameHelper.InAdRewardCooldown())
                        {
                            item.btn_buy.btn_text.text = CommonHelper.TimeFormat((int)GameHelper.GetAdRewardCooldownTime() - Convert.ToInt32(GameHelper.GetNowTime()), CountDownType.Hour);
                            item.btn_buy.touchable = false;
                            item.btn_buy.grayed = true;
                            item.btn_buy.img_saveingpot.visible = false;
                        }
                        else
                        {
                            needWatchAds = true;
                            item.btn_buy.btn_text.text = $"Watch Ad";
                        }
                    }

                    item.btn_buy.SetClick(() =>
                     {
                         if (index == 0)
                         {
                             NetworkKit.BuriedPoint(BuriedPointEvent.Apple_pay_event, BuriedPointEvent.gold_click + "_" + (index ), 1);

                             PaySuccess(0);

                         }
                         else
                         {
                             if (needWatchAds)
                             {
                                 NetworkKit.BuriedPoint(BuriedPointEvent.Apple_pay_event, BuriedPointEvent.gold_click + "_" + (index ), 1);
                                 GameHelper.ShowVideoAd($"buy_gold{index}", success =>
                                 {
                                     if (success)
                                     {
                                         GameHelper.UpdateAdRewardExchangeTime();
                                     }
                                 });
                                 return;
                             }
                             if (GameHelper.CheckAdWatchCount((int)price))
                             {
                                 GameHelper.AddAdWatchCount(-(int)price);

                                 PaySuccess(index);
                             }
                             else
                             {
                                 GameHelper.ShowTips("Insufficient AdWatchCount");
                             }

                         }
                     });
                }


                item.btn_buy.can_buy.selectedIndex = 0;

            }
            else
            {
                if (index != 0 && !GameHelper.IsAdModelOfPay())
                {
                    item.btn_buy.y = 340;
                }

                item.btn_buy.img_saveingpot.visible = false;
                item.btn_buy.can_buy.selectedIndex = 1;
                item.btn_buy.btn_text.text = CommonHelper.TimeFormat(time + list[index].receive_CD - Convert.ToInt32(GameHelper.GetNowTime()), CountDownType.Hour);
                item.btn_buy.SetClick(() =>
                {

                });
            }
            item.text_priceDescription.text = index == 0 ? $"Daily Rewards" : $"Need {price} ADs";

        }
        public string getShopName(int index)
        {
            string name;
            switch(index)
            {
                case 1:
                    name = PurchasingManager.buy_gold_1;
                    break;
                case 2:
                    name = PurchasingManager.buy_gold_2;
                    break;
                case 3:
                    name = PurchasingManager.buy_gold_3;
                    break;
                case 4:
                    name = PurchasingManager.buy_gold_4;
                    break;
                case 5:
                    name = PurchasingManager.buy_gold_5;
                    break;
                default:
                    return "";

            }
            return name;
        }
        void PaySuccess(int index)
        {


            switch (index)
            {
                case 0:
                    SaveData.GetSaveobject()._goldtime0 = (int)GameHelper.GetNowTime();
                    break;
                case 1:
                    SaveData.GetSaveobject()._goldtime1 = (int)GameHelper.GetNowTime();
                    break;
                case 2:
                    SaveData.GetSaveobject()._goldtime2 = (int)GameHelper.GetNowTime();
                    break;
                case 3:
                    SaveData.GetSaveobject()._goldtime3 = (int)GameHelper.GetNowTime();
                    break;
                case 4:
                    SaveData.GetSaveobject()._goldtime4 = (int)GameHelper.GetNowTime();
                    break;
                case 5:
                    SaveData.GetSaveobject()._goldtime5 = (int)GameHelper.GetNowTime();
                    break;
                case 6:
                    SaveData.GetSaveobject()._goldtime6 = (int)GameHelper.GetNowTime();
                    break;
                default:
                    return;
            }
            NetworkKit.BuriedPoint(BuriedPointEvent.Apple_pay_event, BuriedPointEvent.GoldSuccess + "_" + (index ), 1);
            SaveData.saveDataFunc();

            var start = GameHelper.GetUICenterPosition((ui.list_item.GetChildAt(index) as buygold_item).coin_text);
            var end = GameHelper.GetUICenterPosition(ui.top_gold.GetChild("number_text"));

            reward_data temp = new reward_data() { start = start, end = end, change = list[index].Actual_coins, type = 101 };
            UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.CoinWnd_newUI_Open, temp);
            GameHelper.AddGoldNumber(list[index].Actual_coins);
            GameDispatcher.Instance.Dispatch(GameMsg.Gold_refresh);
            DOVirtual.DelayedCall(1, () =>
            {
                DOVirtual.Float(0, (float)GameHelper.GetGoldNumber(), 1f,
            value => { ui.top_gold.GetChild("number_text").text = ((int)value).ToString(); });
            });
            InitList();
        }
    }
}