using System.Collections.Generic;
using System.Linq;

namespace NBF
{
    public static class TabItemDataExtensions
    {
        /// <summary>
        /// 为TabItemData列表添加"全部"选项卡
        /// </summary>
        /// <param name="tabItems">原始选项卡列表</param>
        /// <returns>包含"全部"选项卡的新列表</returns>
        public static void AddAllTabItem(this List<TabItemData> tabItems)
        {
            //判断是否存在二级目录，有二级目录则只在二级目录有"全部"选项卡
            if (tabItems.Any(tabItem => tabItem.Children.Count > 0))
            {
                foreach (var tabItemData in tabItems)
                {
                    if (tabItemData.Children.Count > 0)
                    {
                        var allTab = new TabItemData
                        {
                            Id = 0,
                            Key = "All",
                            Icon = "All",
                            IsAll = true,
                            Items = GetAllItemsFromTabs(tabItemData.Children)
                        };
                        tabItemData.Children.Insert(0, allTab);
                    }
                }
            }
            else
            {
                var allTab = new TabItemData
                {
                    Id = 0,
                    Key = "All",
                    Icon = "All",
                    IsAll = true,
                    Items = GetAllItemsFromTabs(tabItems)
                };
                tabItems.Insert(0, allTab);
            }
        }

        /// <summary>
        /// 递归获取所有选项卡中的项目（去重）
        /// </summary>
        private static List<object> GetAllItemsFromTabs(List<TabItemData> tabs)
        {
            var allItems = new List<object>();

            foreach (var tab in tabs)
            {
                // if (addListTitle)
                // {
                //     allItems.Add(new ClassifyListTitleData()
                //     {
                //         Title = tab.Key
                //     });
                // }
                
                // 添加当前选项卡的项目
                if (tab.Items != null)
                {
                    allItems.AddRange(tab.Items);
                }
            }

            // 去重处理（基于引用相等，如果需要基于内容去重需要重写Equals方法）
            return allItems.Distinct().ToList();
        }

        public static void TabItemDataAddListTitle(this TabItemData tabItem)
        {
            if (tabItem.Items == null || tabItem.Items.Count < 1) return;
            var hasListTitle = tabItem.Items.OfType<ClassifyListTitleData>().Any();
            if (!hasListTitle)
            {
                tabItem.Items.Insert(0, new ClassifyListTitleData()
                {
                    Title = tabItem.Key
                });
            }
        }
    }
}