using System.Collections.Generic;
using UnityEngine;
using FairyGUI;
using FGUI.ZM_Tasks_13;
using DG.Tweening;
using System;
using FGUI.Common_01;
using IgnoreOPS;

namespace ChillConnect
{
    public class NewTaskUI : BaseUI
    {
        private NewTaskUICtrl ctrl;
        private NewTaskModel model;
        private FGUI.ZM_Tasks_13.com_taskView ui;
        List<PassingTask> passing_list = new List<PassingTask>();
        List<Durationtasks> Durationtasks_list = new List<Durationtasks>();
        List<ADTask> ADTaskrewards_list = new List<ADTask>();
        private Vector2 start_pos;
        private int reward_number;
        private int task_id = 0;
        private List<int> recored_list;
        private List<int> time_recored_list;
        private List<int> ad_recored_list;

        private int reward_type = 0;


        public NewTaskUI(NewTaskUICtrl ctrl) : base(ctrl)
        {
            uiName = UIConst.NewTaskUI;
            this.ctrl = ctrl;
        }

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

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

        protected override void OnClose()
        {
            GameHelper.showGameUI = true;


        }

        protected override void OnBind()
        {
            ui = baseUI as FGUI.ZM_Tasks_13.com_taskView;
        }

        protected override void OnOpenBefore(object args)
        {
            if (Screen.safeArea.y != 0)
            {
                ui.gold.y += Screen.safeArea.y;
            }
            CommonHelper.CheckAdTimes();




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

        private void SortListBasedOnIsLevel(int isLevel)
        {
            if (isLevel == 1)
            {
                // ui.title.text = "Level Tasks";
                ui.com_tab.select.selectedIndex = 0;
                SortTaskList();
            }
            else if (isLevel == 2)
            {
                // ui.title.text = "Time Tasks";
                ui.com_tab.select.selectedIndex = 1;
                sortTimeList();
            }
            else
            {
                ui.com_tab.select.selectedIndex = 2;
                sortADNumList();
            }
            SetBtnVisible(isLevel);
        }

        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.GetTaskReward, getRewardSuccess);
        }
        protected override void RemoveListener()
        {
            GameDispatcher.Instance.RemoveListener(GameMsg.GetTaskReward, getRewardSuccess);
        }
        #endregion


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

            bool is_red_1 = SaveData.passtaskred();
            bool is_red_2 = SaveData.timetaskred();
            bool is_red_3 = SaveData.AdTaskred();

            passing_list = ConfigSystem.GetConfig<PassingTaskModel>().DataList;
            Durationtasks_list = ConfigSystem.GetConfig<DurationtasksModel>().DataList;
            ADTaskrewards_list = ConfigSystem.GetConfig<ADTaskModel>().DataList;

            int sortLevel;
            if (!is_red_2)
            {
                sortLevel = is_red_3 ? 3 : (is_red_1 ? 1 : 2);
            }
            else
            {
                sortLevel = 2;
            }
            SortListBasedOnIsLevel(sortLevel);
            Debug.Log($"[is_red_3]  is_red_3======={is_red_3}");
            ui.com_tab.red_1.visible = is_red_1;
            ui.com_tab.red_2.visible = is_red_2;
            ui.com_tab.red_3.visible = is_red_3;

            ui.com_tab.btn_pass.SetClick(() =>
            {
                ui.com_tab.select.selectedIndex = 0;
                SortTaskList();
                SetBtnVisible(1);
                ui.list.visible = true;
            });
            ui.com_tab.btn_elimina.SetClick(() =>
            {
                ui.com_tab.select.selectedIndex =1;

                sortTimeList();
                SetBtnVisible(2);
                ui.list.visible = true;
            });

            ui.com_tab.btn_time.SetClick(() =>
            {
                ui.com_tab.select.selectedIndex = 2;

                sortADNumList();
                SetBtnVisible(3);
                ui.list.visible = true;
            });

