using System.Collections.Generic;
using UnityEngine;
using FairyGUI;
using FGUI.ZM_Pass_14;
using DG.Tweening;
using System;
using FGUI.ZM_Common_01;
using Spine.Unity;

namespace RedHotRoast {
    public class PassViewUI : BaseUI {
        private PassViewUICtrl ctrl;
        private PassViewModel model;
        private FGUI.ZM_Pass_14.com_pass_view ui;
        List<PassingTask> passing_list = new List<PassingTask>();
        List<Durationtasks> Durationtasks_list = new List<Durationtasks>();
        List<Passportrewards> Passportrewards_list = new List<Passportrewards>();
        private Vector2 start_pos;



        public PassViewUI(PassViewUICtrl ctrl) : base(ctrl) {
            uiName = UIConst.PassViewUI;
            this.ctrl = ctrl;
        }

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

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

        protected override void OnClose() {
            GameHelper.showGameUI = true;
            HallManager.Instance.UpdateSecondEvent -= upData;

        }

        protected override void OnBind() {
            ui = baseUI as FGUI.ZM_Pass_14.com_pass_view;
        }

        protected override void OnOpenBefore(object args) {

            if (Screen.safeArea.y != 0)
            {
                // ui.gold.y += Screen.safeArea.y;
                // ui.close.y += Screen.safeArea.y;
                // ui.top_bg.height += Screen.safeArea.y;
                 ui.group_.y += 66;
            }

            if (GameHelper.GetGameday() != DateTime.Now.Day) {
                DataMgr.GameTime.Value = 0;
                SaveData.GetSaveObject().time_task_record = new List<int>();
                GameHelper.SetGameday();
            }

            HallManager.Instance.UpdateSecondEvent += upData;
            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.Update101, SetTopCurr);
            GameDispatcher.Instance.AddListener(GameMsg.Gold_refresh, SetTopCurr);
        }
        protected override void RemoveListener() {
            GameDispatcher.Instance.RemoveListener(GameMsg.apple_pay_success, pay_success);
            GameDispatcher.Instance.RemoveListener(GameMsg.Update101, SetTopCurr);
            GameDispatcher.Instance.RemoveListener(GameMsg.Gold_refresh, SetTopCurr);
        }
        #endregion
        void SetTopCurr(object a = null) {
            ui.gold.GetChild("text_gold").text = $"{DataMgr.Coin.Value:N0}";
        }

        private void pay_success(object a) {
            string type = (string) a;
            if (type == PurchasingManager.GetPaySku(PayType.battle_pass)){
                DOVirtual.DelayedCall(0.5f, () => {
                    SaveData.GetSaveObject().is_get_battlepass = true;
                    int gold = 0;
                    int _out = 0;
                    int _back = 0;
                    int _refresh = 0;
                    List<int> paylist = SaveData.GetSaveObject().battle_pass_paylist;
                    for (int i = 0; i < Passportrewards_list.Count; i++) {
                        if (GameHelper.GetBattleLv() > i) {
                            if (Passportrewards_list[i].Paid_rewards_type == 0)
                                gold += Passportrewards_list[i].Paid_rewards_num;
                            else if (Passportrewards_list[i].Paid_rewards_type == 1)
                                _out += Passportrewards_list[i].Paid_rewards_num;
                            else if (Passportrewards_list[i].Paid_rewards_type == 2)
                                _back += Passportrewards_list[i].Paid_rewards_num;
                            else if (Passportrewards_list[i].Paid_rewards_type == 3)
                                _refresh += Passportrewards_list[i].Paid_rewards_num;
                            SaveData.GetSaveObject().battle_pass_paylist.Add(i + 1);
                        }
                        else
                            break;
                    }

                    GameDispatcher.Instance.Dispatch(GameMsg.Gold_refresh);
                    GameHelper.AddItemNumber(0, _out);
                    GameHelper.AddItemNumber(1, _back);
                    GameHelper.AddItemNumber(2, _refresh);

                    GameDispatcher.Instance.Dispatch(GameMsg.Sheep_item_refresh);
                    SaveData.SaveDataFunc();
                    GameHelper.ShowTips("purchase_succ", true);


                    if (gold > 0) {
                        GetReward(gold, -1);
                    }

                    ui.list_panel.pass_list.numItems = Passportrewards_list.Count;
                    ui.btn_recive.visible = false;

                });
            }
        }

        //初始化页面逻辑
        private void InitView() {


            ui.close.SetClick(() => { UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PassViewUI_Close); });


            ui.gold.GetChild("text_gold").text = $"{DataMgr.Coin.Value:N0}";
            passing_list = ConfigSystem.GetConfig<PassingTask>();
            Durationtasks_list = ConfigSystem.GetConfig<Durationtasks>();
            Passportrewards_list = ConfigSystem.GetConfig<Passportrewards>();
            setPassCom();

