using System;
using System.Collections.Generic;
using FairyGUI;
using UnityEngine;

namespace ScrewsMaster
{
    public class PassunlockUI : BaseUI
    {
        private PassunlockUICtrl ctrl;
        private PassunlockModel model;
        private FGUI.G009_video.com_passunlock ui;

        private int _price = 1;
        private GTextField _textCooldown;
        public PassunlockUI(PassunlockUICtrl ctrl) : base(ctrl)
        {
            uiName = UIConst.PassunlockUI;
            this.ctrl = ctrl;
        }

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

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

        protected override void OnClose()
        {
            HallManager.Instance.UpdateSecondEvent -= UpdateButtonState;
        }

        protected override void OnBind()
        {
            ui = baseUI as FGUI.G009_video.com_passunlock;
        }

        protected override void OnOpenBefore(object args)
        {
            NetworkKit.BuriedPoint(BuriedPointEvent.Apple_pay_event, BuriedPointEvent.pass_show, 1);
            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, OnAdRewardClaimed);
            GameDispatcher.Instance.AddListener(GameMsg.AdWatchCountUpdated, OnAdRewardClaimed);
        }
        protected override void RemoveListener()
        {
            GameDispatcher.Instance.RemoveListener(GameMsg.apple_pay_success, pay_success);
            GameDispatcher.Instance.RemoveListener(GameMsg.AdRewardClaimed, OnAdRewardClaimed);
            GameDispatcher.Instance.RemoveListener(GameMsg.AdWatchCountUpdated, OnAdRewardClaimed);
        }

        private void OnAdRewardClaimed(object args)
        {
            UpdateADsText();
            UpdateButtonState();

        }
        #endregion
        void pay_success(object str)
        {
            string type = (string)str;
            Debug.Log(str);
            if (type == MaxPayManager.battle_pass)
            {
                CtrlCloseUI();
            }
        }
        //初始化页面逻辑
        private void InitView()
        {
            ui.pay_type.selectedIndex = GameHelper.IsAdModelOfPay() ? 0 : 1;
            _price = (int)ConfigSystem.GetConfig<CommonModel>().Passportgift;
            ui.btn_close.SetClick(CtrlCloseUI);
            int gold = 0;

            UpdateADsText();
            UpdateButtonState();


            List<Passportrewards> Passportrewards_list = ConfigSystem.GetConfig<PassportrewardsModel>().dataList;
            for (int i = 0; i < Passportrewards_list.Count; i++)
            {

                if (Passportrewards_list[i].Paid_rewards_type == 0) gold += Passportrewards_list[i].Paid_rewards_num;

            }
            ui.text_allgold.text = gold.ToString();
            // ui.btn_buypass.GetChild("title").text = GameHelper.GetPaymentTypeVO().payicon + ConfigSystem.GetConfig<CommonModel>().Passportgift;
            // ui.btn_buypass.GetChild("title").text = $"{_price}";


            ui.btn_buypass.SetClick(OnClickWatchAdsBtn);
            ui.btn_Claim.SetClick(OnClickBuyPassBtn);

            if (!GameHelper.IsAdModelOfPay())
            {
                ui.pay_type.selectedIndex = 1;
                decimal price = (decimal)GameHelper.GetCommonModel().Passportgift2;
                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;
                }
                else
                {
                    (ui.btn_max_pay.GetChild("img_saveingpot") as GImage).visible = false;
                }
                ui.btn_max_pay.SetClick(() =>
                {
                    ApplePayClass maxPayData = new ApplePayClass
                    {
                        amount = (int)Math.Round(price * 100),
                        sku = MaxPayManager.battle_pass,
                        currency = "USD"
                    };
                    MaxPayManager.Instance.Buy(maxPayData);
                });
            }

        }

        private void UpdateADsText()
        {
            ui.text_YourHaveAds.text = $"You Have ADs:{GameHelper.GetAdWatchCount()}";
            ui.text_NeedAds.text = $"Need ADs:{_price}";
        }

        private void UpdateButtonState()
        {
            var inAdRewardCooldown = GameHelper.InAdRewardCooldown();

            ui.btn_Claim.visible = GameHelper.CheckAdWatchCount(_price);
            ui.btn_buypass.visible = !ui.btn_Claim.visible;

            ui.btn_buypass.grayed = inAdRewardCooldown;
            ui.btn_buypass.touchable = !inAdRewardCooldown;
            if (GameHelper.IsGiftSwitch() && ConfigSystem.GetConfig<CommonModel>().PiggyBankSwitch == 1) (ui.btn_buypass.GetChild("img_saveingpot") as GImage).visible = true;
            if (_textCooldown == null && ui.btn_buypass.GetChild("text_cooldown") is GTextField textCooldown)
            {
                _textCooldown = textCooldown;
                HallManager.Instance.UpdateSecondEvent += UpdateButtonState;
            }

            _textCooldown.visible = inAdRewardCooldown;

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

            ui.btn_buypass.GetChild("title").visible = !inAdRewardCooldown;
            ui.btn_buypass.GetChild("icon").visible = !inAdRewardCooldown;
        }

        private void OnClickWatchAdsBtn()
        {
            NetworkKit.BuriedPoint(BuriedPointEvent.Apple_pay_event, BuriedPointEvent.pass_click, 1);
            GameHelper.ShowVideoAd("PassUnlock", (success) =>
            {
                if (success)
                {
                    GameHelper.UpdateAdRewardExchangeTime();
                }
            });
        }

        private void OnClickBuyPassBtn()
        {
            if (GameHelper.CheckAdWatchCount(_price))
            {
                GameHelper.AddAdWatchCount(-_price);
                CtrlCloseUI();
                GameDispatcher.Instance.Dispatch(GameMsg.apple_pay_success,MaxPayManager.battle_pass);

                NetworkKit.BuriedPoint(BuriedPointEvent.Apple_pay_event, BuriedPointEvent.pass_success, 1);
            }
            else
            {
                GameHelper.ShowTips("Insufficient AdWatchCount");
            }
            // GooglePayClass test = new GooglePayClass()
            // {
            //     transactionId = "",
            //     amount = (int)(ConfigSystem.GetConfig<CommonModel>().Passportgift * 100),
            //     sku = GooglePaymentManager.battle_pass,
            //     currency = "USD"
            // };
            //
            // GooglePaymentManager.Instance.BuyProduct(GooglePaymentManager.battle_pass, test);
        }
    }
}