using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using FutureCore;
using FairyGUI;
using FGUI.threeDaysGift;
using Spine.Unity;
using DG.Tweening;
using FGUI.A000_common;
using System;

namespace ScrewsMaster
{
    public class ThreeDaysGiftUI : BaseUI
    {
        private ThreeDaysGiftUICtrl ctrl;
        private ThreeDaysGiftModel model;
        private FGUI.threeDaysGift.com_three_days ui;

        public ThreeDaysGiftUI(ThreeDaysGiftUICtrl ctrl) : base(ctrl)
        {
            uiName = UIConst.ThreeDaysGiftUI;
            this.ctrl = ctrl;
        }

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

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

        }

        protected override void OnClose()
        {
            HallManager.Instance.UpdateSecondEvent -= InitView;
            GameHelper.showGameUI = true;
            GameDispatcher.Instance.Dispatch(GameMsg.pack_close);
        }

        protected override void OnBind()
        {
            ui = baseUI as FGUI.threeDaysGift.com_three_days;
        }
        private Action closeCallback;
        protected override void OnOpenBefore(object args)
        {

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

            list = ConfigSystem.GetConfig<MultigiftModel>().dataList;

            ui.btn_close.SetClick(() =>
            {
                GameDispatcher.Instance.Dispatch(GameMsg.ThreeDaysGiftUIClose);
                CtrlCloseUI();
            });

            ui.groups.visible = false;

            var ske_bg = FXManager.Instance.SetFx<SkeletonAnimation>(ui.ani_bg, Fx_Type.fx_three_gift, ref closeCallback);
            ske_bg.state.SetAnimation(0, "3_days", false);
            ske_bg.state.Complete += (a) =>
            {
                ske_bg.state.SetAnimation(0, "3_days_dj", false);
            };

            DOVirtual.DelayedCall(0.5f, () =>
            {
                ui.groups.visible = true;
            });

            // var ske_btn = FXManager.Instance.SetFx<SkeletonAnimation>(ui.ani_title, Fx_Type.fx_title_effect, ref closeCallback);
            // ske_btn.state.SetAnimation(0, "animation", true);

            InitView();
            HallManager.Instance.UpdateSecondEvent += InitView;
            // WebviewManager.Instance.SetDarkThough(false);
        }

        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.rewardMul_close, rewardMul_close);
        }
        protected override void RemoveListener()
        {
            GameDispatcher.Instance.RemoveListener(GameMsg.apple_pay_success, pay_success);
            GameDispatcher.Instance.RemoveListener(GameMsg.rewardMul_close, rewardMul_close);
        }
        #endregion
        void pay_success(object str)
        {
            string type = (string)str;
            if (type == MaxPayManager.three_days_gift)
            {

                //                 var start =  Vector2.zero;
                //                 if (SaveData.GetSaveobject().three_gift_got_index == (int)rewardState.day1) {
                //                     start = GameHelper.GetUICenterPosition(ui.day1.item1.lab_num);
                //                 } else if (SaveData.GetSaveobject().three_gift_got_index == (int)rewardState.day2) {
                //                     start = GameHelper.GetUICenterPosition(ui.day2.item1.lab_num);
                //                 } else if (SaveData.GetSaveobject().three_gift_got_index == (int)rewardState.day3) {
                //                     start = GameHelper.GetUICenterPosition(ui.day3.item1.lab_num);
                //                 }
                // 
                //                 var rewardData = new RewardData();
                //                 var end = GameHelper.GetUICenterPosition(ui.node_end);
                // 
                //                 var rewardSingleData = new RewardSingleData(101, list[1].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;
                // 
                //                 UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.AdcomingUI_Close);
                //                 SaveData.GetSaveobject().is_get_removead = true;
                //                 InitView();
                SaveData.GetSaveobject().is_get_ThreeDaysGift = true;
                SaveData.saveDataFunc();
                ui.pay_type.selectedIndex = 2;
            }
            // GameDispatcher.Instance.Dispatch(GameMsg.noads_refresh);

        }

        void rewardMul_close(object str)
        {
            if (SaveData.GetSaveobject().three_gift_got_index == (int)rewardState.day1)
            {
                NetworkKit.BuriedPoint(BuriedPointEvent.Three_days_gift_event, BuriedPointEvent.three_day1_success, 1);
            }
            else if (SaveData.GetSaveobject().three_gift_got_index == (int)rewardState.day2)
            {
                NetworkKit.BuriedPoint(BuriedPointEvent.Three_days_gift_event, BuriedPointEvent.three_day2_success, 1);
            }
            else if (SaveData.GetSaveobject().three_gift_got_index == (int)rewardState.day3)
            {
                NetworkKit.BuriedPoint(BuriedPointEvent.Three_days_gift_event, BuriedPointEvent.three_day3_success, 1);
            }

            SaveData.GetSaveobject().three_gift_got_index++;
            SaveData.GetSaveobject().last_got_three_gift_time = GameHelper.GetNowTime();

        }

        private List<Multigift> list;


        private void InitView()
        {
            // ui.text_have.text = "Owner ADs:" + SaveData.GetSaveobject().look_ad_numbers;
            // ui.need_text.text = "need " + list[0].Paid_price + " ADs";

            ui.text_have.text = $"You Have ADs:{GameHelper.GetAdWatchCount()}";
            ui.need_text.text = $"Need ADs:{list[0].Paid_price}";

            ui.btn_buypack.GetChild("img_saveingpot").visible = false;
            ui.btn_max_pack.GetChild("img_saveingpot").visible = false;

            initItem(0);
            initItem(1);
            initItem(2);

            btn_green btn_buypack = (ui.btn_buypack as btn_green);
            GObject pack_title = ui.btn_buypack.GetChild("title");

            if (SaveData.GetSaveobject().is_get_ThreeDaysGift)
            {
                ui.pay_type.selectedIndex = 2;
                var isToday = GameHelper.InToday(SaveData.GetSaveobject().last_got_three_gift_time, 0, true);
                int three_gift_got_index = SaveData.GetSaveobject().three_gift_got_index;
                if (isToday || (three_gift_got_index > (int)rewardState.day3))
                {
                    ui.btn_get.grayed = true;
                    ui.btn_get.SetClick(() =>
                    {
                        if (three_gift_got_index < (int)rewardState.day3)
                        {
                            GameHelper.ShowTips("Come back and pick it up tomorrow.");
                        }
                    });
                }
                else
                {
                    ui.btn_get.SetClick(() =>
                    {
                        getReward();
                        ui.btn_get.SetClick(() => { });
                    });
                }

            }
            else
            {

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



                    ui.pay_type.selectedIndex = 0;
                    bool is_get = SaveData.GetSaveobject().is_get_ThreeDaysGift;
                    if (is_get)
                    {
                        btn_buypack.state.selectedIndex = 0;
                        btn_buypack.cooldown.selectedIndex = 1;
                        ui.btn_buypack.grayed = true;
                        pack_title.text = "Cliamed";
                        ui.btn_buypack.SetClick(() =>
                        {

                        });
                    }
                    else if (GameHelper.GetAdWatchCount() >= list[0].Paid_price)
                    {
                        btn_buypack.state.selectedIndex = 1;
                        btn_buypack.cooldown.selectedIndex = 0;
                        btn_buypack.SetClick(() => //购买成功
                        {
                              NetworkKit.BuriedPoint(BuriedPointEvent.Apple_AD_event, BuriedPointEvent.three_days_gift_buy_success, 1);
                            //   SaveData.GetSaveobject().look_ad_numbers -= (int)list[0].Paid_price;
                            GameHelper.AddAdWatchCount(-(int)list[0].Paid_price);

                            GameDispatcher.Instance.Dispatch(GameMsg.apple_pay_success, MaxPayManager.three_days_gift);

                            // getReward();
                            ui.btn_buypack.SetClick(() => { });
                        });
                    }
                    else if (GameHelper.GetAdRewardCooldownTime() > GameHelper.GetNowTime())
                    {
                        btn_buypack.state.selectedIndex = 0;
                        btn_buypack.cooldown.selectedIndex = 1;
                        pack_title.text = CommonHelper.TimeFormat((int)GameHelper.GetAdRewardCooldownTime() - Convert.ToInt32(GameHelper.GetNowTime()), CountDownType.Hour);
                        btn_buypack.SetClick(() => { });
                    }
                    else
                    {
                        btn_buypack.state.selectedIndex = 0;
                        btn_buypack.cooldown.selectedIndex = 0;
                        if (GameHelper.IsGiftSwitch() && ConfigSystem.GetConfig<CommonModel>().PiggyBankSwitch == 1)
                        {
                            ui.btn_buypack.GetChild("img_saveingpot").visible = true;
                        }
                        pack_title.text = "Watch AD";
                        btn_buypack.SetClick(() =>
                        {
                            OnClickBuyPackWatchAdsBtn();
                        });
                    }
                }
            }

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

            GameHelper.ShowVideoAd("buy_failpack", success =>
            {
                if (success)
                {
                    GameHelper.UpdateAdRewardExchangeTime();
                }
            });
        }
        private void initItem(int index)
        {
            com_item day = null;
            if (index == 0)
            {
                day = ui.day1;
            }
            else if (index == 1)
            {
                day = ui.day2;
            }
            else if (index == 2)
            {
                day = ui.day3;
            }

            if (SaveData.GetSaveobject().three_gift_got_index - 1 > index)
            {
                day.img_select.visible = true;
                if (SaveData.GetSaveobject().three_gift_got_index - 1 > 2)
                {
                    day.img_select2.visible = true;
                }
            }

            day.state.selectedIndex = list[index].props_quantity.Length;

            setItemUrl(day.item1.loader_, GiftType.coin);
            day.item1.lab_num.text = "x" + list[index].coins_quantity;

            for (int i = 0; i < list[index].props_quantity.Length; i++)
            {
                item_reward item = (day.GetChild("item" + (i + 2)) as item_reward);
                setItemUrl(item.loader_, (GiftType)list[index].props_type[i]);

                item.lab_num.text = "x" + list[index].props_quantity[i];
            }
        }

        private void setItemUrl(GLoader loader, GiftType urltype)
        {
            if (urltype == GiftType.coin) loader.url = "ui://threeDaysGift/3DAYS_prs_001";
            else if (urltype == GiftType.move_out) loader.url = "ui://threeDaysGift/3DAYS_prs_002";
            else if (urltype == GiftType.refresh) loader.url = "ui://threeDaysGift/3DAYS_prs_003";
            else if (urltype == GiftType.undo) loader.url = "ui://threeDaysGift/3DAYS_prs_004";
        }

        private void getReward()
        {
            int index = SaveData.GetSaveobject().three_gift_got_index;

            com_item item = null;
            if (index == (int)rewardState.day1)
            {
                item = ui.day1;
            }
            else if (index == (int)rewardState.day2)
            {
                item = ui.day2;
            }
            else if (index == (int)rewardState.day3)
            {
                item = ui.day3;
            }
            item.img_select.visible = true;


            List<int> types = new List<int>();
            List<int> rewards = new List<int>();
            types.Add((int)GiftType.coin);
            rewards.Add(list[index - 1].coins_quantity);
            for (int i = 0; i < list[index - 1].props_quantity.Length; i++)
            {
                types.Add(list[index - 1].props_type[i]);  // GiftType 类型
                rewards.Add(list[index - 1].props_quantity[i]);
            }
            GiftData data = new GiftData();
            data.type = types;
            data.reward = rewards;
            uiCtrlDispatcher.Dispatch(UICtrlMsg.RewardMulNewUI_Open, data);
        }
    }
}
enum rewardState
{
    day1 = 1,
    day2,
    day3
}
public class GiftData
{
    public List<int> type;
    public List<int> reward;
    public string uiName;
}

public enum GiftType : int
{
    coin = 101,
    move_out = 0,
    undo = 1,
    refresh = 2,
}