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

namespace YGNT.Infrastructure.Helper
{
    public interface ITreeNode<T> where T : ITreeNode<T>
    {
        string Id { get; set; }

        string Pid { get; set; }

        List<T> Children { get; set; }
    }

    public static class TreeEx
    {
        /// <summary>
        /// 将一个树节点列表格式化 并获取当前Pid的所有节点
        /// </summary>
        /// <param name="treeNodes"></param>
        /// <param name="pid"></param>
        /// <returns></returns>
        public static List<T> FormatAndGetNodesByPid<T>(this List<T> treeNodes, string pid = "0") where T : class, ITreeNode<T>
        {
            if (!treeNodes.Any()) return treeNodes;
            var group = treeNodes.GroupBy(x => x.Pid)
                .ToDictionary(x => x.Key, s => s.ToList());

            foreach (var item in treeNodes)
            {
                if (group.ContainsKey(item.Id))
                {
                    foreach (var treeNode in group[item.Id])
                    {
                        item.Children.Add(treeNode);
                    }
                }
            }
            return group[pid];
        }
    }

}