// 本脚本只在不存在时会生成一次。组件逻辑写在当前脚本内。已存在不会再次生成覆盖 

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

namespace NBF
{
    public partial class CommonItemList : GComponent
    {
        private List<TabItemData> _tabList = new List<TabItemData>();
        private TabItemData _currentTab;

        
        private void OnInited()
        {
            Menu.OnTabChange += ChangeTab;
            // SubMenu.OnTabChange += ChangeSubTab;
        }

        public override void Dispose()
        {
            Menu.OnTabChange -= ChangeTab;
            // SubMenu.OnTabChange -= ChangeSubTab;
            base.Dispose();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="tabItemList"></param>
        /// <param name="showAll">是否显示全部页签</param>
        /// <param name="showListTitle">是否列表页显示分类标题</param>
        public void SetData(List<TabItemData> tabItemList, bool showAll = false, bool showListTitle = true)
        {
            _tabList.Clear();
            _currentTab = null;
            // style.selectedIndex = 0; //一级菜单
            // if (tabItemList.Any(tabItem => tabItem.Children.Count > 0))
            // {
            //     style.selectedIndex = 1; //有二级菜单
            // }

            _tabList.AddRange(tabItemList);

            if (showListTitle)
            {
                foreach (var tabItemData in _tabList)
                {
                    tabItemData.TabItemDataAddListTitle();
                    if (tabItemData.Children.Count > 0)
                    {
                        foreach (var itemData in tabItemData.Children)
                        {
                            itemData.TabItemDataAddListTitle();
                        }
                    }
                }
            }

            if (showAll)
            {
                _tabList.AddAllTabItem();
            }

            Menu.SetTabs(_tabList);
        }

        private void ChangeTab(int index)
        {
            if (index < 0) return;
            var tabListData = _tabList[index];
            _currentTab = tabListData;
            // if (style.selectedIndex == 0)
            {
                //只有一级菜单
                List.SetListData(_currentTab.Items);
            }
            // else
            // {
            //     SubMenu.SetTabs(_currentTab.Children);
            // }
        }

        private void ChangeSubTab(int index)
        {
            if (index < 0) return;
            if (_currentTab == null)
            {
                return;
            }

            var subList = _currentTab.Children[index];
            List.SetListData(subList.Items);
        }
    }
}