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

namespace ScrewsMaster
{
    public class PackRewardUI : BaseUI
    {
        private PackRewardUICtrl ctrl;
        private PackRewardModel model;
        private FGUI.G008_reward.com_packreward ui;

        private int _packPrice;
        private int _removeADPrice;
        private GTextField _packCooldownText;
        private GTextField _removeADCooldownText;
        private pack_panel _panel;
        private bool _inAdRewardCooldown;

        public PackRewardUI(PackRewardUICtrl ctrl) : base(ctrl)
        {
            uiName = UIConst.PackrewardUI;
            this.ctrl = ctrl;
        }

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

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

        protected override void OnClose()
        {

            HallManager.Instance.UpdateSecondEvent -= UpdateButtonState;
            GameHelper.showGameUI = true;
            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);
            }
        }

        protected override void OnBind()
        {
            ui = baseUI as FGUI.G008_reward.com_packreward;
        }

        private bool isAutoPop = false;
        protected override void OnOpenBefore(object args)
        {

            ui.panel_parent.panel.height += GRoot.inst.height * 0.25f;

            bool need_scroll = false;
            PackRewardData Datas = args as PackRewardData;
            if (args != null)
            {
                Datas = args as PackRewardData;
                need_scroll = Datas.isNeedScroll;
                isAutoPop = Datas.isAutoPop;
            }
            if (need_scroll) ui.panel_parent.scrollPane.ScrollDown(300, false);

            NetworkKit.BuriedPoint(BuriedPointEvent.Apple_pay_event, BuriedPointEvent.remove_ad_show, 1);

            NetworkKit.BuriedPoint(BuriedPointEvent.Apple_pay_event, BuriedPointEvent.pack_show, 1);

            ui.gold.GetChild("number_text").text = GameHelper.GetGoldNumber().ToString();
            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, OnUpdateAdReward);
            GameDispatcher.Instance.AddListener(GameMsg.AdWatchCountUpdated, OnUpdateAdReward);
        }
        protected override void RemoveListener()
        {
            GameDispatcher.Instance.RemoveListener(GameMsg.apple_pay_success, pay_success);
            GameDispatcher.Instance.RemoveListener(GameMsg.AdRewardClaimed, OnUpdateAdReward);
            GameDispatcher.Instance.RemoveListener(GameMsg.AdWatchCountUpdated, OnUpdateAdReward);
        }

        private void OnUpdateAdReward(object data)
        {
            UpdateAdsText();
            UpdateButtonState();
        }
        #endregion
        void pay_success(object str)
        {
            string type = (string)str;
            if (type == MaxPayManager.pack_reward)
            {
                GameHelper.AddGoldNumber(gold_num);
                GameHelper.AddItemNumber(ItemEnum.AddHole, out_num);
                GameHelper.AddItemNumber(ItemEnum.MergeBox, back_num);
                GameHelper.AddItemNumber(ItemEnum.ClearHole, refresh_num);

                var start = GameHelper.GetUICenterPosition(ui.panel_parent.panel.text_goldnum);
                var end = GameHelper.GetUICenterPosition(ui.gold.GetChild("number_text"));


                reward_data temp = new reward_data() { start = start, end = end, change = list[0].coins_quantity, type = 101 };
                UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.CoinWnd_newUI_Open, temp);


                DOVirtual.DelayedCall(1, () =>
                {
                    DOVirtual.Float(0, GameHelper.GetGoldNumber(), 1,
                        value => { ui.gold.GetChild("number_text").text = ((int)value).ToString(); });
                });

                SaveData.GetSaveobject().is_get_packreward = true;

                SaveData.saveDataFunc();
                GameDispatcher.Instance.Dispatch(GameMsg.Gold_refresh);
                GameDispatcher.Instance.Dispatch(GameMsg.Sheep_item_refresh);
                GameDispatcher.Instance.Dispatch(GameMsg.BuyPack);
                InitView();
            }
            if (type == MaxPayManager.remove_ad)
            {
                GameHelper.AddGoldNumber(_removeAdAddGoldNum);
                var start = GameHelper.GetUICenterPosition(ui.panel_parent.panel.text_goldnum2);
                var end = GameHelper.GetUICenterPosition(ui.gold.GetChild("number_text"));

                reward_data temp = new reward_data() { start = start, end = end, change = _removeAdAddGoldNum, type = 101 };
                UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.CoinWnd_newUI_Open, temp);

                DOVirtual.DelayedCall(1, () =>
                {
                    DOVirtual.Float(0, GameHelper.GetGoldNumber(), 1,
                        value => { ui.gold.GetChild("number_text").text = ((int)value).ToString(); });
                });

                UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.AdcomingUI_Close);

                SaveData.GetSaveobject().is_get_removead = true;
                SaveData.saveDataFunc();

                GameDispatcher.Instance.Dispatch(GameMsg.Gold_refresh);
                GameDispatcher.Instance.Dispatch(GameMsg.Sheep_item_refresh);
                GameDispatcher.Instance.Dispatch(GameMsg.BuyRemoveAdPack);
                InitView();


            }
        }
        //初始化页面逻辑
        private int gold_num = 300;
        private int _removeAdAddGoldNum;
        private int back_num = 1;
        private int out_num = 1;
        private int refresh_num = 1;
        private List<Paidgift> list;
        private void InitView()
        {
            if (Screen.safeArea.y != 0)
            {//刘海屏
                ui.gold.y += Screen.safeArea.y;
            }

            _panel = ui.panel_parent.panel;
            _panel.pay_type.selectedIndex = GameHelper.IsAdModelOfPay() ? 0 : 1;
            list = ConfigSystem.GetConfig<PaidgiftModel>().dataList;

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



            _packPrice = (int)list[0].Paid_price;
            _removeADPrice = (int)list[1].Paid_price;

            _panel.btn_close0.SetClick(CtrlCloseUI);
            _panel.btn_close1.SetClick(CtrlCloseUI);
            _panel.text_goldnum.text = "x" + gold_num;
            _panel.text_backnum1.text = "x" + back_num;
            _panel.text_outnum.text = "x" + out_num;
            _panel.text_refreshnum.text = "x" + refresh_num;

            _removeAdAddGoldNum = list[1].coins_quantity;
            ui.panel_parent.panel.text_goldnum2.text = "x" + list[1].coins_quantity;

            _panel.btn_buyPackClaim.SetClick(OnClickBuyPack);
            _panel.btn_buypack.SetClick(OnClickBuyPackWatchAdsBtn);
            _panel.btn_RemoveAdClaim.SetClick(OnClickBuyRemoveAd);
            _panel.btn_buyremovead.SetClick(OnClickBuyRemoveAdWatchAdsBtn);

            UpdateAdsText();
            HallManager.Instance.UpdateSecondEvent += UpdateButtonState;
            UpdateButtonState();
        }

        private void UpdateAdsText()
        {
            ui.panel_parent.panel.text_hasAdCount.text = $"You Have ADs:{GameHelper.GetAdWatchCount()}";
            ui.panel_parent.panel.text_needAdCount1.text = $"Need ADs:{_packPrice}";
            ui.panel_parent.panel.text_needAdCount2.text = $"Need ADs:{_removeADPrice}";
        }

        private void UpdateButtonState()
        {
            _inAdRewardCooldown = GameHelper.InAdRewardCooldown();

            UpdateBtnBuyPackState();
            UpdateBtnBuyRemoveAdState();
        }

        private void UpdateBtnBuyPackState()
        {

            if (SaveData.GetSaveobject().is_get_packreward)
            {
                _panel.btn_buyPackClaim.grayed = true;
                _panel.btn_buyPackClaim.visible = true;
                _panel.btn_buypack.visible = false;
                _panel.btn_max_pack.visible = false;
                return;
            }

            if (!GameHelper.IsAdModelOfPay())
            {
                _panel.btn_buyPackClaim.visible = false;
                decimal price_pack = (decimal)list[0].Paid_price2;
                ui.panel_parent.panel.btn_max_pack.title = "$ "+price_pack;
                bool is_get = SaveData.GetSaveobject().is_get_packreward;
                if (is_get)
                {
                    ui.panel_parent.panel.btn_max_pack.enabled = false;
                    ui.panel_parent.panel.btn_max_pack.SetClick(() => { });
                }
                else
                {
                    ui.panel_parent.panel.btn_max_pack.SetClick(() =>
                    {
                        ApplePayClass maxPayData = new ApplePayClass
                        {
                            amount = (int)Math.Round(price_pack * 100),
                            sku = MaxPayManager.pack_reward,
                            currency = "USD"
                        };
                        MaxPayManager.Instance.Buy(maxPayData);
                    });
                }
                if (GameHelper.IsGiftSwitch() && ConfigSystem.GetConfig<CommonModel>().PiggyBankSwitch == 1) (_panel.btn_max_pack.GetChild("img_saveingpot") as GImage).visible = true;
            }
            else
            {
                _panel.btn_buyPackClaim.visible = GameHelper.CheckAdWatchCount(_packPrice);
                _panel.btn_buypack.visible = !_panel.btn_buyPackClaim.visible;

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

                if (_packCooldownText == null && _panel.btn_buypack.GetChild("text_cooldown") is GTextField packCooldownText)
                {
                    _packCooldownText = packCooldownText;
                }

                if (_packCooldownText != null)
                {
                    _packCooldownText.visible = _inAdRewardCooldown;

                    if (_inAdRewardCooldown)
                    {
                        _packCooldownText.text = CommonHelper.TimeFormat(
                            (int)GameHelper.GetAdRewardCooldownTime() - Convert.ToInt32(GameHelper.GetNowTime()),
                            CountDownType.Hour);
                    }
                }

                _panel.btn_buypack.GetChild("title").visible = !_inAdRewardCooldown;
                _panel.btn_buypack.GetChild("icon").visible = !_inAdRewardCooldown;
            }

        }
        private void UpdateBtnBuyRemoveAdState()
        {
            if (SaveData.GetSaveobject().is_get_removead)
            {
                _panel.btn_RemoveAdClaim.grayed = true;
                _panel.btn_RemoveAdClaim.visible = true;
                _panel.btn_buyremovead.visible = false;
                _panel.btn_max_remove.visible = false;
                return;
            }
            if (!GameHelper.IsAdModelOfPay())
            {
                _panel.btn_RemoveAdClaim.visible = false;
                decimal price_remove = (decimal)list[1].Paid_price2;
                ui.panel_parent.panel.btn_max_remove.title = "$ "+price_remove;
                bool is_get1 = SaveData.GetSaveobject().is_get_removead;
                if (is_get1)
                {
                    ui.panel_parent.panel.btn_max_remove.enabled = false;
                    ui.panel_parent.panel.btn_max_remove.SetClick(() => { });
                }
                else
                {
                    ui.panel_parent.panel.btn_max_remove.SetClick(() =>
                    {
                        ApplePayClass maxPayData = new ApplePayClass
                        {
                            amount = (int)Math.Round(price_remove * 100),
                            sku = MaxPayManager.remove_ad,
                            currency = "USD"
                        };
                        MaxPayManager.Instance.Buy(maxPayData);
                    });
                }

                if (GameHelper.IsGiftSwitch() && ConfigSystem.GetConfig<CommonModel>().PiggyBankSwitch == 1) (_panel.btn_max_remove.GetChild("img_saveingpot") as GImage).visible = true;

            }
            else
            {
                if (GameHelper.IsGiftSwitch() && ConfigSystem.GetConfig<CommonModel>().PiggyBankSwitch == 1) (_panel.btn_buyremovead.GetChild("img_saveingpot") as GImage).visible = true;
                _panel.btn_RemoveAdClaim.visible = GameHelper.CheckAdWatchCount(_removeADPrice);
                _panel.btn_buyremovead.visible = !_panel.btn_RemoveAdClaim.visible;
                _panel.btn_buyremovead.grayed = _inAdRewardCooldown;
                _panel.btn_buyremovead.touchable = !_inAdRewardCooldown;
                if (_removeADCooldownText == null && _panel.btn_buyremovead.GetChild("text_cooldown") is GTextField removeADCooldownText)
                {
                    _removeADCooldownText = removeADCooldownText;
                }

                if (_removeADCooldownText != null)
                {
                    _removeADCooldownText.visible = _inAdRewardCooldown;

                    if (_inAdRewardCooldown)
                    {
                        _removeADCooldownText.text = CommonHelper.TimeFormat(
                            (int)GameHelper.GetAdRewardCooldownTime() - Convert.ToInt32(GameHelper.GetNowTime()),
                            CountDownType.Hour);
                    }
                }

                _panel.btn_buyremovead.GetChild("title").visible = !_inAdRewardCooldown;
                _panel.btn_buyremovead.GetChild("icon").visible = !_inAdRewardCooldown;
            }

        }

        private void OnClickBuyPackWatchAdsBtn()
        {
            NetworkKit.BuriedPoint(BuriedPointEvent.Apple_pay_event,
                BuriedPointEvent.first_pack_click, 1);

            GameHelper.ShowVideoAd("BuyPack", success =>
            {
                if (success)
                {
                    GameHelper.UpdateAdRewardExchangeTime();
                }
            });
        }
        private void OnClickBuyRemoveAdWatchAdsBtn()
        {
            NetworkKit.BuriedPoint(BuriedPointEvent.Apple_pay_event,
                BuriedPointEvent.remove_ad_click, 1);
            GameHelper.ShowVideoAd("BuyRemoveAd", success =>
            {
                if (success)
                {
                    GameHelper.UpdateAdRewardExchangeTime();
                }
            });
        }

        private void OnClickBuyPack()
        {

            if (SaveData.GetSaveobject().is_get_packreward) return;

            if (GameHelper.CheckAdWatchCount((int)list[0].Paid_price))
            {
                GameHelper.AddAdWatchCount(-(int)list[0].Paid_price);
            }
            else
            {
                GameHelper.ShowTips("Insufficient AdWatchCount");
                return;
            }

            GameHelper.AddGoldNumber(gold_num);
            GameHelper.AddItemNumber(ItemEnum.AddHole, out_num);
            GameHelper.AddItemNumber(ItemEnum.MergeBox, back_num);
            GameHelper.AddItemNumber(ItemEnum.ClearHole, refresh_num);

            var start = GameHelper.GetUICenterPosition(ui.panel_parent.panel.text_goldnum);
            var end = GameHelper.GetUICenterPosition(ui.gold.GetChild("number_text"));


            reward_data temp = new reward_data() { start = start, end = end, change = list[0].coins_quantity, type = 101 };
            UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.CoinWnd_newUI_Open, temp);


            DOVirtual.DelayedCall(1, () =>
            {
                DOVirtual.Float(0, GameHelper.GetGoldNumber(), 1,
                    value => { ui.gold.GetChild("number_text").text = ((int)value).ToString(); });
            });

            SaveData.GetSaveobject().is_get_packreward = true;
            NetworkKit.BuriedPoint(BuriedPointEvent.Apple_pay_event,
                BuriedPointEvent.first_pack_success, 1);
            SaveData.saveDataFunc();
            GameDispatcher.Instance.Dispatch(GameMsg.Gold_refresh);
            GameDispatcher.Instance.Dispatch(GameMsg.Sheep_item_refresh);
            GameDispatcher.Instance.Dispatch(GameMsg.BuyPack);
            InitView();
        }

        private void OnClickBuyRemoveAd()
        {
            // GooglePayClass info = new GooglePayClass()
            // {
            //     transactionId = "",
            //     amount = (int)(list[1].Paid_price * 100),
            //     sku = GooglePaymentManager.remove_ad,
            //     currency = "USD"
            // };
            //
            // GooglePaymentManager.Instance.BuyProduct(GooglePaymentManager.remove_ad, info);
            if (SaveData.GetSaveobject().is_get_removead) return;

            if (GameHelper.CheckAdWatchCount((int)list[1].Paid_price))
            {
                GameHelper.AddAdWatchCount(-(int)list[1].Paid_price);
            }
            else
            {
                GameHelper.ShowTips("Insufficient AdWatchCount");
                return;
            }

            GameHelper.AddGoldNumber(_removeAdAddGoldNum);
            var start = GameHelper.GetUICenterPosition(ui.panel_parent.panel.text_goldnum2);
            var end = GameHelper.GetUICenterPosition(ui.gold.GetChild("number_text"));

            reward_data temp = new reward_data() { start = start, end = end, change = _removeAdAddGoldNum, type = 101 };
            UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.CoinWnd_newUI_Open, temp);

            DOVirtual.DelayedCall(1, () =>
            {
                DOVirtual.Float(0, GameHelper.GetGoldNumber(), 1,
                    value => { ui.gold.GetChild("number_text").text = ((int)value).ToString(); });
            });

            UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.AdcomingUI_Close);

            SaveData.GetSaveobject().is_get_removead = true;
            SaveData.saveDataFunc();
            NetworkKit.BuriedPoint(BuriedPointEvent.Apple_pay_event,
                BuriedPointEvent.remove_ad_success, 1);
            GameDispatcher.Instance.Dispatch(GameMsg.Gold_refresh);
            GameDispatcher.Instance.Dispatch(GameMsg.Sheep_item_refresh);
            GameDispatcher.Instance.Dispatch(GameMsg.BuyRemoveAdPack);
            InitView();
        }
    }
}
public class PackRewardData
{
    public bool isAutoPop;
    public bool isNeedScroll;
}