using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using FutureCore;
using FairyGUI;
using FGUI.Pack_16;
using DG.Tweening;
using FGUI.Common_01;
using System;
using IgnoreOPS;
using SGModule.Net;
using IgnoreOPS;
using SGModule.NetKit;

namespace ChillConnect
{
    public class PackrewardUI : BaseUI
    {
        private PackrewardUICtrl ctrl;
        private PackrewardModel model;
        private FGUI.Pack_16.com_packaward ui;
        private List<Paidgift> list;

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

        protected override void SetUIInfo(UIInfo uiInfo)
        {
            uiInfo.packageName = "Pack_16";
            uiInfo.assetName = "com_packaward";
            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 PackrewardModel;
        }

        private bool isAutoPop = false;

        protected override void OnClose()
        {
            AdRedeemManager.Instance.Destroy();
            GameHelper.showGameUI = true;
            // WebviewManager.Instance.SetDarkThough(true);
            GameDispatcher.Instance.Dispatch(GameMsg.pack_close);
            HallManager.Instance.UpdateEvent -= InitView;
            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);
            }
            GameHelper.CallShowTurn();
        }

        protected override void OnBind()
        {
            ui = baseUI as FGUI.Pack_16.com_packaward;
        }

        protected override void OnOpenBefore(object args)
        {
            if (Screen.safeArea.y != 0)
            {
                //刘海屏
                ui.gold.y += Screen.safeArea.y;
            }

            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);
            if (need_scroll)
            {
                TrackKit.SendEvent(GameHelper.getTrackEvenName(),Property.RemoveAdShow);
            }
            else
            {
                TrackKit.SendEvent(GameHelper.getTrackEvenName(),Property.FirstPackShow);
            }

            ui.gold.GetChild("text_gold").text = GameHelper.Get101Str(GameHelper.GetGoldNumber());


            list = ConfigSystem.GetConfig<PaidgiftModel>().DataList;

            if (GameHelper.IsAdModelOfPay())
            {
                AdRedeemManager.Instance.SetWatchAd(PurchasingManager.GetPaySku(PayType.pack_reward),
                    ui.panel_parent.panel.btn_buypack as btn_watchAd, SetTextString1);
                AdRedeemManager.Instance.SetWatchAd(PurchasingManager.GetPaySku(PayType.remove_ad),
                    ui.panel_parent.panel.btn_buyremovead as btn_watchAd, SetTextString1);
            }
            HallManager.Instance.UpdateEvent += InitView;
            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);
        }

        protected override void RemoveListener()
        {
            GameDispatcher.Instance.RemoveListener(GameMsg.apple_pay_success, pay_success);
        }

        #endregion

        void pay_success(object str)
        {
            string type = (string)str;
            if (type == PurchasingManager.GetPaySku(PayType.remove_ad))
            {
                var gold = list[1].coins_quantity;
                var start = GameHelper.GetUICenterPosition(ui.panel_parent.panel.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;
                InitView();
            }
            else if (type == PurchasingManager.GetPaySku(PayType.pack_reward))
            {
                var start = GameHelper.GetUICenterPosition(ui.panel_parent.panel.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 = new Vector2(end.x - 100, end.y - 180)
                };
                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;
                Debug.Log(SaveData.GetSaveObject().is_get_packreward+"////////////////////////");
                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.panel_parent.panel.btn_close0.SetClick(CtrlCloseUI);
            ui.panel_parent.panel.btn_close1.SetClick(CtrlCloseUI);
            ui.panel_parent.panel.text_goldnum.text = "x" + GameHelper.Get101Str(gold_num);
            ui.panel_parent.panel.text_backnum1.text = "x" + back_num;
            ui.panel_parent.panel.text_outnum.text = "x" + out_num;
            ui.panel_parent.panel.text_refreshnum.text = "x" + refresh_num;
            var buy_text = ui.panel_parent.panel.btn_buypack.GetChild("title") as GTextField;
            buy_text.SetVar("price", list[0].Paid_price.ToString()).FlushVars();

            ui.panel_parent.panel.text_goldnum2.text = "x" + GameHelper.Get101Str(list[1].coins_quantity);
            var buy_text1 = ui.panel_parent.panel.btn_buyremovead.GetChild("title") as GTextField;
            buy_text1.SetVar("price", list[1].Paid_price.ToString()).FlushVars();
            if (GameHelper.IsGiftSwitch() && ConfigSystem.GetConfig<CommonModel>().PiggyBankSwitch == 1) (ui.panel_parent.panel.btn_max_pack.GetChild("img_saveingpot") as GImage).visible = true;
            if (GameHelper.IsGiftSwitch() && ConfigSystem.GetConfig<CommonModel>().PiggyBankSwitch == 1) (ui.panel_parent.panel.btn_max_remove.GetChild("img_saveingpot") as GImage).visible = true;
            if (!GameHelper.IsAdModelOfPay())
            {
                ui.panel_parent.panel.pay_type.selectedIndex = 1;
                decimal price_pack = (decimal)list[0].Paid_price2;
                ui.panel_parent.panel.btn_max_pack.title = GameHelper.getPrice(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 = PurchasingManager.GetPaySku(PayType.pack_reward),
                            currency = "USD"
                        };
                        MaxPayManager.Instance.Buy(maxPayData);
                    });
                }

                decimal price_remove = (decimal)list[1].Paid_price2;
                ui.panel_parent.panel.btn_max_remove.title = GameHelper.getPrice(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
                {
                    string sku = PurchasingManager.GetPaySku(PayType.pack_reward);
                    // if (GameHelper.IsGiftSwitch())
                    // {
                    //     sku = PurchasingManager.GetPaySku(PayType.pack_reward);
                    // }
                    // else
                    // {
                    sku = PurchasingManager.GetPaySku(PayType.remove_ad);
                    //}

                    ui.panel_parent.panel.btn_max_remove.SetClick(() =>
                    {
                        ApplePayClass maxPayData = new ApplePayClass
                        {
                            amount = (int)Math.Round(price_remove * 100),
                            sku = sku,
                            type = PurchasingManager.GetPaySku(PayType.remove_ad),
                            currency = "USD"
                        };
                        MaxPayManager.Instance.Buy(maxPayData);
                    });
                }
            }
            else
            {
                ui.panel_parent.panel.pay_type.selectedIndex = 0;
                AdRedeemManager.Instance.Start();
                SetTextString1();
            }
            ui.panel_parent.panel.btn_max_remove.grayed = false;
            if (GameHelper.IsAdModelOfPay())
            {
                if (SaveData.GetSaveObject()._watch_ad_cd > GameHelper.GetNowTime())
                {
                    // (ui.panel_parent.panel.btn_buyremovead as btn_watchAd).buy_state.selectedIndex = 0;
                    (ui.panel_parent.panel.btn_buyremovead as btn_watchAd).can_buy.selectedIndex = 1;
                    (ui.panel_parent.panel.btn_buyremovead as btn_watchAd).btn_text.text = CommonHelper.TimeFormat((int)SaveData.GetSaveObject()._watch_ad_cd - Convert.ToInt32(GameHelper.GetNowTime()), CountDownType.Hour);

                }
                else if (SaveData.GetSaveObject().remove_ad_time > GameHelper.GetNowTime())
                {
                    (ui.panel_parent.panel.btn_buyremovead as btn_watchAd).buy_state.selectedIndex = 0;
                    (ui.panel_parent.panel.btn_buyremovead as btn_watchAd).can_buy.selectedIndex = 1;
                    (ui.panel_parent.panel.btn_buyremovead as btn_watchAd).btn_text.text = CommonHelper.TimeFormat((int)SaveData.GetSaveObject().remove_ad_time - Convert.ToInt32(GameHelper.GetNowTime()), CountDownType.Hour);
                }

            }
            else
            {
                if (SaveData.GetSaveObject().remove_ad_time > GameHelper.GetNowTime())
                {
                    // (item.btn_max_remove as btn_yellow).can_buy.selectedIndex = 1;
                    ui.panel_parent.panel.btn_max_remove.grayed = true;
                    ui.panel_parent.panel.btn_max_remove.title = CommonHelper.TimeFormat((int)SaveData.GetSaveObject().remove_ad_time - Convert.ToInt32(GameHelper.GetNowTime()), CountDownType.Hour);
                }

            }

            ui.panel_parent.panel.text_removetime.text = "Valid for " + GameHelper.GetCommonModel().RemoveADsPackDuration + " hours";

        }

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

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


    public class PackRewardData
    {
        public bool isAutoPop;
        public bool isNeedScroll;
    }
}