using System.Collections.Generic;
using UnityEngine;
using FairyGUI;
using FGUI.ZM_store_17;
using System;
using DG.Tweening;
using FGUI.ZM_Common_01;
using SGModule.NetKit;
using Spine.Unity;

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

        private List<Paidgift> _paidGiftList;


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

        protected override void SetUIInfo(UIInfo uiInfo)
        {
            uiInfo.packageName = "ZM_store_17";
            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;
            HallManager.Instance.UpdateSecondEvent -= upWatchAdsBtn;
            GameDispatcher.Instance.Dispatch(GameMsg.pack_close);
            // if (Isbuysuccess)
            // {
            //     GameHelper.ShowTurnOffReward();
            // }
            // else
            // {
            //     GameHelper.ShowPaidPack();
            // }
        }
        private bool Isbuysuccess = false;
        protected override void OnBind()
        {
            ui = baseUI as FGUI.ZM_store_17.com_buygold;
        }


        protected override void OnOpenBefore(object args)
        {
            if (Screen.safeArea.y != 0)
            {
                //刘海屏
                ui.top_gold.y += Screen.safeArea.y - 15;
            }

            var eventName = GameHelper.IsAdModelOfPay() ? ADEventTrack.Event : ADEventTrack.MaxPayEvent;
            TrackKit.SendEvent(eventName, ADEventTrack.Property.shop_show);

            _paidGiftList = ConfigSystem.GetConfig<Paidgift>();

            ui.top_gold.GetChild("text_gold").text = GameHelper.Get101Str(GameHelper.GetGoldNumber());
            ui.pay_type.selectedIndex = !GameHelper.IsAdModelOfPay() ? 1 : 0;

            InitView();

            HallManager.Instance.UpdateSecondEvent += initList;
            HallManager.Instance.UpdateSecondEvent += upWatchAdsBtn;


            var head = ui.com_head as btn_head;
            var headId = DataMgr.PlayerAvatarId.Value;
            GameHelper.SetSelfAvatar(head.head.load_avatar, headId);
        }
        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);
        }

        protected override void RemoveListener()
        {
            GameDispatcher.Instance.RemoveListener(GameMsg.apple_pay_success, pay_success);
        }

        #endregion

        void GetAward(decimal gold, int index)
        {
            var item = ui.gold_list.GetChildAt(index);
            var start = GameHelper.GetUICenterPosition(item);
            var end = GameHelper.GetUICenterPosition(ui.top_gold.GetChild("text_gold"));

            var rewardData = new RewardData();
            var rewardSingleData = new RewardSingleData(101, gold, RewardOrigin.AdTask)
            {
                startPosition = start,
                endPosition = new Vector2(end.x, end.y)
            };
            rewardData.AddReward(rewardSingleData);
            rewardData.displayType = RewardDisplayType.RewardFly | RewardDisplayType.ValueChange;
            rewardData.AddCompleted((isScu) =>
            {
                DOVirtual.DelayedCall(0.5f, () =>
                {
                    var startNum = DataMgr.Coin.Value - gold;
                    DOVirtual.Float((float)startNum, (float)GameHelper.GetGoldNumber(), 1f,
                        value => { ui.top_gold.GetChild("text_gold").text = GameHelper.Get101Str((decimal)value); });
                });
            });

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

        void pay_success(object str)
        {
            string type = (string)str;
            string purch_number = "";

            if (type.StartsWith("buy_gold"))
            {
                int startIndex = "buy_gold".Length;
                string suffix = type[startIndex..]; // 截取 "gold" 后的所有字符
                int suffix_num = int.Parse(suffix);

                SaveData.GetSaveObject()._goldtime[suffix_num] = (int)GameHelper.GetNowTime();
                SaveData.SaveDataFunc();
                GetAward(list[suffix_num].Actual_coins, suffix_num);
                purch_number = list[suffix_num].Payment_amount.ToString();
                Isbuysuccess = true;
            }
            // else if (type == AdExchangeManager.pack_reward)
            // {
            //     var end = GameHelper.GetUICenterPosition(ui.top_gold.GetChild("icon"));
            //     var gold = (decimal)_paidGiftList[0].coins_quantity;

            //     var rewardData = new RewardData();
            //     var rewardSingleData = new RewardSingleData(101, gold, RewardOrigin.AdTask)
            //     {
            //         endPosition = end,
            //     };
            //     rewardData.AddReward(rewardSingleData);
            //     rewardData.displayType = RewardDisplayType.RewardFly | RewardDisplayType.ValueChange;
            //     rewardData.AddCompleted((isScu) =>
            //     {
            //         DOVirtual.DelayedCall(0.5f, () =>
            //         {
            //             var startNum = DataMgr.Coin.Value - gold;
            //             DOVirtual.Float((float)startNum, (float)GameHelper.GetGoldNumber(), 1f,
            //                 value => { ui.top_gold.GetChild("text_gold").text = GameHelper.Get101Str((decimal)value); });
            //         });
            //     });

            //     GameDispatcher.Instance.Dispatch(GameMsg.GetReward, rewardData);
            //     SaveData.GetSaveObject().is_get_packreward = true;
            //     Isbuysuccess = true;
            // }
            // else if (type == AdExchangeManager.remove_ad)
            // {
            //     var end = GameHelper.GetUICenterPosition(ui.top_gold.GetChild("icon"));
            //     var gold = (decimal)_paidGiftList[1].coins_quantity;

            //     var rewardData = new RewardData();
            //     var rewardSingleData = new RewardSingleData(101, gold, RewardOrigin.AdTask)
            //     {
            //         endPosition = new Vector2(end.x, end.y)
            //     };
            //     rewardData.AddReward(rewardSingleData);
            //     rewardData.displayType = RewardDisplayType.RewardFly | RewardDisplayType.ValueChange;
            //     rewardData.AddCompleted(isScu =>
            //     {
            //         DOVirtual.DelayedCall(0.5f, () =>
            //         {
            //             var startNum = DataMgr.Coin.Value - gold;
            //             DOVirtual.Float((float)startNum, GameHelper.GetGoldNumber(), 1f,
            //                 value => { ui.top_gold.GetChild("text_gold").text = GameHelper.Get101Str((decimal)value); });
            //         });
            //     });

            //     GameDispatcher.Instance.Dispatch(GameMsg.GetReward, rewardData);
            //     SaveData.GetSaveObject().is_get_removead = true;
            //     Isbuysuccess = true;
            // }


            InitView();
        }

        //初始化页面逻辑
        private void InitView()
        {
            ui.top_gold.touchable = false;
            ui.btn_close.SetClick(() => { UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.BuygoldUI_Close); });

            initList();
            upWatchAdsBtn();


            ui.btn_watch.SetClick(() =>
            {
                var eventName = GameHelper.IsAdModelOfPay() ? ADEventTrack.Event : ADEventTrack.MaxPayEvent;
                TrackKit.SendEvent(eventName, ADEventTrack.Property.gold_click_ad);

                GameHelper.ShowVideoAd("BuyGold", (issuccess) =>
                {
                    if (issuccess)
                    {
                        var ad_times = Convert.ToInt32(GameHelper.GetNowTime());
                        SaveData.GetSaveObject()._watch_ad_cd = ad_times + GameHelper.GetCommonModel().exchangeCD;

                        SaveData.SaveDataFunc();
                        initList();
                    }
                });
            });
        }

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

        void initList()
        {
            ui.gold_list.itemRenderer = setRemaintime;
            ui.gold_list.numItems = list.Count;

            SetTextString();
        }



        public void upWatchAdsBtn()
        {
            var lastTimes = SaveData.GetSaveObject()._watch_ad_cd;

            if (GameHelper.GetNowTime() < lastTimes)
            {
                ui.btn_watch.enabled = false;
                ui.btn_watch.can_buy.selectedIndex = 1;
                ui.btn_watch.btn_text.text =
                    CommonHelper.TimeFormat(lastTimes - Convert.ToInt32(GameHelper.GetNowTime()), CountDownType.Hour);
            }
            else
            {
                ui.btn_watch.enabled = true;
                ui.btn_watch.can_buy.selectedIndex = 0;
            }
        }

        public void SetTextString()
        {
            var myAds = AdExchangeManager.Instance.GetLookRewardADNum();
            ui.text_my_ads.SetVar("ads", myAds.ToString()).FlushVars();
        }

        private SkeletonAnimation pack_anims = null;
        private SkeletonAnimation no_ad_anims = null;
        private Action closeCallback = null;


        // private void UpdatePack(int index, GObject obj)
        // {
        //     item_gift item_gift = (item_gift)obj;
        //
        //     var gold_num = _paidGiftList[0].coins_quantity;
        //     var back_num = _paidGiftList[0].props_quantity[1];
        //     var out_num = _paidGiftList[0].props_quantity[0];
        //     var refresh_num = _paidGiftList[0].props_quantity[2];
        //
        //     item_gift.text_goldnum.text = "x" + GameHelper.Get101Str(gold_num);
        //     item_gift.text_backnum1.text = "x" + back_num;
        //     item_gift.text_outnum.text = "x" + out_num;
        //     item_gift.text_refreshnum.text = "x" + refresh_num;
        //
        //     item_gift.text_goldnum2.text = "x" + GameHelper.Get101Str(_paidGiftList[1].coins_quantity);
        //
        //     switch (index)
        //     {
        //         case 0:
        //             item_gift.anim_gold.visible = true;
        //             item_gift.anim_no_ad.visible = false;
        //             item_gift.type.selectedIndex = 0;
        //             pack_anims ??= FXManager.Instance.SetFx<SkeletonAnimation>(item_gift.anim_gold, Fx_Type.fx_pack_gold, ref closeCallback);
        //             pack_anims.state.SetAnimation(0, "animation2", true);
        //             break;
        //         case 1:
        //             item_gift.anim_gold.visible = false;
        //             item_gift.anim_no_ad.visible = true;
        //             no_ad_anims ??= FXManager.Instance.SetFx<SkeletonAnimation>(item_gift.anim_no_ad, Fx_Type.fx_no_ad, ref closeCallback);
        //             item_gift.type.selectedIndex = 1;
        //             no_ad_anims.state.SetAnimation(0, "wait", true);
        //             break;
        //     }
        //
        //     btn_remove_get = item_gift.btn_remove_get;
        //
        //     if (GameHelper.IsGiftSwitch()) {
        //         item_gift.lab_time.visible = true;
        //         item_gift.lab_time.SetVar("num", ConfigSystem.GetConfig<CommonModel>().RemoveADsPackDuration.ToString()).FlushVars();
        //     }
        //     else {
        //         item_gift.lab_time.visible = false;
        //     }
        //
        //
        //     if (!GameHelper.IsAdModelOfPay())
        //     {
        //         decimal price_pack = (decimal)_paidGiftList[0].Paid_price2;
        //         item_gift.btn_pack_get.title = GameHelper.Get102Str(price_pack);
        //         bool is_get = SaveData.GetSaveObject().is_get_packreward;
        //         if (is_get)
        //         {
        //             item_gift.btn_pack_get.enabled = false;
        //         }
        //         else
        //         {
        //             item_gift.btn_pack_get.SetClick(() =>
        //             {
        //                 ApplePayClass maxPayData = new ApplePayClass
        //                 {
        //                     amount = (int)Math.Round(price_pack * 100),
        //                     sku = MaxPayManager.pack_reward,
        //                     currency = "USD"
        //                 };
        //                 MaxPayManager.Instance.Buy(maxPayData);
        //             });
        //         }
        //
        //         decimal price_remove = (decimal)_paidGiftList[1].Paid_price2;
        //         bool is_get1 = SaveData.GetSaveObject().is_get_removead;
        //
        //         if (is_get1)
        //         {
        //             btn_remove_get.enabled = false;
        //
        //             btn_remove_get.SetClick(() => { });
        //             HallManager.Instance.UpdateSecondEvent += RemoveAdCountDown;
        //
        //             int cd = SaveData.GetSaveObject().remove_ad_time - Convert.ToInt32(GameHelper.GetNowTime());
        //             if (cd > 24 * 3600) {
        //                 btn_remove_get.title = CommonHelper.TimeFormat(cd, CountDownType.Day, "D");
        //             }
        //             else {
        //                 btn_remove_get.title = CommonHelper.TimeFormat(cd, CountDownType.Hour);
        //             }
        //         }
        //         else
        //         {
        //             btn_remove_get.title = GameHelper.Get102Str(price_remove);
        //             btn_remove_get.enabled = true;
        //             btn_remove_get.SetClick(() =>
        //             {
        //                 ApplePayClass maxPayData = new ApplePayClass
        //                 {
        //                     amount = (int)Math.Round(price_remove * 100),
        //                     sku = MaxPayManager.remove_ad,
        //                     currency = "USD"
        //                 };
        //                 MaxPayManager.Instance.Buy(maxPayData);
        //             });
        //         }
        //     }
        //     else
        //     {
        //         int myAds = AdExchangeManager.Instance.GetLookRewardADNum();
        //         int pack_reward_ad_count = AdExchangeManager.Instance.GetCeilingNeedAds(AdExchangeManager.pack_reward);
        //         var remove_need = AdExchangeManager.Instance.GetCeilingNeedAds(AdExchangeManager.remove_ad);
        //         item_gift.btn_pack_get.title = pack_reward_ad_count + "ADs";
        //         btn_remove_get.title = remove_need + "ADs";
        //
        //         bool is_get = SaveData.GetSaveObject().is_get_packreward;
        //         if (is_get)
        //         {
        //             item_gift.btn_pack_get.enabled = false;
        //         }
        //         else
        //         {
        //             if (myAds >= pack_reward_ad_count)
        //             {
        //                 item_gift.btn_pack_get.state.selectedIndex = 0;
        //                 item_gift.btn_pack_get.title = "Redeem";
        //             }
        //             else
        //             {
        //                 item_gift.btn_pack_get.state.selectedIndex = 1;
        //                 item_gift.btn_pack_get.title = pack_reward_ad_count + " ADs";
        //             }
        //
        //             item_gift.btn_pack_get.SetClick(() =>
        //             {
        //                 AdExchangeData test = new AdExchangeData
        //                 {
        //                     ad_count = pack_reward_ad_count,
        //                     type = AdExchangeManager.pack_reward
        //                 };
        //                 AdExchangeManager.Instance.Exchange(test);
        //             });
        //         }
        //
        //         is_get = SaveData.GetSaveObject().is_get_removead;
        //         if (is_get)
        //         {
        //
        //
        //             HallManager.Instance.UpdateSecondEvent += RemoveAdCountDown;
        //             btn_remove_get.enabled = false;
        //             btn_remove_get.SetClick(() => { });
        //             int cd = SaveData.GetSaveObject().remove_ad_time - Convert.ToInt32(GameHelper.GetNowTime());
        //             if (cd > 24 * 3600) {
        //                 btn_remove_get.title = CommonHelper.TimeFormat(cd, CountDownType.Day, "D");
        //             }
        //             else {
        //                 btn_remove_get.title = CommonHelper.TimeFormat(cd, CountDownType.Hour);
        //             }
        //
        //         }
        //         else
        //         {
        //             btn_remove_get.enabled = true;
        //
        //             if (myAds >= remove_need)
        //             {
        //                 btn_remove_get.state.selectedIndex = 0;
        //                 btn_remove_get.title = "Redeem";
        //
        //             }
        //             else
        //             {
        //                 btn_remove_get.state.selectedIndex = 1;
        //                 btn_remove_get.title = remove_need + " ADs";
        //             }
        //
        //             btn_remove_get.SetClick(() =>
        //             {
        //                 AdExchangeData test = new AdExchangeData
        //                 {
        //                     ad_count = AdExchangeManager.Instance.GetCeilingNeedAds(AdExchangeManager.remove_ad),
        //                     type = AdExchangeManager.remove_ad
        //                 };
        //                 AdExchangeManager.Instance.Exchange(test);
        //             });
        //         }
        //     }
        // }

        void setRemaintime(int index, GObject obj)
        {
            buygold_item item = (buygold_item)obj;

            int time = 0;
            time = SaveData.GetSaveObject()._goldtime[index];

            item.coin_text.text = GameHelper.Get101Str(list[index].Actual_coins);
            item.index.selectedIndex = index > 6 ? 6 : index;
            bool is_paid = list[index].is_paid;
            item.btn_buy.index.selectedIndex = 0;

            // item.off_text.text = list[index].Discount_rate + "%";
            // item.discount.visible = !GameHelper.IsAdModelOfPay() && list[index].Discount_rate > 0;
            //
            // if (list[index].Discount_rate != 0) item.off_text.text = list[index].Discount_rate + "%";
            
            if (AdExchangeManager.Instance.GetLookRewardADNum() >= list[index].Payment_amount)
            {
                if (!GameHelper.IsAdModelOfPay())
                {
                    //支付
                    decimal price = (decimal)list[index].Payment_amount2;
                    item.btn_buy.btn_text.text = GameHelper.getPrice(price);

                    item.text_ads.visible = false;
                }
                else
                {
                    //广告
                    double gold_price1 = list[index].Payment_amount;
                    int needAds = (int)Math.Ceiling(gold_price1);
                    // item.text_ads.SetVar("num", needAds.ToString()).FlushVars();
                    item.btn_buy.btn_text.text = needAds + " AD";
                }
                item.btn_buy.index.selectedIndex = 1;
                
                item.btn_buy.can_buy.selectedIndex = 0;
                item.btn_buy.SetClick(() =>
                {
                    if (!is_paid)
                    {
                        SaveData.GetSaveObject()._goldtime[index] = (int)GameHelper.GetNowTime();
                        SaveData.SaveDataFunc();
                        GetAward(list[index].Actual_coins, index);

                        InitView();
                    }
                    else
                    {
                        rm_Gold(index);
                    }
                });
            }
            else
            {
                item.btn_buy.can_buy.selectedIndex = 1;
                if (!GameHelper.IsAdModelOfPay())
                {
                }
                else
                {
                    double gold_price1 = list[index].Payment_amount;
                    int needAds = (int)Math.Ceiling(gold_price1);
                    item.btn_buy.btn_text.text = needAds + " AD";
                }
                
                item.btn_buy.SetClick(() => { });
            }
            
            if (!is_paid)
            {
                if(time + list[index].receive_CD < GameHelper.GetNowTime())
                {
                    item.btn_buy.btn_text.text = Language.GetContent("free");
                }
                else
                {
                    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);
                }
            }

        }

        private void rm_Gold(int index)
        {
            // string _type = "buy_gold" + index.ToString();
            // if (GameHelper.IsAdModelOfPay())
            // {
            //     AdExchangeData test = new AdExchangeData()
            //     {
            //         ad_count = AdExchangeManager.Instance.GetCeilingNeedAds(_type),
            //         type = _type,
            //     };
            //     AdExchangeManager.Instance.Exchange(test);
            // }
            // else
            // {
            //     decimal price = (decimal)list[index].Payment_amount2;
            //     ApplePayClass maxPayData = new ApplePayClass()
            //     {
            //         amount = (int)Math.Round(price * 100),
            //         sku = _type,
            //         currency = "USD"
            //     };
            //     Debug.Log($"amount============={maxPayData.amount}");
            //     MaxPayManager.Instance.Buy(maxPayData);
            // }
            string _type = getShopName(index);
            if (GameHelper.IsAdModelOfPay())
            {
                AdExchangeData test = new AdExchangeData()
                {
                    ad_count = AdExchangeManager.Instance.GetCeilingNeedAds(_type),
                    type = $"buy_gold{index}",
                    shopName = $"buy_gold{index}"
                };
                AdExchangeManager.Instance.Exchange(test);
            }
            else
            {
                decimal price = (decimal)list[index].Payment_amount2;
                ApplePayClass maxPayData = new ApplePayClass()
                {
                    amount = (int)Math.Round(price * 100),
                    sku = _type,
                    currency = "USD",
                    shopName = $"buy_gold{index}"
                };
                MaxPayManager.Instance.Buy(maxPayData);
            }
        }
        public string getShopName(int index)
        {
            string name;
            name = list[index].SKU;
            return name;
        }
    }
}
