using System;
using System.Collections.Generic;
using DG.Tweening;
using FairyGUI;
using FGUI.store_17;
using IgnoreOPS;
using SGModule.Net;
using SGModule.NetKit;
using Spine.Unity;
using UnityEngine;

namespace ChillConnect
{
    public class BuygoldUI : BaseUI
    {
        private BuygoldUICtrl ctrl;
        private BuygoldModel model;
        private com_buygold ui;
        private Action closeCallback;
        private bool isAutoPop;

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

        protected override void SetUIInfo(UIInfo uiInfo)
        {
            uiInfo.packageName = "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()
        {
            AdRedeemManager.Instance.Destroy();

            GameHelper.showGameUI = true;
            HallManager.Instance.UpdateSecondEvent -= initList;
            HallManager.Instance.UpdateSecondEvent -= upWatchAdsBtn;
            // HallManager.Instance.UpdateSecondEvent -= removeAdCountDown;
            GameDispatcher.Instance.Dispatch(GameMsg.pack_close);

            //int three_gift_got_index = SaveData.GetSaveObject().three_gift_got_index;
            // if (isAutoPop && (three_gift_got_index <= (int) rewardState.day3)) {
            //     uiCtrlDispatcher.Dispatch(UICtrlMsg.ThreeDaysGiftUI_Open);
            // }
            if (Isbuysuccess)
            {
                GameHelper.ShowTurnOffReward();
            }
            else
            {
                GameHelper.ShowPaidPack();
            }

        }
        private bool Isbuysuccess = false;
        protected override void OnBind()
        {
            ui = baseUI as com_buygold;
        }

        protected override void OnOpenBefore(object args)
        {
            if (args != null)
            {
                isAutoPop = (bool)args;
            }

            // test
            // SaveData.GetSaveObject().remove_ad_time = Convert.ToInt32(GameHelper.GetNowTime()) + 5;
            // SaveData.GetSaveObject().is_get_removead = true;

            if (SaveData.GetSaveObject().gold_shop_time == null || SaveData.GetSaveObject().gold_shop_time.Count < list.Count)
            {
                SaveData.GetSaveObject().gold_shop_time = new List<int>();
                for (int i = 0; i < list.Count; i++)
                {
                    SaveData.GetSaveObject().gold_shop_time.Add(0);
                }
            }

            if (Screen.safeArea.y != 0)
            {//刘海屏
                // ui.shop_panel_parent.y += 68;
                ui.top_gold.y += 68;
            }

            var anim_paly = FXManager.Instance.SetFx<SkeletonAnimation>(ui.top_gold.GetChild("gold_anim") as GGraph, Fx_Type.fx_coin, ref closeCallback);
            anim_paly.state.SetAnimation(0, "animation", true);


            PaidgiftList = ConfigSystem.GetConfig<PaidgiftModel>().DataList;

            // NetworkKit.BuriedPoint(BuriedPointEvent.Apple_pay_event, BuriedPointEvent.gold_show, 1);
            TrackKit.SendEvent(GameHelper.getTrackEvenName(),Property.GoldShow);

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

            if (GameHelper.IsAdModelOfPay())
            {
                ui.state.selectedIndex = 0;
            }
            else
            {
                ui.state.selectedIndex = 1;
            }

            InitView();

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

        }

        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


        public void upWatchAdsBtn()
        {
            int lastTimes = SaveData.GetSaveObject()._watch_ad_cd;
            int time = Convert.ToInt32(GameHelper.GetNowTime());

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

        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("gold_anim"));

            var rewardData = new RewardData();
            var rewardSingleData = new RewardSingleData(101, gold, RewardOrigin.AdTask)
            {
                startPosition = start,
                endPosition = new Vector2(end.x - 130, end.y - 130)
            };
            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);
        }

        void pay_success(object str)
        {
            string type = (string)str;
            string purch_number = "";
            Debug.Log("pay_success------" + type);

            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;
            }

