using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace wispro.sp.entity
{
    public class EnumnDescription<T>
    {
        public string Description { get; set; }

        public T Value { get; set; }
    }

    public class EnumHelper
    {

        /// <summary>
        /// 将枚举转换成描述字典集合
        /// </summary>
        /// <typeparam name="T">枚举类型</typeparam>
        /// <returns></returns>
        public static List<EnumnDescription<T>> getEnumDescriptionDic<T>()
        {
            List<EnumnDescription<T>> resultList = new List<EnumnDescription<T>>();
            Type type = typeof(T);
            var strList = Enum.GetNames(typeof(T)).ToList();
            foreach (string key in strList)
            {
                var obj = (T)Enum.Parse(type, key);
                FieldInfo field = obj.GetType().GetField(obj.ToString());

                DescriptionAttribute att = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute), false) as DescriptionAttribute;

                if (att == null)
                {
                    resultList.Add(new EnumnDescription<T>() { Description = key, Value = obj });
                }
                else
                {
                    resultList.Add(new EnumnDescription<T>() { Description = att.Description, Value = obj });

                }
            }

            return resultList;

        }

        public static string GetDescription<T>(T obj)
        {
            Type type = typeof(T);
            FieldInfo field = obj.GetType().GetField(obj.ToString());
            DescriptionAttribute att = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute), false) as DescriptionAttribute;

            if (att == null)
            {
                return obj.ToString();
            }
            else
            {
                return att.Description;
            }
        }

    }
}
