using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using FutureCore;
using FairyGUI;
using FGUI.failpack;
using System;
using FGUI.A000_common;
using DG.Tweening;

namespace ScrewsMaster
{
    public class ResurgenceUI : BaseUI
    {
        private ResurgenceUICtrl ctrl;
        private ResurgenceModel model;
        private FGUI.failpack.com_resurgence ui;

        public ResurgenceUI(ResurgenceUICtrl ctrl) : base(ctrl)
        {
            uiName = UIConst.ResurgenceUI;
            this.ctrl = ctrl;
        }
        private float progress_value;

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

        #region 生命周期
        protected override void OnInit()
        {

        }

        protected override void OnClose()
        {
        }

        protected override void OnBind()
        {
            ui = baseUI as FGUI.failpack.com_resurgence;
        }

        protected override void OnOpenBefore(object args)
        {

            Debug.Log(args);
            progress_value = GameObject.Find("GameStage").GetComponent<ShowScrews>().LevelProgress * 100;

            InitView();
            NetworkKit.BuriedPoint(BuriedPointEvent.Apple_pay_event, BuriedPointEvent.fail_show, 1);
        }

        protected override void OnOpen(object args)
        {
        }

        protected override void OnHide()
        {
        }

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

        #region 消息
        protected override void AddListener()
        {
            if (GameHelper.IsAdModelOfPay())
            {
                HallManager.Instance.UpdateSecondEvent += InitView;
            }
            GameDispatcher.Instance.AddListener(GameMsg.apple_pay_success, pay_success);
            HallManager.Instance.UpdateSecondEvent += updatEevent;
            updatEevent();
        }
        protected override void RemoveListener()
        {
            if (GameHelper.IsAdModelOfPay())
            {
                HallManager.Instance.UpdateSecondEvent -= InitView;
            }
            GameDispatcher.Instance.RemoveListener(GameMsg.apple_pay_success, pay_success);
            HallManager.Instance.UpdateSecondEvent -= updatEevent;
        }
        #endregion
        private void updatEevent()
        {
            bool _inAdRewardCooldown = GameHelper.InAdRewardCooldown();
            ui.btn_buy.GetChild("title").visible = !_inAdRewardCooldown;
            ui.btn_buy.GetChild("icon").visible = !_inAdRewardCooldown;
            ui.btn_buy.GetChild("text_cooldown").visible = _inAdRewardCooldown;
            ui.btn_buy.grayed = _inAdRewardCooldown;

            ui.btn_buy.GetChild("text_cooldown").text = CommonHelper.TimeFormat((int)GameHelper.GetAdRewardCooldownTime() - Convert.ToInt32(GameHelper.GetNowTime()), CountDownType.Hour);

            if (GameHelper.IsGiftSwitch() && ConfigSystem.GetConfig<CommonModel>().PiggyBankSwitch == 1 && !ui.btn_buy.grayed) (ui.btn_buy.GetChild("img_saveingpot") as GImage).visible = true;


            //  ui.text_remain.text=CommonHelper.TimeFormat((int)(SaveData.GetSaveobject().failed_pack_time - Convert.ToInt32(GameHelper.GetNowTime())), CountDownType.Hour);

        }
        void pay_success(object str)
        {
            string type = (string)str;
            Debug.Log("77777777777777777777777777" + type);
            if (type == MaxPayManager.fail_pack)
            {
                var start = GameHelper.GetUICenterPosition(ui.bg);
                var rewardData = new RewardData();
                var end = GameHelper.GetUICenterPosition(ui.end_point);
                int back_num = list[2].props_quantity[1];
                int out_num = list[2].props_quantity[0];
                int refresh_num = list[2].props_quantity[2];
                var rewardSingleData = new RewardSingleData(101, list[2].coins_quantity, RewardOrigin.AdTask)
                {
                    startPosition = start,
                    endPosition = end
                };

                rewardData.AddReward(rewardSingleData);
                rewardData.displayType = RewardDisplayType.RewardFly | RewardDisplayType.ValueChange;
                rewardData.AddCompleted(success =>
                {
                    // if (success)
                    // {
                    //     RefreshGold(awardNum);
                    // }
                });
                //  GameHelper.AddGoldNumber(list[2].coins_quantity);
                GameDispatcher.Instance.Dispatch(GameMsg.GetReward, rewardData);
                // PreferencesMgr.Instance.Currency101 -= list[1].coins_quantity;
                GameHelper.AddItemNumber(ItemEnum.AddHole, out_num);
                GameHelper.AddItemNumber(ItemEnum.MergeBox, back_num);
                GameHelper.AddItemNumber(ItemEnum.ClearHole, refresh_num);
                GameDispatcher.Instance.Dispatch(GameMsg.Sheep_item_refresh);
                // GameObject.Find("GameStage").GetComponent<ShowScrews>().ClearHoleBtnClick();
                if (!UIManager.Instance.IsExistUI(UIConst.GameHomeUI))
                {
                    // ShowScrews.Instance._isLevelOver = false;
                    ShowScrews.Instance.OnResurrect();
                }
                DOVirtual.DelayedCall(0.1f, () =>
                {
                    CtrlCloseUI();
                });
            }

        }
        private List<Paidgift> list;
        //初始化页面逻辑
        private void InitView()
        {
            if (SaveData.GetSaveobject().failed_pack_time < GameHelper.GetNowTime())
            {
                SaveData.GetSaveobject().failed_pack_time = (int)GameHelper.GetNowTime() + GameHelper.GetCommonModel().FailedGiftCD;
            }
            ui.btn_back.SetClick(() =>
            {
                UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.ResurgenceUI_Close);
                if (!UIManager.Instance.IsExistUI(UIConst.GameHomeUI))
                {
                    ShowScrews.Instance._isLevelOver = false;
                    if (ShowScrews.Instance.GetIdleHoleCount() <= 0) ShowScrews.Instance.OnGameFailed();
                }

            });
            list = ConfigSystem.GetConfig<PaidgiftModel>().dataList;
            int gold_num = list[2].coins_quantity;
            int back_num = list[2].props_quantity[1];
            int out_num = list[2].props_quantity[0];
            int refresh_num = list[2].props_quantity[2];
            ui.text_outnum.text = "x" + out_num;
            ui.text_backnum.text = "x" + back_num;
            ui.text_refreshnum.text = "x" + refresh_num;
            ui.text_goldnum.text = "x" + gold_num;
            ui.text_progress.text = "Completion:" + Math.Round(progress_value) + "%";
            ui.progress_1.value = progress_value;
            if (!GameHelper.IsAdModelOfPay())
            {
                ui.pay_type.selectedIndex = 1;

                decimal price = (decimal)list[2].Paid_price2;
                ui.btn_max_pay.title = "$ " + price;
                if (GameHelper.IsGiftSwitch() && ConfigSystem.GetConfig<CommonModel>().PiggyBankSwitch == 1) (ui.btn_max_pay.GetChild("img_saveingpot") as GImage).visible = true;
                ui.btn_max_pay.SetClick(() =>
                {
                    ApplePayClass maxPayData = new()
                    {
                        amount = (int)Math.Round(price * 100),
                        sku = MaxPayManager.fail_pack,
                        currency = "USD"
                    };
                    MaxPayManager.Instance.Buy(maxPayData);
                });


                return;
            }





