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

namespace YGNT.Infrastructure.Helper
{
    /// <summary>
    /// 树节点帮助
    /// </summary>
    public class TreeNodeHelper// where T : TreeNodeHelper<T>
    {
        /// <summary>
        /// 初始化一个基本的树节点
        /// </summary>
        public TreeNodeHelper()
        {
            Children = new List<TreeNodeHelper>();
        }

        /// <summary>
        /// 名称
        /// </summary>
        public string Name { get; set; }
        /// <summary>
        /// 主键Id
        /// </summary>
        public string Id { get; set; }
        /// <summary>
        /// 父Id
        /// </summary>
        public string Pid { get; set; }
        /// <summary>
        /// 子节点
        /// </summary>
        public List<TreeNodeHelper> Children { get; set; }
    }

    /// <summary>
    /// 树节点扩展
    /// </summary>
    public static class TreeNodeExHelper
    {
        /// <summary>
        /// 将一个树节点列表格式化 并获取当前Pid的所有节点
        /// </summary>
        /// <param name="treeNodes"></param>
        /// <param name="pid"></param>
        /// <returns></returns>
        public static List<T> ToTree<T>(this List<T> treeNodes, string pid = "0")// where T : TreeNodeHelper<T>
        {
            if (!treeNodes.Any())
                return treeNodes;

            ////https://www.cnblogs.com/lao-tang/p/11780266.html
            //Type aType = treeNodes.GetType();
            //var dataParameter = Expression.Parameter(aType, "x");    // 定义 data => 且data类型
            //var expar = DynamicExpressionParser.ParseLambda(new[] { dataParameter }, typeof(bool), "data.Age > 5 && data.Name == \"小哥哥\"");

            //var group = treeNodes.GroupBy(x => x.Pid)
            //    .ToDictionary(x => x.Key, s => s.ToList());

            Dictionary<string, List<T>> group = new Dictionary<string, List<T>>();
            foreach (dynamic item in treeNodes)
            {
                if (item.Id == item.Pid)
                    throw new Exception("id和pid相同，无限循环引用");
                if (item.Id == "0")
                    throw new Exception("id不能为0，不合法的数据");

                if (group.ContainsKey(item.Pid))
                    group[item.Pid].Add(item);
                else
                    group.Add(item.Pid, new List<T>() { item });
            }

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

}
