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

namespace RedHotRoast
{
    public class LuckyPackUI : BaseUI
    {
        private LuckyPackUICtrl ctrl;
        private LuckyPackModel model;
        private FGUI.LG_LuckyGift.com_lucky ui;
        private List<Paidgift> list;

        public LuckyPackUI(LuckyPackUICtrl ctrl) : base(ctrl)
        {
            uiName = UIConst.LuckyPackUI;
            this.ctrl = ctrl;
        }

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

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

        protected override void OnClose()
        {
            AdExchangeManager.Instance.Destroy();
            GameHelper.showGameUI = true;

            GameDispatcher.Instance.Dispatch(GameMsg.pack_close);
            int three_gift_got_index = SaveData.GetSaveObject().three_gift_got_index;
            // if (GameHelper.isAutoPop && (three_gift_got_index <= (int)rewardState.day3))
            // {
            //     uiCtrlDispatcher.Dispatch(UICtrlMsg.ThreeDaysGiftUI_Open);
            //     GameHelper.isAutoPop = false;
            // }
            GameHelper.CallShowTurn();
        }

        protected override void OnBind()
        {
            ui = baseUI as FGUI.LG_LuckyGift.com_lucky;
        }

        protected override void OnOpenBefore(object args)
        {

            ui.gold.GetChild("text_gold").text = GameHelper.Get101Str(GameHelper.GetGoldNumber());
            var needScroll = false;
            if (args != null) needScroll = (bool)args;
            ui.type.selectedIndex = needScroll ? 1 : 0;
            ui.gift_switch.selectedIndex = GameHelper.IsGiftSwitch() ? 1 : 0;
            Debug.Log($"needScroll============={needScroll}= {ui.type.selectedIndex}");
            TrackKit.SendEvent(GameHelper.GetEventName(), needScroll ? ADEventTrack.Property.gift_show : ADEventTrack.Property.first_pack_show);

            list = ConfigSystem.GetConfig<Paidgift>();

            if (GameHelper.IsAdModelOfPay())
            {

                AdExchangeManager.Instance.SetWatchAd(PurchasingManager.GetPaySku(PayType.pack_reward), ui.btn_buypack as btn_watchAd, SetTextString1);
                AdExchangeManager.Instance.SetWatchAd(PurchasingManager.GetPaySku(PayType.remove_ad), ui.btn_buyremovead as btn_watchAd, SetTextString1);
            }

            ui.btn_go_ad.SetClick(() =>
            {
                ui.type.selectedIndex = 1;
            });
            ui.btn_go_lucky.SetClick(() =>
            {
                ui.type.selectedIndex = 0;
            });

            InitView();
//             var fileName = GameHelper.GetBackgroundName(1);
//             Debug.Log($"fileName======{fileName}");
//             TextureHelper.SetImgLoader(ui.no_ad_pic.picture, fileName, null, "Background/");
// 
//             var fileName1 = GameHelper.GetBackgroundName(2);
//             Debug.Log($"fileName1======{fileName1}");
// 
//             TextureHelper.SetImgLoader(ui.lucky_pic.picture, fileName1, null, "Background/");

            
            
            // var fileName = GameHelper.GetBackgroundName(1);
            // var task = new List<(GLoader loader, string fileName, Action<NTexture> callback, string folder, string localFolder)>();
            // task.Add((ui.lucky_pic.picture, fileName, null, "Background/", FolderNames.BackgroundName));
            // var fileName1 = GameHelper.GetBackgroundName(2);
            // task.Add((ui.no_ad_pic.picture, fileName1, null, "Background/", FolderNames.BackgroundName));
            // TextureHelper.SetImgLoaders(task);
        }

        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 pay_success(object str)
        {
            string type = (string)str;
            Debug.Log($"pay_success type================{type}");
            if (type == PurchasingManager.GetPaySku(PayType.remove_ad))
            {
                var gold = list[1].coins_quantity;
                var start = GameHelper.GetUICenterPosition(ui.text_goldnum2);
                var end = GameHelper.GetUICenterPosition(ui.gold.GetChild("icon"));

                var rewardData = new RewardData();
                var rewardSingleData = new RewardSingleData(101, gold, RewardOrigin.AdTask)
                {
                    startPosition = start,
                    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.gold.GetChild("text_gold").text = GameHelper.Get101Str((decimal)value); });
                                    });
                });

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



                UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.AdcomingUI_Close);
                SaveData.GetSaveObject().is_get_removead = true;
                SaveData.SaveDataFunc();
                InitView();


            }
            else if (type == PurchasingManager.GetPaySku(PayType.pack_reward))
            {
                var start = GameHelper.GetUICenterPosition(ui.text_goldnum);
                var end = GameHelper.GetUICenterPosition(ui.gold.GetChild("icon"));
                var gold = list[0].coins_quantity;

                var rewardData = new RewardData();
                var rewardSingleData = new RewardSingleData(101, gold, RewardOrigin.AdTask)
                {
                    startPosition = start,
                    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.gold.GetChild("text_gold").text = GameHelper.Get101Str((decimal)value); });
                                    });
                });

                GameDispatcher.Instance.Dispatch(GameMsg.GetReward, rewardData);
                SaveData.GetSaveObject().is_get_packreward = true;

                SaveData.SaveDataFunc();

                InitView();
            }


        }
        //初始化页面逻辑
        private int gold_num = 300;
        private int back_num = 1;
        private int out_num = 1;
        private int refresh_num = 1;
        private void InitView()
        {
            gold_num = list[0].coins_quantity;
            back_num = list[0].props_quantity[1];
            out_num = list[0].props_quantity[0];
            refresh_num = list[0].props_quantity[2];

            ui.text_time.SetVar("time", ConfigSystem.GetCommonConf().RemoveADsPackDuration.ToString()).FlushVars();

            ui.btn_close.SetClick(CtrlCloseUI);
            ui.btn_luck_close.SetClick(CtrlCloseUI);
            ui.text_goldnum.text = "x" + GameHelper.Get101Str(gold_num);
            ui.text_backnum1.text = "x" + back_num;
            ui.text_outnum.text = "x" + out_num;
            ui.text_refreshnum.text = "x" + refresh_num;
            var buy_text = ui.btn_buypack.GetChild("title") as GTextField;
            buy_text.SetVar("price", list[0].Paid_price.ToString()).FlushVars();

            ui.text_goldnum2.text = "x" + GameHelper.Get101Str(list[1].coins_quantity);
            var buy_text1 = ui.btn_buyremovead.GetChild("title") as GTextField;
            buy_text1.SetVar("price", list[1].Paid_price.ToString()).FlushVars();

            if (!GameHelper.IsAdModelOfPay())
            {
                ui.pay_type.selectedIndex = 1;
                decimal price_pack = (decimal)list[0].Paid_price2;
                ui.btn_max_pack.title = GameHelper.Get102Str(price_pack);
                bool is_get = SaveData.GetSaveObject().is_get_packreward;
                Debug.Log($"is_get================{is_get}");
                if (is_get)
                {
                    ui.btn_max_pack.enabled = false;
                    ui.btn_max_pack.SetClick(() => { });
                }
                else
                {

                    ui.btn_max_pack.SetClick(() =>
                    {
                        ApplePayClass maxPayData = new ApplePayClass
                        {
                            amount = (int)Math.Round(price_pack * 100),
                            sku = PurchasingManager.GetPaySku(PayType.pack_reward),
                            currency = "USD"
                        };
                        MaxPayManager.Instance.Buy(maxPayData);
                    });
                }
                decimal price_remove = (decimal)list[1].Paid_price2;
                ui.btn_max_remove.title = GameHelper.Get102Str(price_remove);
                bool is_get1 = SaveData.GetSaveObject().is_get_removead;
                Debug.Log($"is_get1================{is_get1}");
                if (is_get1)
                {
                    HallManager.Instance.UpdateSecondEvent += RemoveAdCountDown;
                    ui.btn_max_remove.enabled = false;
                    ui.btn_max_remove.SetClick(() => { });
                    int cd = SaveData.GetSaveObject().remove_ad_time - Convert.ToInt32(GameHelper.GetNowTime());
                    if (cd > 24 * 3600)
                    {
                        ui.btn_max_remove.title = CommonHelper.TimeFormat(cd, CountDownType.Day, "D");
                    }
                    else
                    {
                        ui.btn_max_remove.title = CommonHelper.TimeFormat(cd, CountDownType.Hour);
                    }
                }
                else
                {
                    ui.btn_max_remove.SetClick(() =>
                    {
                        ApplePayClass maxPayData = new ApplePayClass
                        {
                            amount = (int)Math.Round(price_remove * 100),
                            sku = PurchasingManager.GetPaySku(PayType.remove_ad),
                            currency = "USD"
                        };
                        MaxPayManager.Instance.Buy(maxPayData);
                    });
                }
            }
            else
            {
                ui.pay_type.selectedIndex = 0;
                AdExchangeManager.Instance.Start();
                SetTextString1();

                decimal price_remove = (decimal)list[1].Paid_price2;
                bool is_get1 = SaveData.GetSaveObject().is_get_removead;

                if (is_get1)
                {
                    HallManager.Instance.UpdateSecondEvent += RemoveAdCountDown;

                    ui.btn_buyremovead.enabled = false;
                    ui.btn_buyremovead.SetClick(() => { });

                    var lastTimes = SaveData.GetSaveObject()._watch_ad_cd;
                    if (GameHelper.GetNowTime() < lastTimes)
                    {

                    }
                    int cd = SaveData.GetSaveObject().remove_ad_time - Convert.ToInt32(GameHelper.GetNowTime());
                    if (cd > 24 * 3600)
                    {
                        ui.btn_buyremovead.title = CommonHelper.TimeFormat(cd, CountDownType.Day, "D");
                    }
                    else
                    {
                        ui.btn_buyremovead.title = CommonHelper.TimeFormat(cd, CountDownType.Hour);
                    }
                }

            }

        }

        private void RemoveAdCountDown()
        {
            int cd = SaveData.GetSaveObject().remove_ad_time - Convert.ToInt32(GameHelper.GetNowTime());
            if (cd > 0)
            {
                if (cd > 24 * 3600)
                {
                    ui.btn_max_remove.title = CommonHelper.TimeFormat(cd, CountDownType.Day, "D");
                    ui.btn_buyremovead.title = CommonHelper.TimeFormat(cd, CountDownType.Day, "D");
                }
                else
                {
                    ui.btn_max_remove.title = CommonHelper.TimeFormat(cd, CountDownType.Hour);
                    ui.btn_buyremovead.title = CommonHelper.TimeFormat(cd, CountDownType.Hour);
                }
            }
            else
            {
                SaveData.GetSaveObject().is_get_removead = false;
                SaveData.GetSaveObject().remove_ad_time = 0;
                InitView();
            }
        }

        public void SetTextString1()
        {
            var remove_need = AdExchangeManager.Instance.GetCeilingNeedAds(PurchasingManager.GetPaySku(PayType.remove_ad));
            var pack_need =  AdExchangeManager.Instance.GetCeilingNeedAds(PurchasingManager.GetPaySku(PayType.pack_reward));
            var myAd = AdExchangeManager.Instance.GetLookRewardADNum();

            ui.ads.SetVar("num", myAd.ToString()).FlushVars();
            ui.tips1.SetVar("num", pack_need.ToString()).FlushVars();
            ui.tips2.SetVar("num", remove_need.ToString()).FlushVars();
        }
    }
}