            ui.text_have.text = $"You Have ADs:{GameHelper.GetAdWatchCount()}";
            ui.need_text.text = $"Need ADs:{list[2].Paid_price}";
            ui.btn_buy.GetChild("img_saveingpot").visible = false;

            updatEevent();

            if (GameHelper.CheckAdWatchCount((int)list[2].Paid_price))
            {
                ui.btn_buyPackClaim.visible = true;
                ui.btn_buy.visible = false;
            }
            else
            {
                ui.btn_buyPackClaim.visible = false;
                ui.btn_buy.visible = true;
            }
            ui.btn_buy.SetClick(() =>
            {
                if (ui.btn_buy.grayed) return;
                OnClickBuyPackWatchAdsBtn();
            });

            ui.btn_buyPackClaim.SetClick(() =>
            {
                if (GameHelper.CheckAdWatchCount((int)list[2].Paid_price))
                {
                    GameHelper.AddAdWatchCount(-(int)list[2].Paid_price);

                    var start = GameHelper.GetUICenterPosition(ui.bg);
                    var rewardData = new RewardData();
                    var end = GameHelper.GetUICenterPosition(ui.end_point);

                    var rewardSingleData = new RewardSingleData(101, list[2].coins_quantity, RewardOrigin.AdTask)
                    {
                        startPosition = start,
                        endPosition = end
                    };

                    rewardData.AddReward(rewardSingleData);
                    rewardData.displayType = RewardDisplayType.RewardFly | RewardDisplayType.ValueChange;
                    rewardData.AddCompleted(success =>
                    {
                        // if (success)
                        // {
                        //     RefreshGold(awardNum);
                        // }
                    });
                    GameDispatcher.Instance.Dispatch(GameMsg.GetReward, rewardData);
                    // PreferencesMgr.Instance.Currency101 -= list[1].coins_quantity;
                    // GameHelper.AddGoldNumber(list[2].coins_quantity);
                    UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.ResurgenceUI_Close);
                    GameHelper.AddItemNumber(ItemEnum.AddHole, out_num);
                    GameHelper.AddItemNumber(ItemEnum.MergeBox, back_num);
                    GameHelper.AddItemNumber(ItemEnum.ClearHole, refresh_num);
                    GameDispatcher.Instance.Dispatch(GameMsg.Sheep_item_refresh);
                    // GameObject.Find("GameStage").GetComponent<ShowScrews>().ClearHoleBtnClick();
                    if (!UIManager.Instance.IsExistUI(UIConst.GameHomeUI))
                    {
                        // ShowScrews.Instance._isLevelOver = false;
                        ShowScrews.Instance.OnResurrect();
                    }
                    NetworkKit.BuriedPoint(BuriedPointEvent.Apple_pay_event, BuriedPointEvent.fail_buy_success, 1);
                }
                else
                {
                    GameHelper.ShowTips("Insufficient AdWatchCount");
                    return;
                }
                Debug.Log("goumaichenggong");


            });

        }


        private void OnClickBuyPackWatchAdsBtn()
        {
            NetworkKit.BuriedPoint(BuriedPointEvent.Apple_pay_event, BuriedPointEvent.fail_click, 1);
            GameHelper.ShowVideoAd("buy_failpack", success =>
            {
                updatEevent();
                if (success)
                {
                    GameHelper.UpdateAdRewardExchangeTime();
                }
            });
        }
    }
}