            ui.btn_tips.SetClick(() => {
                tips_time = 20;
                ui.progress_pass.show_tips.selectedIndex = 1;
            });


            gotoItem();
        }

        private int tips_time = 0;

        void upData() {
            ui.remain_time.text = CommonHelper.TimeFormat(
                  SaveData.GetSaveObject().battle_pass_time + Passportrewards_list[0].Passportrewards_CD * 24 * 3600 - Convert.ToInt32(GameHelper.GetNowTime()),
                  CountDownType.Day);

            if ((SaveData.GetSaveObject().battle_pass_time + Passportrewards_list[0].Passportrewards_CD * 24 * 3600) < GameHelper.GetNowTime()) {
                SaveData.GetSaveObject().battle_pass_time = (int) GameHelper.GetNowTime();
                SaveData.GetSaveObject().battle_pass_freelist.Clear();
                SaveData.GetSaveObject().battle_pass_paylist.Clear();
                SaveData.GetSaveObject().is_get_battlepass = false;
                GameHelper.ResetGameExp();
                SaveData.SaveDataFunc();
                setPassCom();
            }

            tips_time++;
            if (tips_time > 20) {
                ui.progress_pass.show_tips.selectedIndex = 1;
            }
            if (tips_time > 25) {
                ui.progress_pass.show_tips.selectedIndex = 0;
                tips_time = 0;
            }

        }
        void setPassCom() {
            if ((SaveData.GetSaveObject().battle_pass_time + Passportrewards_list[0].Passportrewards_CD * 24 * 3600) < GameHelper.GetNowTime()) {
                SaveData.GetSaveObject().battle_pass_time = (int) GameHelper.GetNowTime();
                GameHelper.ResetGameExp();
                SaveData.GetSaveObject().battle_pass_freelist.Clear();
                SaveData.GetSaveObject().battle_pass_paylist.Clear();
                SaveData.GetSaveObject().is_get_battlepass = false;
                SaveData.SaveDataFunc();
            }
            upData();
            ui.list_panel.pass_list.itemRenderer = battle_itemRender;
            ui.list_panel.pass_list.numItems = Passportrewards_list.Count;

            ui.text_level.text = GameHelper.GetBattleLv().ToString();

            ui.progress_pass.value = GameHelper.GetGameExp();

            if (GameHelper.GetBattleLv() >= Passportrewards_list.Count) {
                ui.progress_pass.max = Passportrewards_list[GameHelper.GetBattleLv() - 1].Eliminating_quantity;
                ui.progress_pass.text_num.text = GameHelper.GetGameExp().ToString();
            }
            else {
                ui.progress_pass.max = Passportrewards_list[GameHelper.GetBattleLv()].Eliminating_quantity;
                ui.progress_pass.text_num.text = GameHelper.GetGameExp() + "/" + Passportrewards_list[GameHelper.GetBattleLv()].Eliminating_quantity;
            }

            ui.btn_recive.visible = !SaveData.GetSaveObject().is_get_battlepass;
            ui.btn_recive.SetClick(() => {
                // if (!GameHelper.IsGiftSwitch())UnlockPass();
                UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PassunlockUI_Open);

            });

        }
        void setItemUrl(GLoader loader, int urltype) {
            if (urltype == 0)
                loader.url = "ui://ZM_Pass_14/bbq_gold02";
            else if (urltype == 4)
                loader.url = "ui://ZM_Pass_14/bbq_gold02";
            else if (urltype == 1)
                loader.url = "ui://ZM_Common_01/triple_game_dj_001";
            else if (urltype == 2)
                loader.url = "ui://ZM_Common_01/triple_game_dj_002";
            else if (urltype == 3)
                loader.url = "ui://ZM_Common_01/triple_game_dj_003";
        }
        void seItemClick(com_item_award item, int number, int type, int index = 0) {
            if (type == 0) {
                GetReward(number, index);
                getRewardIndex = -1;
            }
            else {
                GameHelper.AddItemNumber(type - 1, number);
                GameDispatcher.Instance.Dispatch(GameMsg.Sheep_item_refresh);
            }

            ui.list_panel.pass_list.numItems = Passportrewards_list.Count;

            GameDispatcher.Instance.Dispatch(GameMsg.RefreshRedDot);
        }


        private void UnlockPass() {
            GameHelper.ShowVideoAd("pass_unlock", isSuccess => {
                if (isSuccess) {
                    SaveData.GetSaveObject().is_get_battlepass = true;
                    int gold = 0;
                    int out_ = 0;
                    int back_ = 0;
                    int refresh_ = 0;

                    for (int i = 0; i < Passportrewards_list.Count; i++) {
                        if (GameHelper.GetBattleLv() > i) {
                            if (Passportrewards_list[i].Paid_rewards_type == 0)
                                gold += Passportrewards_list[i].Paid_rewards_num;
                            else if (Passportrewards_list[i].Paid_rewards_type == 1)
                                out_ += Passportrewards_list[i].Paid_rewards_num;
                            else if (Passportrewards_list[i].Paid_rewards_type == 2)
                                back_ += Passportrewards_list[i].Paid_rewards_num;
                            else if (Passportrewards_list[i].Paid_rewards_type == 3)
                                refresh_ += Passportrewards_list[i].Paid_rewards_num;
                            SaveData.GetSaveObject().battle_pass_paylist.Add(i + 1);
                        }
                        else
                            break;
                    }

                    if (gold > 0) {
                        GetReward(gold);
                        // var start = GameHelper.GetUICenterPosition(ui.btn_recive);
                        // var end = GameHelper.GetUICenterPosition(ui.gold.GetChild("icon"));

                        // var rewardData = new RewardData();
                        // var rewardSingleData = new RewardSingleData(101, gold, RewardOrigin.AdTask);
                        // 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 = ((int)value).ToString(); });
                        //                     });
                        // });

                        // GameDispatcher.Instance.Dispatch(GameMsg.GetReward, rewardData);
                    }

                    GameHelper.AddItemNumber(0, out_);
                    GameHelper.AddItemNumber(1, back_);
                    GameHelper.AddItemNumber(2, refresh_);
                    GameDispatcher.Instance.Dispatch(GameMsg.Sheep_item_refresh);
                    ui.list_panel.pass_list.numItems = Passportrewards_list.Count;
                    ui.btn_recive.visible = false;
                    SaveData.SaveDataFunc();
                }
            });
        }


        private void GetReward(int awardNum, int index = 0) {
            var rewardData = new RewardData();
            var end = GameHelper.GetUICenterPosition(ui.gold.GetChild("icon"));

            var rewardSingleData = new RewardSingleData(101, awardNum, RewardOrigin.Passview, index) {
                startPosition = start_pos,
                endPosition = new Vector2(end.x, end.y)
            };

            rewardData.AddReward(rewardSingleData);
            // rewardData.displayType = RewardDisplayType.RewardFly | RewardDisplayType.ValueChange;
            if (index >= 0) {
                rewardData.displayType = RewardDisplayType.RewardFly | RewardDisplayType.Dialog |
                               RewardDisplayType.ValueChange;
            }
            else
                rewardData.displayType = RewardDisplayType.RewardFly | RewardDisplayType.ValueChange;
            rewardData.AddCompleted(success => {
                if (success) {
                    var startNum = DataMgr.Coin.Value - awardNum;

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

        private int getRewardIndex = -1;

        void gotoItem() {
            if (getRewardIndex > 0) {
                ui.list_panel.pass_list.ScrollToView_UseAnim(getRewardIndex - 1, true, 0.65f);
            }
        }

        private Action closeCallback = null;
        private List<SkeletonAnimation> free_anims = new List<SkeletonAnimation>();
        private List<SkeletonAnimation> pay_anims = new List<SkeletonAnimation>();

        //初始化动画列表
        private void EnsureListHasAnimation(List<SkeletonAnimation> animList, int index, GGraph parent, Fx_Type fxType) {
            int realIndex = index - 1;
            // 扩展列表到目标索引
            while (realIndex >= animList.Count) {
                animList.Add(null);
            }

            // 如果目标位置没有动画，则设置
            if (animList[realIndex] == null) {
                animList[realIndex] = FXManager.Instance.SetFx<SkeletonAnimation>(parent, fxType, ref closeCallback);
            }
        }

        void battle_itemRender(int index, GObject obj) {
            index++;
            int pass_level = GameHelper.GetBattleLv();
            com_pass_item item = (com_pass_item) obj;
            item.index_text.text = index.ToString();
            item.free_item.type.selectedIndex = 0;
            item.pay_item.type.selectedIndex = 1;

            // EnsureListHasAnimation(free_anims, index, item.free_item.anim_parent, Fx_Type.fx_pass_free);
            // EnsureListHasAnimation(pay_anims, index, item.pay_item.anim_parent, Fx_Type.fx_pass_premium);

            List<int> freelist = SaveData.GetSaveObject().battle_pass_freelist;
            List<int> paylist = SaveData.GetSaveObject().battle_pass_paylist;
            if (index > 0) {

                item.free_item.number_text.text = "x" + GameHelper.Get101Str(Passportrewards_list[index - 1].Free_rewards_num);
                item.pay_item.number_text.text = "x" + GameHelper.Get101Str(Passportrewards_list[index - 1].Paid_rewards_num);
                if (Passportrewards_list[index - 1].Free_rewards_type == 0) {
                    setItemUrl(item.free_item.item_loader, 0);
                }
                else {
                    setItemUrl(item.free_item.item_loader, Passportrewards_list[index - 1].Paid_rewards_type);
                }
                if (Passportrewards_list[index - 1].Paid_rewards_type == 0) {
                    setItemUrl(item.pay_item.item_loader, 4);
                }
                else {
                    setItemUrl(item.pay_item.item_loader, Passportrewards_list[index - 1].Paid_rewards_type);
                    if (Passportrewards_list[index - 1].Paid_rewards_type >= 1 && Passportrewards_list[index - 1].Paid_rewards_type <= 3) {
                        // item.pay_item.item_loader.SetScale(0.55f, 0.55f);
                    }
                }
                if (index <= pass_level)//等级超过了
                {
                    if (freelist.Contains(index))//领取过
                    {
                        Debug.Log($"领取过------------{index}");
                        item.free_item.state.selectedIndex = 2;
                        item.free_item.SetClick(() => { });
                        item.free_item.btn_claim.SetClick(() => { });
                        // free_anims[index - 1].state.SetAnimation(0, "get2", true);
                    }
                    else {
                        if (getRewardIndex < 0)
                            getRewardIndex = index;
                        // free_anims[index - 1].state.SetAnimation(0, "appear", true);
                        item.free_item.state.selectedIndex = 1;
                        item.free_item.btn_claim.SetClick(() => {
                            // free_anims[index - 1].state.SetAnimation(0, "get", false);
                            // free_anims[index - 1].state.Complete += (trackEntry) => {
                            //     free_anims[index - 1].state.SetAnimation(0, "get2", true);
                            // };
                        
                            freelist.Add(index);
                            SaveData.SaveDataFunc();
                            // GameHelper.ShowTips("claim_succ", true);
                            seItemClick(item.free_item, Passportrewards_list[index - 1].Free_rewards_num, Passportrewards_list[index - 1].Free_rewards_type, index - 1);
                            
                        });
                    }

                    if (paylist.Contains(index))//领取过
                    {
                        item.pay_item.state.selectedIndex = 2;
                        item.pay_item.SetClick(() => { });
                        item.pay_item.btn_claim.SetClick(() => { });
                        // pay_anims[index - 1].state.SetAnimation(0, "get2", true);
                    }
                    else {
                        if (SaveData.GetSaveObject().is_get_battlepass) {
                            if (getRewardIndex < 0)
                                getRewardIndex = index;
                            // pay_anims[index - 1].state.SetAnimation(0, "appear", true);

                            item.pay_item.state.selectedIndex = 1;
                            item.pay_item.btn_claim.SetClick(() => {
                                // pay_anims[index - 1].state.SetAnimation(0, "get", false);
                                // pay_anims[index - 1].state.Complete += (trackEntry) => {
                                //
                                //     pay_anims[index - 1].state.SetAnimation(0, "get2", true);
                                //
                                // };

                                paylist.Add(index);
                                SaveData.SaveDataFunc();
                                seItemClick(item.pay_item, Passportrewards_list[index - 1].Paid_rewards_num, Passportrewards_list[index - 1].Paid_rewards_type, -1);

                                GameHelper.ShowTips("claim_succ", true);

                            });
                        }
                        else {
                            item.pay_item.state.selectedIndex = 4;
                            item.pay_item.SetClick(() => {
                                // if (!GameHelper.IsGiftSwitch()) UnlockPass();
                                UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PassunlockUI_Open);
                            });
                        }

                    }

                }
                else {
                    item.free_item.state.selectedIndex = 0;//不可领取
                    item.free_item.SetClick(() => {
                        GameHelper.ShowTips("no_enough_lv_ps", true);
                    });
                    item.pay_item.SetClick(() => {
                        if (SaveData.GetSaveObject().is_get_battlepass) {
                            GameHelper.ShowTips("no_enough_lv_ps", true);
                        }
                        else {
                            // if (!GameHelper.IsGiftSwitch()) UnlockPass();
                            UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PassunlockUI_Open);
                        }
                    });
                    if (SaveData.GetSaveObject().is_get_battlepass) {
                        item.pay_item.state.selectedIndex = 0;
                    }
                    else {
                        item.pay_item.state.selectedIndex = 3;
                    }
                }
            }

            if (index <= pass_level)//进度条
            {
                item.is_full.selectedIndex = com_pass_item.Is_full_full;

            }
            else if (index > pass_level) {
                item.is_full.selectedIndex = com_pass_item.Is_full_empty;

            }
            else {
                item.is_full.selectedIndex = com_pass_item.Is_full_empty;

            }

            if (index == 0) {
                // item.state.selectedIndex = 3;
                // index++;
            }
            if (index == 1) {
                item.state.selectedIndex = 0;

            }
            else if (index == Passportrewards_list.Count) {
                item.state.selectedIndex = 2;

            }
            else {
                item.state.selectedIndex = 1;

            }
        }
    }
}
