// 本脚本只在不存在时会生成一次。已存在不会再次生成覆盖

using System.Collections.Generic;
using FairyGUI;
using UnityEngine;
using NBC;
using UIPanel = NBC.UIPanel;

namespace NBF
{
    public partial class HomePanel : UIPanel
    {
        private string[] PageNames = new[] { "HomeMainPage", "HomeActivityPage", "HomeRankPage" };

        private List<HomePageBase> _pages = new List<HomePageBase>();

        private HomePageBase _currentPage;

        private List<TabItemData> tabList = new List<TabItemData>();

        protected override void OnInit()
        {
            base.OnInit();
            foreach (var group in PageNames)
            {
                var tab = new TabItemData
                {
                    // Name = group
                };
                tabList.Add(tab);
            }


            Menu.OnTabChange += ChangeTab;
        }

        protected override void OnShow()
        {
            InputManager.Instance.On(this);
            Menu.SetTabs(tabList);
            ChangeTab(0);
        }

        #region UI事件

        [InputInvoke(InputDef.UI.Back, UIInputButtonShowMode.BottomRight)]
        private void OnBack()
        {
            Hide();
        }

        #endregion

        #region Tab切换

        private void ChangeTab(int index)
        {
            if (index < 0) return;
            Log.Info($"Change tab index={index}");
            foreach (var page in _pages)
            {
                page.Hide();
            }

            var nowPage = GetPage(index);
            if (nowPage != null)
            {
                nowPage.Show(this);
                _currentPage = nowPage;
            }
        }

        private HomePageBase GetPage(int index)
        {
            var page = _pages.Find(t => t.Page == index);
            if (page == null)
            {
                var pageName = PageNames[index];
                var pageObject = UIPackage.CreateObject(UIPackName, pageName);
                if (pageObject is HomePageBase homePage)
                {
                    Pages.AddChild(homePage);
                    _pages.Add(homePage);
                    return homePage;
                }

                return null;
            }

            return page;
        }

        #endregion


        protected override void OnHide()
        {
            InputManager.Instance.Off(this);
        }

        protected override void OnDestroy()
        {
            base.OnDestroy();
        }
    }
}