using System;
using System.Collections.Generic;
using DG.Tweening;
using FairyGUI;
using FGUI.Common_01;
using FGUI.threeDaysGift;
using IgnoreOPS;
using SGModule.Net;
using SGModule.NetKit;
using Spine.Unity;
using UnityEngine;

namespace ChillConnect
{
    public class ThreeDaysGiftUI : BaseUI
    {
        private ThreeDaysGiftUICtrl ctrl;
        private ThreeDaysGiftModel model;
        private 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);
            GameHelper.CallShowTurn();
        }

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

            // NetworkKit.BuriedPoint(BuriedPointEvent.Apple_pay_event, BuriedPointEvent.three_days_gift_show, 1);
            TrackKit.SendEvent(GameHelper.getTrackEvenName(),Property.ThreeDaysGiftShow);
            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.7f, () =>
            {
                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);
            InitBroadCast();
            InitView();
            HallManager.Instance.UpdateSecondEvent += InitView;
            if (Screen.safeArea.y != 0)
            {
                ui.broadcast_top.y += 68;
            }
            if (GameHelper.IsGiftSwitch())
            {
                ui.broadcast_top.visible = true;
            }
            // 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 == PurchasingManager.GetPaySku(PayType.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);
                //                 // DataMgr.Coin.Value -= list[1].coins_quantity;
                // 
                //                 UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.AdcomingUI_Close);
                //                 SaveData.GetSaveObject().is_get_removead = true;
                //                 InitView();

                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)
            {
                TrackKit.SendEvent(GameHelper.getTrackEvenName(),Property.ThreeDays1GiftSuccess);
                // NetworkKit.BuriedPoint(BuriedPointEvent.Three_days_gift_event, BuriedPointEvent.three_day1_success, 1);
            }
            else if (SaveData.GetSaveObject().three_gift_got_index == (int)rewardState.day2)
            {
                TrackKit.SendEvent(GameHelper.getTrackEvenName(),Property.ThreeDays2GiftSuccess);
                // NetworkKit.BuriedPoint(BuriedPointEvent.Three_days_gift_event, BuriedPointEvent.three_day2_success, 1);
            }
            else if (SaveData.GetSaveObject().three_gift_got_index == (int)rewardState.day3)
            {
                TrackKit.SendEvent(GameHelper.getTrackEvenName(),Property.ThreeDays3GiftSuccess);
                // 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()
        {
            int myAdNum = AdRedeemManager.Instance.GetLookRewardADNum();
            ui.text_have.text = "Owner ADs:" + myAdNum;
            ui.need_text.text = "need " + list[0].Paid_price + " ADs";
            ui.btn_buypack.GetChild("img_saveingpot").visible = false;
            ui.btn_max_pack.GetChild("img_saveingpot").visible = false;

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

            btn_watchAd btn_buypack = (ui.btn_buypack as btn_watchAd);
            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 = GameHelper.getPrice(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(() =>
                        {
                            Debug.Log(price_pack);
                            ApplePayClass maxPayData = new ApplePayClass
                            {
                                amount = (int)Math.Round(price_pack * 100),
                                sku = PurchasingManager.GetPaySku(PayType.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.buy_state.selectedIndex = 0;
                        btn_buypack.can_buy.selectedIndex = 1;
                        ui.btn_buypack.grayed = true;
                        pack_title.text = "Cliamed";
                        ui.btn_buypack.SetClick(() =>
                        {

                        });
                    }
                    else if (myAdNum >= list[0].Paid_price)
                    {
                        btn_buypack.buy_state.selectedIndex = 1;
                        btn_buypack.can_buy.selectedIndex = 0;
                        btn_buypack.SetClick(() =>
                        {
                            TrackKit.SendEvent(GameHelper.getTrackEvenName(),Property.ThreeDaysGiftBuySuccess);
                            // NetworkKit.BuriedPoint(BuriedPointEvent.Apple_AD_event, BuriedPointEvent.three_days_gift_buy_success, 1);
                            AdRedeemManager.Instance.SetLookRewardADNum(myAdNum - (int)list[0].Paid_price);
                            GameDispatcher.Instance.Dispatch(GameMsg.apple_pay_success, PurchasingManager.GetPaySku(PayType.three_days_gift));

                            //getReward();
                            ui.btn_buypack.SetClick(() => { });
                        });
                    }
                    else if (SaveData.GetSaveObject()._watch_ad_cd > GameHelper.GetNowTime())
                    {
                        btn_buypack.buy_state.selectedIndex = 0;
                        btn_buypack.can_buy.selectedIndex = 1;
                        btn_watchAd btn_buy = ui.btn_buypack as btn_watchAd;
                        btn_buy.btn_text.text = CommonHelper.TimeFormat(SaveData.GetSaveObject()._watch_ad_cd - Convert.ToInt32(GameHelper.GetNowTime()), CountDownType.Hour);
                        btn_buypack.SetClick(() => { });
                    }
                    else
                    {
                        btn_buypack.buy_state.selectedIndex = 0;
                        btn_buypack.can_buy.selectedIndex = 0;
                        if (GameHelper.IsGiftSwitch() && ConfigSystem.GetConfig<CommonModel>().PiggyBankSwitch == 1)
                        {
                            ui.btn_buypack.GetChild("img_saveingpot").visible = true;
                        }
                        btn_buypack.SetClick(() =>
                        {

                            GameHelper.ShowVideoAd("ThreeDaysGift", issuccess =>
                            {
                                if (issuccess)
                                {
                                    SaveData.GetSaveObject()._watch_ad_cd = (int)GameHelper.GetNowTime() + GameHelper.GetCommonModel().exchangeCD;
                                    InitView();
                                }
                            });
                            TrackKit.SendEvent(GameHelper.getTrackEvenName(),Property.ThreeDaysGiftClick);
                            // NetworkKit.BuriedPoint(BuriedPointEvent.Apple_AD_event, BuriedPointEvent.three_days_gift_click, 1);
                        });
                    }
                }
            }
            BroadCast();
        }

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

            if (index == 2)
            {
                day.state.selectedIndex = 3;
                for (int i = 0; i < 3; i++)
                {
                    item_reward item = day.GetChild("item" + (i + 2)) as item_reward;
                    item.visible = false;
                }
            }
            else
            {
                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.visible = true;
                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_003";
            else if (urltype == GiftType.refresh) loader.url = "ui://threeDaysGift/3DAYS_prs_004";
            else if (urltype == GiftType.undo) loader.url = "ui://threeDaysGift/3DAYS_prs_002";
        }

        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);
        }
        private int broadtime = 0;
        private List<string> config_name_list = ConfigSystem.GetConfig<LevelAttemptsModel>().config_name_list;
        private List<string> config_money_list = ConfigSystem.GetConfig<LevelAttemptsModel>().config_money_list;
        private List<string[]> broad_list = new List<string[]>();
        private List<GTextField> text_list = new List<GTextField>();
        private void InitBroadCast()
        {
            text_list.Add((ui.broadcast_top as broadcast_top).item_0.text_1);
            text_list.Add((ui.broadcast_top as broadcast_top).item_1.text_1);
            text_list.Add((ui.broadcast_top as broadcast_top).item_2.text_1);
            for (int i = 0; i < 3; i++)
            {

                int name_index = UnityEngine.Random.Range(0, config_name_list.Count);
                int money_index = UnityEngine.Random.Range(0, config_money_list.Count);
                broad_list.Add(new string[2] { config_name_list[name_index], config_money_list[money_index] });
                text_list[i].text = "Congratulations,User [color=#ff9600][size=42]" + broad_list[i][0] + "[/size][/color] !After purchasing the ThreeDays Bouns,play [color=#ff9600]" + broad_list[i][1] + "[/color] matcher to clear the stage!";
            }
        }


        private void BroadCast()
        {
            broadtime++;
            if (broadtime % 13 == 1)
            {
                (ui.broadcast_top as broadcast_top).t1.Play(() =>
                {

                    int name_index = UnityEngine.Random.Range(0, config_name_list.Count);
                    int money_index = UnityEngine.Random.Range(0, config_money_list.Count);
                    string[] array_ = new string[2] { config_name_list[name_index], config_money_list[money_index] };
                    text_list[0].text = "Congratulations,User [color=#ff9600][size=42]" + array_[0] +
                    "[/size][/color] !After purchasing the ThreeDays Bouns,play [color=#ff9600]" + array_[1] + "[/color] matcher to clear the stage!";
                });
            }
            else if (broadtime % 13 == 4)
            {
                (ui.broadcast_top as broadcast_top).t2.Play(() =>
                {

                    int name_index = UnityEngine.Random.Range(0, config_name_list.Count);
                    int money_index = UnityEngine.Random.Range(0, config_money_list.Count);
                    string[] array_ = new string[2] { config_name_list[name_index], config_money_list[money_index] };
                    text_list[1].text = "Congratulations,User [color=#ff9600][size=42]" + array_[0] +
                    "[/size][/color] !After purchasing the ThreeDays Bouns,play [color=#ff9600]" + array_[1] + "[/color] matcher to clear the stage!";
                });

            }
            else if (broadtime % 13 == 7)
            {
                (ui.broadcast_top as broadcast_top).t3.Play(() =>
                {

                    int name_index = UnityEngine.Random.Range(0, config_name_list.Count);
                    int money_index = UnityEngine.Random.Range(0, config_money_list.Count);
                    string[] array_ = new string[2] { config_name_list[name_index], config_money_list[money_index] };
                    text_list[2].text = "Congratulations,User [color=#ff9600][size=42]" + array_[0] +
                    "[/size][/color] !After purchasing the ThreeDays Bouns,play [color=#ff9600]" + array_[1] + "[/color] matcher to clear the stage!";
                });

            }
        }
    }
}
enum rewardState
{
    day1 = 1,
    day2,
    day3
}
public class GiftData
{
    public List<int> type;
    public List<int> reward;
    public string uiName;
}

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