            if (purch_number != "")
            {
                GameHelper.SendRevenueToAF(purch_number);
            }
            SetTextString();
        }

        //初始化页面逻辑
        private List<Paidgift> PaidgiftList;
        private int gold_num = 300;
        private int back_num = 1;
        private int out_num = 1;
        private int refresh_num = 1;

        private void InitView()
        {
            ui.top_gold.touchable = false;
            ui.btn_close.SetClick(() => { UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.BuygoldUI_Close); });
            if (GameHelper.IsGiftSwitch() && ConfigSystem.GetConfig<CommonModel>().PiggyBankSwitch == 1)
            {
                ui.btn_watch.img_saveingpot.visible = true;
            }

            initList();

            upWatchAdsBtn();
            ui.btn_watch.SetClick(() =>
            {

                // NetworkKit.BuriedPoint(BuriedPointEvent.Apple_AD_event, BuriedPointEvent.gold_click_ad,1);
                TrackKit.SendEvent(GameHelper.getTrackEvenName(),Property.GoldClickAd);

                GameHelper.ShowVideoAd("BuyGold", issuccess =>
                {
                    if (issuccess)
                    {
                        var ad_times = Convert.ToInt32(GameHelper.GetNowTime());
                        SaveData.GetSaveObject()._watch_ad_cd = ad_times + GameHelper.GetCommonModel().exchangeCD;
                        DOVirtual.DelayedCall(0.01f, () =>
                        {
                            initList();
                            upWatchAdsBtn();
                        });

                    }
                });
            });
        }



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

        void initList()
        {
            ui.gold_list.itemRenderer = setRemaintime;
            ui.gold_list.numItems = list.Count > 6 ? 6 : list.Count;

            SetTextString();
        }


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

            // var remove_need = AdRedeemManager.Instance.GetCeilingNeedAds(PurchasingManager.GetPaySku(PayType.remove_ad));
            // var pack_need = AdRedeemManager.Instance.GetCeilingNeedAds(PurchasingManager.GetPaySku(PayType.pack_reward));
            // 
            // ui.shop_panel_parent.shopPanel.btn_pack_get.title = pack_need + " ADs";
            // ui.shop_panel_parent.shopPanel.btn_remove_get.title = remove_need + " ADs";


        }

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

            var myAds = AdRedeemManager.Instance.GetLookRewardADNum();
            int time = 0;
            time = SaveData.GetSaveObject()._goldtime[index];

            item.coin_text.text = GameHelper.Get101Str(list[index].Actual_coins);

            bool is_paid = list[index].is_paid;
            item.index.selectedIndex = is_paid ? 1 : 0;
            item.off_text.text = list[index].Discount_rate + "%";
            item.discount.visible = !GameHelper.IsAdModelOfPay() && list[index].Discount_rate > 0;
            double gold_price1 = list[index].Payment_amount;
            int needAds = (int)Math.Ceiling(gold_price1);
            if (list[index].Discount_rate != 0) item.off_text.text = list[index].Discount_rate + "%";
            if (time + list[index].receive_CD < GameHelper.GetNowTime())
            {
                if (!is_paid)
                {
                    item.btn_buy.btn_text.text = "Free";
                    item.discount.visible = false;
                    item.btn_buy.can_buy.selectedIndex = 0;
                }
                else
                {
                    if (!GameHelper.IsAdModelOfPay())
                    {
                        item.btn_buy.can_buy.selectedIndex = 0;
                        decimal price = (decimal)list[index].Payment_amount2;
                        item.btn_buy.btn_text.text =  GameHelper.getPrice(price);

                        if (GameHelper.IsGiftSwitch() && ConfigSystem.GetConfig<CommonModel>().PiggyBankSwitch == 1)
                        {
                            item.btn_buy.img_saveingpot.visible = true;
                        }
                    }
                    else
                    {


                        if (myAds >= needAds)
                        {
                            item.btn_buy.can_buy.selectedIndex = 0;
                            item.btn_buy.btn_text.text = "Redeem";
                        }
                        else
                        {
                            item.btn_buy.can_buy.selectedIndex = 1;
                            item.btn_buy.btn_text.text = myAds + "/" + needAds;
                        }

                        item.text_ads.SetVar("ads", needAds.ToString()).FlushVars();
                    }
                    item.text_ads.visible = GameHelper.IsAdModelOfPay();
                }

                item.btn_buy.SetClick(() =>
                 {
                     if (!is_paid)
                     {
                         SaveData.GetSaveObject()._goldtime[index] = (int)GameHelper.GetNowTime();

                         GetAward(list[index].Actual_coins, index);

                         InitView();
                     }
                     else
                     {
                         //  AdRedeemManager.Instance.SetLookRewardADNum(AdRedeemManager.Instance.GetLookRewardADNum() - needAds);
                         SaveData.saveDataFunc();
                         redeem_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 = CommonHelper.TimeFormat(time + list[index].receive_CD - Convert.ToInt32(GameHelper.GetNowTime()), CountDownType.Hour);
                item.btn_buy.SetClick(() =>
                {

                });
                item.text_ads.visible = GameHelper.IsAdModelOfPay();
            }


        }

        public string getShopName(int index)
        {
            string name;
            name = list[index].SKU;
            return name;
        }

        private void redeem_Gold(int index)
        {
            // string _type = "buy_gold" + index.ToString();
            string _type = getShopName(index);
            if (GameHelper.IsAdModelOfPay())
            {
                AdRedeemData test = new AdRedeemData
                {
                    ad_count = AdRedeemManager.Instance.GetCeilingNeedAds($"buy_gold{index}"),
                    type = $"buy_gold{index}",
                    shopName = $"buy_gold{index}"
                };
                AdRedeemManager.Instance.Redeem(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);
            }
        }
    }
}