
using System;
using FGUI.A000_common;
using UnityEngine;
using FairyGUI;
using Roy.Datas;
using SGame;
using DG.Tweening;

namespace ScrewsMaster
{
    public class PropUI : BaseUI
    {
        private PropUICtrl ctrl;
        private PropModel model;
        private FGUI.G003_play.com_prop ui;
        private int type;
        private int num;

        private PropViewData _data;

        private int _payBoxPrice;
        private bool _needWatchAds;

        public PropUI(PropUICtrl ctrl) : base(ctrl)
        {
            uiName = UIConst.PropUI;
            this.ctrl = ctrl;
        }

        protected override void SetUIInfo(UIInfo uiInfo)
        {
            uiInfo.packageName = "G003_play";
            uiInfo.assetName = "com_prop";
            uiInfo.layerType = UILayerType.Normal;
            uiInfo.isNeedOpenAnim = true;
            uiInfo.isNeedCloseAnim = true;
            uiInfo.isNeedUIMask = true;
        }

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

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

        protected override void OnBind()
        {
            ui = baseUI as FGUI.G003_play.com_prop;
        }

        protected override void OnOpenBefore(object args)
        {
            _data = args as PropViewData;
            if (_data != null)
            {
                type = _data.type;
                num = _data.index;
            }

            // args.GetType().GetProperty("type").GetValue(args);
            // num = (int)args.GetType().GetProperty("index").GetValue(args);
            ui.cont_prop.selectedIndex = type;
            ui.pay_type.selectedIndex = GameHelper.IsAdModelOfPay() ? 0 : 1;
            if (type == 3)
            {
                Debug.Log(BuriedPointEvent.AddBoxShow + "_" + num);
                NetworkKit.BuriedPoint(BuriedPointEvent.Apple_pay_event, BuriedPointEvent.AddBoxShow + "_" + num, 1);
                HallManager.Instance.UpdateSecondEvent += UpdateButtonState;

            }
            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.AdRewardClaimed, OnUpdateAdReward);
            GameDispatcher.Instance.AddListener(GameMsg.AdWatchCountUpdated, OnUpdateAdReward);
            GameDispatcher.Instance.AddListener(GameMsg.apple_pay_success, pay_success);
        }
        protected override void RemoveListener()
        {

            GameDispatcher.Instance.RemoveListener(GameMsg.AdRewardClaimed, OnUpdateAdReward);
            GameDispatcher.Instance.RemoveListener(GameMsg.AdWatchCountUpdated, OnUpdateAdReward);
            GameDispatcher.Instance.RemoveListener(GameMsg.apple_pay_success, pay_success);
        }

