using System;
using System.Collections.Generic;
using DG.Tweening;
using FairyGUI;
using FGUI.Common_01;
using FGUI.rank;
using SGModule.Net;
using SGModule.NetKit;
using UnityEngine;

namespace ChillConnect
{
    public class RankUI : BaseUI
    {
        private RankUICtrl ctrl;
        private RankModel model;
        private com_rank_view ui;

        public btn_watchAd btn_WatchAd;

        List<UserData> users = new List<UserData>();
        List<UserData> topThreeList = new List<UserData>();
        rankType curType = rankType.hour;
        int selfRank;
        float selfBonus;
        long countDownTime;
        bool newRound;

        public RankUI(RankUICtrl ctrl) : base(ctrl)
        {
            uiName = UIConst.RankUI;
            this.ctrl = ctrl;
        }

        protected override void SetUIInfo(UIInfo uiInfo)
        {
            uiInfo.packageName = "rank";
            uiInfo.assetName = "com_rank_view";
            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 -= upTime;

            RankSystemMgr.Instance.upRewardAndRank();
            var data = SaveData.GetRankData().rankRewardData;
            if (data.Count > 0 && !HallManager.Instance.isShowRankView) {
                HallManager.Instance.isShowRankView = true;
                uiCtrlDispatcher.Dispatch(UICtrlMsg.RankRewardUI_Open);
            }
        }

        protected override void OnBind()
        {
            ui = baseUI as com_rank_view;
        }

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

            TrackKit.SendEvent(Property.rank_Event,Property.RankShow);