            ui.btn_close.SetClick(() => { UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.NewTaskUI_Close); });
        }

        private void SetBtnVisible(int type)
        {
            ui.com_tab.btn_pass.visible = type != 1;
            ui.com_tab.btn_elimina.visible = type != 2;
            ui.com_tab.btn_time.visible = type != 3;
        }


        private void RefreshGold(decimal coin = -1)
        {
            float times = 0.5f;
            if (coin < 0)
            {
                times = 1f;
                coin = DataMgr.Coin.Value ;
            }
            var btnCoin = ui.gold as com_gold;


            CommonHelper.ShowNumAnim(btnCoin.text_gold, coin, 101, times);
        }

        void SortTaskList()
        {
            // recored_list = NewTaskModel.getTaskRecord();
            recored_list = SaveData.GetSaveObject().pass_task_record;
            List<PassingTask> templist = new List<PassingTask>();
            passing_list.Sort((x, y) => x.id - y.id);
            for (int i = 0; i < passing_list.Count; i++)
            {
                if (recored_list.Contains(passing_list[i].id))
                {
                    passing_list[i].is_get = true;
                    templist.Add(passing_list[i]);
                    passing_list.Remove(passing_list[i]);
                    i--;
                }
            }
            passing_list.AddRange(templist);

            ui.list.itemRenderer = passingTaskrRender;
            ui.list.numItems = passing_list.Count;
            ui.com_tab.red_1.visible = SaveData.passtaskred();
            GameDispatcher.Instance.Dispatch(GameMsg.RefreshRedDot);

        }
        void sortTimeList()
        {
            //time_recored_list = NewTaskModel.getTimeRecord();
            time_recored_list = SaveData.GetSaveObject().time_task_record;
            List<Durationtasks> templist = new List<Durationtasks>();
            Durationtasks_list.Sort((x, y) => x.id - y.id);

            for (int i = 0; i < Durationtasks_list.Count; i++)
            {
                if (time_recored_list.Contains(Durationtasks_list[i].id))
                {
                    Durationtasks_list[i].is_get = true;
                    templist.Add(Durationtasks_list[i]);
                    Durationtasks_list.Remove(Durationtasks_list[i]);
                    i--;
                }
                else
                {
                    Durationtasks_list[i].is_get = false;

                }
            }
            Durationtasks_list.AddRange(templist);

            ui.list.itemRenderer = durationRender;
            ui.list.numItems = Durationtasks_list.Count;
            ui.com_tab.red_2.visible = SaveData.timetaskred();
            GameDispatcher.Instance.Dispatch(GameMsg.RefreshRedDot);

        }

        void sortADNumList()
        {
            ad_recored_list = SaveData.GetSaveObject().ad_task_record;
            List<ADTask> templist = new List<ADTask>();

            ADTaskrewards_list.Sort((x, y) => x.id - y.id);
            for (int i = 0; i < ADTaskrewards_list.Count; i++)
            {
                if (ad_recored_list.Contains(ADTaskrewards_list[i].id))
                {
                    ADTaskrewards_list[i].is_get = true;
                    templist.Add(ADTaskrewards_list[i]);
                    ADTaskrewards_list.Remove(ADTaskrewards_list[i]);
                    i--;
                }
                else
                {
                    ADTaskrewards_list[i].is_get = false;
                }
            }
            ADTaskrewards_list.AddRange(templist);
            ui.list.itemRenderer = ADTaskRender;
            ui.list.numItems = ADTaskrewards_list.Count;
            ui.com_tab.red_3.visible = SaveData.AdTaskred();
            GameDispatcher.Instance.Dispatch(GameMsg.RefreshRedDot);
        }

        void ADTaskRender(int index, GObject obj)
        {
            com_task_item item = (com_task_item)obj;
            item.content_text.text = ADTaskrewards_list[index].text_read;
            item.number_text.text = "x" + ADTaskrewards_list[index].reward_num;
            item.progress.max = ADTaskrewards_list[index].tol_num;

            if (DataMgr.VideoWatchCount.Value < ADTaskrewards_list[index].tol_num)
            {
                item.progress_text.text = DataMgr.VideoWatchCount + "/" + ADTaskrewards_list[index].tol_num;
                item.progress.value = DataMgr.VideoWatchCount.Value;

                item.btn_claim.state.selectedIndex = 1;
                item.btn_claim.title = "To complete";
                item.btn_claim.SetClick(() =>
                {

                });
            }
            else
            {
                item.progress_text.text = ADTaskrewards_list[index].tol_num + "/" + ADTaskrewards_list[index].tol_num;
                item.progress.value = DataMgr.VideoWatchCount.Value;
                if (!ADTaskrewards_list[index].is_get)
                {
                    item.btn_claim.state.selectedIndex = 0;
                    item.btn_claim.SetClick(() =>
                    {
                        item.btn_claim.SetClick(() =>
                        {
                        });
                        start_pos = GameHelper.GetUICenterPosition(item.gold_icon);
                        reward_number = ADTaskrewards_list[index].reward_num;
                        task_id = ADTaskrewards_list[index].id;
                        reward_type = 3;
                        var rewarddata = new ScrollItemData();
                        rewarddata.rewards = ADTaskrewards_list[index].reward_num;
                        rewarddata.Boost = ADTaskrewards_list[index].Boost;
                        rewarddata.weight = ADTaskrewards_list[index].weight;
                        UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.GetTaskRewardUI_Open, rewarddata);
                    });
                    item.btn_claim.title = "Collect";
                }
                else
                {
                    item.btn_claim.title = "Collected";
                    item.btn_claim.SetClick(() =>
                    {

                    });
                    item.btn_claim.state.selectedIndex = 1;
                }

            }
        }
        void passingTaskrRender(int index, GObject obj)
        {
            com_task_item item = (com_task_item)obj;
            item.content_text.text = passing_list[index].text_read;
            item.number_text.text = "x" + passing_list[index].reward_num;
            item.progress.max = passing_list[index].tol_num;
            if ((GameHelper.GetLevel() - 1) < passing_list[index].tol_num)
            {
                item.progress_text.text = GameHelper.GetLevel() - 1 + "/" + passing_list[index].tol_num;
                item.progress.value = GameHelper.GetLevel() - 1;

                item.btn_claim.state.selectedIndex = 1;
                item.btn_claim.title = "To complete";
                item.btn_claim.SetClick(() =>
                {

                });
            }
            else
            {
                item.progress_text.text = passing_list[index].tol_num + "/" + passing_list[index].tol_num;
                item.progress.value = GameHelper.GetLevel() - 1;
                if (!passing_list[index].is_get)
                {
                    item.btn_claim.state.selectedIndex = 0;
                    item.btn_claim.SetClick(() =>
                    {
                        item.btn_claim.SetClick(() =>
                        {
                        });
                        start_pos = GameHelper.GetUICenterPosition(item.gold_icon);
                        reward_number = passing_list[index].reward_num;
                        task_id = passing_list[index].id;
                        reward_type = 1;
                        var rewarddata = new ScrollItemData();
                        rewarddata.rewards = passing_list[index].reward_num;
                        rewarddata.Boost = passing_list[index].Boost;
                        rewarddata.weight = passing_list[index].weight;
                        UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.GetTaskRewardUI_Open, rewarddata);
                    });
                    item.btn_claim.title = "Collect";
                }
                else
                {
                    item.btn_claim.title = "Collected";
                    item.btn_claim.SetClick(() =>
                    {

                    });
                    item.btn_claim.state.selectedIndex = 1;
                }

            }
        }

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

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

            rewardData.AddReward(rewardSingleData);
            rewardData.displayType = RewardDisplayType.RewardFly | RewardDisplayType.ValueChange;
            rewardData.AddCompleted(success =>
            {
                if (success)
                {
                    RefreshGold(awardNum);
                }
            });
            GameDispatcher.Instance.Dispatch(GameMsg.GetReward, rewardData);
        }

        void getRewardSuccess(object a = null)
        {

            Debug.Log($"getRewardSuccess==============={a}");
            if (a == null) return;
            var isMult = reward_number <= (int)a;
            reward_number = (int)a;

            GetReward(reward_number);

            if (reward_type == 1)
            {
                recored_list.Add(task_id);
                SaveData.saveDataFunc();
            }
            else if (reward_type == 2)
            {
                time_recored_list.Add(task_id);
                SaveData.saveDataFunc();
            }
            else if (reward_type == 3)
            {
                ad_recored_list.Add(task_id);
                SaveData.saveDataFunc();
            }

            DOVirtual.DelayedCall(1, () =>
            {
                if (reward_type == 3 || isMult)
                {
                    sortADNumList();
                }

                if (reward_type == 1)
                {
                    SortTaskList();
                }
                else if (reward_type == 2)
                {
                    sortTimeList();
                }
                // else if (reward_type == 3)
                // {
                //     sortADNumList();
                // }
                // GameHelper.AddInterAdnumber();
            });
        }

        void durationRender(int index, GObject obj)
        {
            com_task_item item = (com_task_item)obj;

            item.content_text.text = Durationtasks_list[index].text_read;
            item.number_text.text = "x" + Durationtasks_list[index].reward_num;
            item.progress.max = Durationtasks_list[index].tol_num;
            if ((GameHelper.GetGameTime() / 60) < Durationtasks_list[index].tol_num)
            {
                item.progress_text.text = Math.Round((float)GameHelper.GetGameTime() / 60, 2) + "/" + Durationtasks_list[index].tol_num;
                item.progress.value = Math.Round((float)GameHelper.GetGameTime() / 60, 2);
                item.btn_claim.state.selectedIndex = 1;
                item.btn_claim.SetClick(() =>
                {

                });
                item.btn_claim.title = "To complete";
            }
            else
            {
                item.progress_text.text = Durationtasks_list[index].tol_num + "/" + Durationtasks_list[index].tol_num;
                item.progress.value = Durationtasks_list[index].tol_num;
                if (!Durationtasks_list[index].is_get)
                {
                    item.btn_claim.state.selectedIndex = 0;
                    item.btn_claim.SetClick(() =>
                    {
                        item.btn_claim.SetClick(() =>
                        {
                        });

                        start_pos = GameHelper.GetUICenterPosition(item.gold_icon);
                        reward_number = Durationtasks_list[index].reward_num;
                        task_id = Durationtasks_list[index].id;
                        reward_type = 2;
                        var rewarddata = new ScrollItemData();
                        rewarddata.rewards = Durationtasks_list[index].reward_num;
                        rewarddata.Boost = Durationtasks_list[index].Boost;
                        rewarddata.weight = Durationtasks_list[index].weight;
                        UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.GetTaskRewardUI_Open, rewarddata);
                    });
                    item.btn_claim.title = "Collect";
                }
                else
                {
                    item.btn_claim.title = "Collected";
                    item.btn_claim.SetClick(() =>
                    {

                    });
                    item.btn_claim.state.selectedIndex = 1;
                }

            }
        }

    }

    public class ScrollItemData
    {
        public int rewards;
        public int[] Boost; // 比如 "x3"
        public int[] weight;   // 权重
    }
}