        private void OnUpdateAdReward(object data)
        {
            UpdateWatchAdsText();
            UpdateButtonState();
        }
        #endregion
        void pay_success(object str)
        {
            string type = (string)str;
            if (type == MaxPayManager.buy_one)
            {
                ShowScrews.Instance.OnSuccessPayBox1(num);
                SetButtonsTouchable(false);
                DOVirtual.DelayedCall(0.1f, () =>
                {
                    CtrlCloseUI();
                });
            }
        }
        //初始化页面逻辑
        private void InitView()
        {
            // var addPrice = ConfigSystem.GetConfig<CommonModel>().Purchaseprops;
            // var mergePrice = ConfigSystem.GetConfig<CommonModel>().Purchaseprops;
            // var cleanPrice = ConfigSystem.GetConfig<CommonModel>().Purchaseprops;
            _payBoxPrice = (int)ConfigSystem.GetConfig<CommonModel>().addspace;
            if (type != 3)
            {
                _payBoxPrice = 1;

            }

            // if (ui.btn_add is btn_revive btnAdd) btnAdd.txt_coin.text = addPrice.ToString();
            // ui.btn_add.onClick.Add(() =>
            // {
            //     if (!GameHelper.CheckGoldNumber(addPrice))
            //     {
            //         GameHelper.ShowTips("Not Enough Coins");
            //         return;
            //     }
            //     GameHelper.AddGoldNumber(-addPrice);
            //     GameDispatcher.Instance.Dispatch(GameMsg.Gold_refresh);

            //     GameHelper.AddItemNumber(ItemEnum.AddHole, 1);
            //     SetButtonsTouchable(false);
            //     CtrlCloseUI();
            //     ShowScrews.Instance.ShowToast("Successful purchase");
            // });

            // if (ui.btn_merge is btn_revive btnMerge) btnMerge.txt_coin.text = mergePrice.ToString();
            // ui.btn_merge.onClick.Add(() =>
            // {
            //     if (!GameHelper.CheckGoldNumber(mergePrice))
            //     {
            //         GameHelper.ShowTips("Not Enough Coins");
            //         return;
            //     }
            //     GameHelper.AddGoldNumber(-mergePrice);
            //     GameDispatcher.Instance.Dispatch(GameMsg.Gold_refresh);

            //     GameHelper.AddItemNumber(ItemEnum.MergeBox, 1);

            //     SetButtonsTouchable(false);
            //     CtrlCloseUI();
            //     ShowScrews.Instance.ShowToast("Successful purchase");
            // });

            // if (ui.btn_clean is btn_revive btnClean) btnClean.txt_coin.text = cleanPrice.ToString();
            // ui.btn_clean.onClick.Add(() =>
            // {
            //     if (!GameHelper.CheckGoldNumber(cleanPrice))
            //     {
            //         GameHelper.ShowTips("Not Enough Coins");
            //         return;
            //     }
            //     GameHelper.AddGoldNumber(-cleanPrice);
            //     GameDispatcher.Instance.Dispatch(GameMsg.Gold_refresh);

            //     GameHelper.AddItemNumber(ItemEnum.ClearHole, 1);
            //     SetButtonsTouchable(false);
            //     CtrlCloseUI();
            //     ShowScrews.Instance.ShowToast("Successful purchase");
            // });

            // if (ui.btn_PayBox is btn_revive btnPayBox) btnPayBox.txt_coin.text = payBoxPrice.ToString();
            ui.btn_PayBox.onClick.Add(() =>
            {
                if (type != 3)
                {
                    if (_needWatchAds)
                    {
                        NetworkKit.BuriedPoint(BuriedPointEvent.Apple_pay_event, BuriedPointEvent.BuyProp + "_" + type, 1);
                        GameHelper.ShowVideoAd($"Prop", success =>
                        {
                            if (success)
                            {
                                GameHelper.UpdateAdRewardExchangeTime();
                            }
                        });
                        return;
                    }

                    if (GameHelper.CheckAdWatchCount(_payBoxPrice))
                    {
                        GameHelper.AddAdWatchCount(-_payBoxPrice);

                        // ShowScrews.Instance.OnSuccessPayBox1(num);
                        // SetButtonsTouchable(false);
                        // CtrlCloseUI();
                        // ShowScrews.Instance.ShowToast("Successful purchase");
                        if (type == 0) GameHelper.AddItemNumber(ItemEnum.AddHole, 1);
                        else if (type == 1) GameHelper.AddItemNumber(ItemEnum.MergeBox, 1);
                        else if (type == 2) GameHelper.AddItemNumber(ItemEnum.ClearHole, 1);
                        SetButtonsTouchable(false);
                        CtrlCloseUI();
                        ShowScrews.Instance.ShowToast("Exchange successful");
                    }
                    else
                    {
                        GameHelper.ShowTips("Insufficient AdWatchCount");
                    }
                }
                else if (type == 3)
                {
                    if (_needWatchAds)
                    {
                        NetworkKit.BuriedPoint(BuriedPointEvent.Apple_pay_event, BuriedPointEvent.AddBoxClick + "_" + num, 1);
                        GameHelper.ShowVideoAd($"PayBox", success =>
                        {
                            if (success)
                            {
                                GameHelper.UpdateAdRewardExchangeTime();
                            }
                        });
                        return;
                    }

                    if (GameHelper.CheckAdWatchCount(_payBoxPrice))
                    {
                        GameHelper.AddAdWatchCount(-_payBoxPrice);
                        ShowScrews.Instance.OnSuccessPayBox1(num);
                        SetButtonsTouchable(false);
                        CtrlCloseUI();
                        ShowScrews.Instance.ShowToast("Exchange successful");
                    }
                    else
                    {
                        GameHelper.ShowTips("Insufficient AdWatchCount");
                    }
                }
            });


            ui.btn_close.onClick.Add(() =>
            {
                this.ctrl.CloseUI();
            });
            UpdateButtonState();
            UpdateWatchAdsText();
            if (!GameHelper.IsAdModelOfPay())
            {
                ui.pay_type.selectedIndex = 1;
                decimal price = (decimal)GameHelper.GetCommonModel().addspace2;
                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(() =>
                {
                    Debug.Log(BuriedPointEvent.AddBoxClick + "_" + num);
                    NetworkKit.BuriedPoint(BuriedPointEvent.Apple_pay_event, BuriedPointEvent.AddBoxClick + "_" + num, 1);
                    ApplePayClass maxPayData = new ApplePayClass
                    {
                        amount = (int)Math.Round(price * 100),
                        sku = MaxPayManager.buy_one,
                        currency = "USD"
                    };
                    MaxPayManager.Instance.Buy(maxPayData);
                });
            }
        }

        private void UpdateWatchAdsText()
        {
            ui.text_hasADsCount.text = $"Owner ADs:{GameHelper.GetAdWatchCount()}";
            ui.text_NeedAds.text = $"Need {(int)_payBoxPrice} ADs";
        }

        private void UpdateButtonState()
        {
            (ui.btn_PayBox.GetChild("img_saveingpot") as GImage).visible = false;

            _needWatchAds = false;
            ui.btn_PayBox.touchable = true;
            ui.btn_PayBox.grayed = false;
            if (GameHelper.CheckAdWatchCount(_payBoxPrice))
            {
                ui.btn_PayBox.text = "Claim";
            }
            else if (GameHelper.InAdRewardCooldown())
            {
                ui.btn_PayBox.text = CommonHelper.TimeFormat((int)GameHelper.GetAdRewardCooldownTime() - Convert.ToInt32(GameHelper.GetNowTime()), CountDownType.Hour);
                ui.btn_PayBox.touchable = false;
                ui.btn_PayBox.grayed = true;
            }
            else
            {
                if (GameHelper.IsGiftSwitch() && ConfigSystem.GetConfig<CommonModel>().PiggyBankSwitch == 1) (ui.btn_PayBox.GetChild("img_saveingpot") as GImage).visible = true;

                _needWatchAds = true;
                ui.btn_PayBox.text = $"Watch Ad";
            }
        }

        private void SetButtonsTouchable(bool b)
        {
            // ui.btn_add.touchable = b;
            // ui.btn_merge.touchable = b;
            // ui.btn_clean.touchable = b;
            ui.btn_PayBox.touchable = b;
        }
    }
}