            HallManager.Instance.UpdateSecondEvent += upTime;
            InitView();
           if (GameHelper.GetCommonModel().PiggyBankSwitch != 1) {
                ui.pot_switch.selectedIndex = 1;
                ui.self_pot.type.selectedIndex = 2;
                ui.first_pot.type.selectedIndex = 2;
                ui.second_pot.type.selectedIndex = 2;
                ui.third_pot.type.selectedIndex = 2;
            }
        }

        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.RefreshRedDot, RefreshRed);
            GameDispatcher.Instance.AddListener(GameMsg.RefreshSaveingPot, RefreshSaveingPot);
            GameDispatcher.Instance.AddListener(GameMsg.pack_close, RefreshRed);
        }
        protected override void RemoveListener()
        {
            GameDispatcher.Instance.RemoveListener(GameMsg.RefreshRedDot, RefreshRed);
            GameDispatcher.Instance.RemoveListener(GameMsg.RefreshSaveingPot, RefreshSaveingPot);
            GameDispatcher.Instance.RemoveListener(GameMsg.pack_close, RefreshRed);
        }
        #endregion

        //初始化页面逻辑
        private void InitView()
        {
            RankSystemMgr.Instance.upRewardAndRank();
            users = RankSystemMgr.Instance.getRankData(rankType.hour);

            SaveingPotHelper.TestingClearTime();
            ui.lab_pot.text = $"{SaveData.GetSaveObject().saveingpot_ch:N}";
            showRank(curType);

            int addPoints = RankSystemMgr.Instance.getAddPointsUI();
            if (addPoints > 0)
            {
                com_add_points add_Points = ui.add_points as com_add_points;
                add_Points.visible = true;
                add_Points.lab_addPoints.text = "+" + addPoints;
                ui.t0.Play();

                DOTween.To(() => SaveData.GetRankData().selfUser.hourPoints - addPoints, x =>
                {
                    ui.self_points.lab_value.text = x.ToString();
                }, SaveData.GetRankData().selfUser.hourPoints, 1);
            }

            ui.btn_close.SetClick(CtrlCloseUI);


            ui.btn_task_tab.btn_hour.SetClick(() =>
            {
                ui.btn_task_tab.select.selectedIndex = 0;
                showRank(rankType.hour);
            });

            ui.btn_task_tab.btn_day.SetClick(() =>
            {
                ui.btn_task_tab.select.selectedIndex = 1;
                showRank(rankType.day);
            });

            ui.btn_task_tab.btn_week.SetClick(() =>
            {
                ui.btn_task_tab.select.selectedIndex = 2;
                showRank(rankType.week);
            });

            ui.btn_rule.SetClick(() =>
            {
                UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.RankRuleUI_Open);
            });

            ui.btn_pot.SetClick(() =>
            {
                UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.SaveingPotUI_Open);
            });

            var data = SaveData.GetRankData().rankRewardData;
            if (data.Count > 0)
            {
                uiCtrlDispatcher.Dispatch(UICtrlMsg.RankRewardUI_Open);
            }
        }

        private void showRank(rankType type)
        {
            // RankSystemMgr.Instance.upRewardAndRank();
            curType = type;
            users = RankSystemMgr.Instance.getRankData(type);
            topThreeList.Clear();

            for (int i = 0; i < users.Count; i++)
            {
                if (users[i].uid == GameHelper.GetLoginModel().Uid)
                {
                    selfRank = i + 1;
                    selfBonus = users[i].bonus;
                    break;
                }
            }
            if (users.Count >= 3)
            {
                topThreeList.AddRange(users.GetRange(0, 3));
                users.RemoveRange(0, 3);
            }

            ui.list_rank.itemRenderer = refreshItem;
            if (users.Count > 47)
            {
                ui.list_rank.numItems = 47;//users.Count;
            }
            else
            {
                ui.list_rank.numItems = users.Count;
            }

            showTopThree();
            showTime();
            showSelfInfo();
        }

        private void showTopThree()
        {
            for (int i = 0; i < topThreeList.Count; i++)
            {
                if (curType == rankType.hour)
                {
                    if (i == 0)
                    {
                        ui.first_points.lab_value.text = topThreeList[i].hourPoints.ToString();
                        ui.first_pot.lab_value.text = topThreeList[i].bonus.ToString();
                        var head = ui.head_1 ;
                        TextureHelper.SetAvatarToLoader(topThreeList[i].headId, head.load_avatar);
                        ui.lab_name1.text = topThreeList[i].name;
                    }
                    else if (i == 1)
                    {
                        ui.second_points.lab_value.text = topThreeList[i].hourPoints.ToString();
                        ui.second_pot.lab_value.text = topThreeList[i].bonus.ToString();
                        var head = ui.head_2 ;
                        TextureHelper.SetAvatarToLoader(topThreeList[i].headId, head.load_avatar);
                        ui.lab_name2.text = topThreeList[i].name;
                    }
                    else if (i == 2)
                    {
                        ui.third_points.lab_value.text = topThreeList[i].hourPoints.ToString();
                        ui.third_pot.lab_value.text = topThreeList[i].bonus.ToString();
                        var head = ui.head_3 ;
                        TextureHelper.SetAvatarToLoader(topThreeList[i].headId, head.load_avatar);
                        ui.lab_name3.text = topThreeList[i].name;
                    }
                }
                else if (curType == rankType.day)
                {
                    if (i == 0)
                    {
                        ui.first_points.lab_value.text = topThreeList[i].dayPoints.ToString();
                        ui.first_pot.lab_value.text = topThreeList[i].bonus.ToString();
                        var head = ui.head_1  ;
                        TextureHelper.SetAvatarToLoader(topThreeList[i].headId, head.load_avatar);
                        ui.lab_name1.text = topThreeList[i].name;
                    }
                    else if (i == 1)
                    {
                        ui.second_points.lab_value.text = topThreeList[i].dayPoints.ToString();
                        ui.second_pot.lab_value.text = topThreeList[i].bonus.ToString();
                        var head = ui.head_2 ;
                        TextureHelper.SetAvatarToLoader(topThreeList[i].headId, head.load_avatar);
                        ui.lab_name2.text = topThreeList[i].name;
                    }
                    else if (i == 2)
                    {
                        ui.third_points.lab_value.text = topThreeList[i].dayPoints.ToString();
                        ui.third_pot.lab_value.text = topThreeList[i].bonus.ToString();
                        var head = ui.head_3 ;
                        TextureHelper.SetAvatarToLoader(topThreeList[i].headId, head.load_avatar);
                        ui.lab_name3.text = topThreeList[i].name;
                    }
                }
                else if (curType == rankType.week)
                {
                    if (i == 0)
                    {
                        ui.first_points.lab_value.text = topThreeList[i].weekPoints.ToString();
                        ui.first_pot.lab_value.text = topThreeList[i].bonus.ToString();
                        var head = ui.head_1 ;
                        TextureHelper.SetAvatarToLoader(topThreeList[i].headId, head.load_avatar);
                        ui.lab_name1.text = topThreeList[i].name;
                    }
                    else if (i == 1)
                    {
                        ui.second_points.lab_value.text = topThreeList[i].weekPoints.ToString();
                        ui.second_pot.lab_value.text = topThreeList[i].bonus.ToString();
                        var head = ui.head_2 ;
                        TextureHelper.SetAvatarToLoader(topThreeList[i].headId, head.load_avatar);
                        ui.lab_name2.text = topThreeList[i].name;
                    }
                    else if (i == 2)
                    {
                        ui.third_points.lab_value.text = topThreeList[i].weekPoints.ToString();
                        ui.third_pot.lab_value.text = topThreeList[i].bonus.ToString();
                        var head = ui.head_3;
                        TextureHelper.SetAvatarToLoader(topThreeList[i].headId, head.load_avatar);
                        ui.lab_name3.text = topThreeList[i].name;
                    }
                }
            }
        }

        private void refreshItem(int index, GObject obj)
        {
            rank_item item = (rank_item)obj;
            item.lab_rank.text = (index + 4).ToString();
            item.lab_name.text = users[index].name;
            if (curType == rankType.hour)
            {
                item.lab_points.text = users[index].hourPoints.ToString();
            }
            else if (curType == rankType.day)
            {
                item.lab_points.text = users[index].dayPoints.ToString();
            }
            else if (curType == rankType.week)
            {
                item.lab_points.text = users[index].weekPoints.ToString();
            }
            item.lab_pot.text = users[index].bonus.ToString();
            if (GameHelper.GetCommonModel().PiggyBankSwitch != 1) {
                item.pot_switch.selectedIndex = 1;
            }
            var imgHead = item.btn_head;
            TextureHelper.SetAvatarToLoader(users[index].headId, imgHead.load_avatar);
        }

        private void showSelfInfo()
        {

            ui.lab_rank.text = selfRank.ToString();
            var head = ui.btn_head;
            GameHelper.SetSelfAvatar(head.load_avatar);
            if (curType == rankType.hour)
            {
                ui.self_points.lab_value.text = SaveData.GetRankData().selfUser.hourPoints.ToString();
            }
            else if (curType == rankType.day)
            {
                ui.self_points.lab_value.text = SaveData.GetRankData().selfUser.dayPoints.ToString();
            }
            else if (curType == rankType.week)
            {
                ui.self_points.lab_value.text = SaveData.GetRankData().selfUser.weekPoints.ToString();
            }
            ui.self_pot.lab_value.text = $"{selfBonus:N}";
            ui.lab_name.text = GameHelper.GetUserName();

        }

        private void showTime()
        {
            long curTime = GameHelper.GetNowTime();
            DateTime utcTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(curTime);
            DateTime curLocalTime = utcTime.ToLocalTime();
            int year = curLocalTime.Year;
            int month = curLocalTime.Month;
            int day = curLocalTime.Day;
            int hour = curLocalTime.Hour;
            int minute = curLocalTime.Minute;
            int sec = curLocalTime.Second;
            DayOfWeek dayOfWeek = curLocalTime.DayOfWeek;
            int round = hour / ConfigSystem.GetConfig<CommonModel>().HourTime;
            string curHM = $"{hour:D2}:{minute:D2}:{sec:D2}";
            if (newRound)
            {
                curHM = $"{hour:D2}:{minute:D2}:00";
            }
            DateTime dt1 = DateTime.Parse(curHM);

            if (curType == rankType.hour)
            {
                int endHour = (round + 1) * ConfigSystem.GetConfig<CommonModel>().HourTime;
                string endHM = $"{endHour:D2}:00:00";
                if (endHour >= 24)
                {
                    endHM = "23:59:59";
                }
                DateTime dt2 = DateTime.Parse(endHM);
                TimeSpan difference = dt2 - dt1;
                countDownTime = (long)difference.TotalSeconds - 1;
                ui.lab_time.text = CommonHelper.TimeFormat((int)countDownTime, CountDownType.Hour);
            }
            else if (curType == rankType.day)
            {
                string endHM = "23:59:59";
                DateTime dt2 = DateTime.Parse(endHM);
                TimeSpan difference = dt2 - dt1;
                countDownTime = (long)difference.TotalSeconds - 1;
                ui.lab_time.text = CommonHelper.TimeFormat((int)countDownTime, CountDownType.Hour);
            }
            else if (curType == rankType.week)
            {
                // 获取本周日 23:59:59
                DateTime targetTime = RankSystemMgr.Instance.GetThisWeekdayTime(curLocalTime, DayOfWeek.Sunday, 23, 59, 59);
                TimeSpan difference = targetTime - curLocalTime;
                countDownTime = (long)difference.TotalSeconds - 1;


                ui.lab_time.text = CommonHelper.TimeFormat((int)countDownTime, CountDownType.Day, "D");
            }
        }

        private void upTime()
        {
            if (countDownTime < 0)
            {
                newRound = true;
                InitView();

                return;
            }
            countDownTime--;
            if (curType == rankType.hour)
            {
                ui.lab_time.text = CommonHelper.TimeFormat((int)countDownTime, CountDownType.Hour);
            }
            else if (curType == rankType.day)
            {
                ui.lab_time.text = CommonHelper.TimeFormat((int)countDownTime, CountDownType.Hour);
            }
            else if (curType == rankType.week)
            {
                ui.lab_time.text = CommonHelper.TimeFormat((int)countDownTime, CountDownType.Day, "D");
            }
        }

        private void RefreshRed(object isShow = null)
        {
            SaveingPotHelper.TestingClearTime();
            ui.lab_pot.text = $"{SaveData.GetSaveObject().saveingpot_ch:N}";

            InitView();
        }

        private void RefreshSaveingPot(object isShow = null)
        {
            ui.lab_pot.text = $"{SaveData.GetSaveObject().saveingpot_ch:N}";
        }

    }
}
