using System;
using System.Collections.Generic;
using DG.Tweening;
using FairyGUI;
using FGUI.P14_PassView;
using IgnoreOPS;
using Spine.Unity;
using UnityEngine;

namespace ChillConnect
{
    public class PassViewUI : BaseUI
    {
        private PassViewUICtrl ctrl;
        private PassViewModel model;
        private 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;
        private Action closeCallback;


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

        protected override void SetUIInfo(UIInfo uiInfo)
        {
            uiInfo.packageName = "P14_PassView";
            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 com_pass_view;
        }

        protected override void OnOpenBefore(object args)
        {
            if (Screen.safeArea.y != 0)
            {
                ui.bg.y += 68;
                ui.group_top.y += 68;
            }

            var anim_paly = FXManager.Instance.SetFx<SkeletonAnimation>(ui.gold.GetChild("gold_anim") as GGraph, Fx_Type.fx_coin, ref closeCallback);
            anim_paly.state.SetAnimation(0, "animation", true);

            if (GameHelper.GetGameday() != DateTime.Now.Day)
            {
                PlayerPrefs.SetInt("_time", 0);
                SaveData.GetSaveObject().time_task_record = new List<int>();
                GameHelper.SetGameday();
            }

            HallManager.Instance.UpdateSecondEvent += upData;
            InitView();
            ui.btn_tips.SetClick(() =>
            {
                ui.t0.Play();
                tips_time = 0;
            });
        }
        private int tips_time = 0;
        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, () =>
                {
                    int gold = 0;
                    GameHelper.ShowTips("Purchase successful");

                    List<Passportrewards> Passportrewards_list = ConfigSystem.GetConfig<PassportrewardsModel>().DataList;
                    for (int i = 0; i < Passportrewards_list.Count; i++)
                    {
                        if (GameHelper.GetBattleLv() > i || (GameHelper.GetGameExp() >= Passportrewards_list[Passportrewards_list.Count - 1].Eliminating_quantity))
                        {
                            if (Passportrewards_list[i].Paid_rewards_type == 0) gold += Passportrewards_list[i].Paid_rewards_num;
                            SaveData.GetSaveObject().battle_pass_paylist.Add(i + 1);
                        }
                        else break;
                    }


                    GetReward(gold,-1);


                    ui.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<PassingTaskModel>().DataList;
            Durationtasks_list = ConfigSystem.GetConfig<DurationtasksModel>().DataList;
            Passportrewards_list = ConfigSystem.GetConfig<PassportrewardsModel>().DataList;
            setPassCom();

            gotoItem();
        }

        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.t0.Play();
                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.pass_list.itemRenderer = battle_itemRender;
            ui.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://P14_PassView/master_gold01";
            else if (urltype == 4) loader.url = "ui://P14_PassView/master_gold02";
            else if (urltype == 1) loader.url = "ui://Common_01/spin_remove";
            else if (urltype == 2) loader.url = "ui://Common_01/spin_undo";
            else if (urltype == 3) loader.url = "ui://Common_01/spin_refresh";
        }
        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.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("ani_node"));

                        // 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.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("gold_anim"));

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

            rewardData.AddReward(rewardSingleData);
            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(startNum, 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.pass_list.ScrollToView(getRewardIndex - 1);
            }
        }

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

            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))//领取过
                    {
                        item.free_item.state.selectedIndex = 2;
                        item.free_item.ani_node.visible = false;
                        item.free_item.SetClick(() => { });
                    }
                    else
                    {
                        if (getRewardIndex < 0) getRewardIndex = index;

                        item.free_item.state.selectedIndex = 1;
                        item.free_item.btn_claim.SetClick(() =>
                        {
                            // fx_pass.state.SetAnimation(0, "lingqu", false);
                            // fx_pass.state.Complete += (a) => {
                            //     item.free_item.ani_node.visible = false;
                            // };

                            freelist.Add(index);
                            SaveData.saveDataFunc();
                            GameHelper.ShowTips("Successfully claimed");
                            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(() => { });
                    }
                    else
                    {
                        if (SaveData.GetSaveObject().is_get_battlepass)
                        {
                            if (getRewardIndex < 0) getRewardIndex = index;
                            item.pay_item.state.selectedIndex = 1;
                            item.pay_item.btn_claim.SetClick(() =>
                            {
                                // fx_pass2.state.SetAnimation(0, "lingqu", false);
                                // fx_pass2.state.Complete += (a) => {
                                //     // fx_pass.state.SetAnimation(0, "lingqudaiji", true);
                                //     item.pay_item.ani_node.visible = false;
                                // };

                                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("Successfully claimed");

                            });
                        }
                        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("Receiving level not reached");
                    });
                    item.pay_item.SetClick(() =>
                    {
                        if (SaveData.GetSaveObject().is_get_battlepass)
                        {
                            GameHelper.ShowTips("Receiving level not reached");
                        }
                        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)//进度条
            //             {
            //
            //             }
            //             else if (index >= pass_level)
            //             {
            //                 item.is_full.selectedIndex = 2;
            //
            //             }
            //             else
            //             {
            //                 item.is_full.selectedIndex = 2;
            //
            //             }

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

                if (pass_level > 0)
                {
                    item.progress_0_top.height = top_progress;
            

                    if (((float)(GameHelper.GetGameExp() - Passportrewards_list[0].Eliminating_quantity) / (Passportrewards_list[1].Eliminating_quantity - Passportrewards_list[0].Eliminating_quantity)) > 0.5)
                    {
                        item.progress_0_down.height = down_progress;
                    }
                    else
                    {

                        item.progress_0_down.height = (float)(GameHelper.GetGameExp() - Passportrewards_list[0].Eliminating_quantity) / (Passportrewards_list[1].Eliminating_quantity - Passportrewards_list[0].Eliminating_quantity) * 2 * down_progress;
                    }

                }
                else
                {
                    item.progress_0_top.height = (float)GameHelper.GetGameExp() / Passportrewards_list[0].Eliminating_quantity * top_progress;
                    item.progress_0_down.height = 0;

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


                if (((float)(GameHelper.GetGameExp() - Passportrewards_list[index - 2].Eliminating_quantity) / (Passportrewards_list[index - 1].Eliminating_quantity - Passportrewards_list[index - 2].Eliminating_quantity)) > 0.5)
                {
                    float height = (((float)(GameHelper.GetGameExp() - Passportrewards_list[index - 2].Eliminating_quantity) / (Passportrewards_list[index - 1].Eliminating_quantity - Passportrewards_list[index - 2].Eliminating_quantity)) - 0.5f) * 2 * top_progress;
                    if (height > top_progress)
                    {
                        height = top_progress;
                        
                    }
                    item.progress_2_top.height = height;
                }
                else item.progress_2_top.height = 0;


            }
            else
            {
                item.state.selectedIndex = 1;

                if (pass_level >= index)
                {

                    item.progress_1_top.height = top_progress;
                }
                else
                {
                    if (pass_level == (index - 1))
                    {

                        if (((float)(GameHelper.GetGameExp() - Passportrewards_list[index - 2].Eliminating_quantity) / (Passportrewards_list[index - 1].Eliminating_quantity - Passportrewards_list[index - 2].Eliminating_quantity)) > 0.5)
                        {

                            float height = (((float)(GameHelper.GetGameExp() - Passportrewards_list[index - 2].Eliminating_quantity) / (Passportrewards_list[index - 1].Eliminating_quantity - Passportrewards_list[index - 2].Eliminating_quantity)) - 0.5f) * 2 * top_progress;
                            if (height > top_progress) height = top_progress;
                            item.progress_1_top.height = height;
                        }
                        else item.progress_1_top.height = 0;


                    }
                    else
                    {
                        item.progress_1_top.height = 0;
                    }
                }

                if (pass_level == index)
                {
                    if (((float)(GameHelper.GetGameExp() - Passportrewards_list[index - 1].Eliminating_quantity) / (Passportrewards_list[index].Eliminating_quantity - Passportrewards_list[index - 1].Eliminating_quantity)) <= 0.5)
                    {
                        float height = (float)(GameHelper.GetGameExp() - Passportrewards_list[index - 1].Eliminating_quantity) / (Passportrewards_list[index].Eliminating_quantity - Passportrewards_list[index - 1].Eliminating_quantity) * 2 * down_progress;
                        if (height > down_progress)
                        {
                            height = down_progress;
                        }
                        item.progress_1_down.height = height;
                    }
                    else
                    {
                        item.progress_1_down.height = down_progress;
                    }

                }
                else
                {
                    if (pass_level > index)
                    {
                        item.progress_1_down.height = down_progress;
                    }
                    else item.progress_1_down.height = 0;
                }
            }
        }
        private int top_progress=105;
        private int down_progress=116;
    }
}
