using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
using System.Text;

namespace Performance.Infrastructure
{
    public class EnumItem
    {
        public string Name { get; set; }
        public int Value { get; set; }
        public string Description { get; set; }
    }
    /// <summary>
    /// 枚举类型操作公共类。
    /// </summary>
    public static class EnumHelper
    {
        /// <summary>
        /// 获取枚举所有成员名称。
        /// </summary>
        /// <typeparam name="T">枚举类型</typeparam>
        public static string[] GetNames<T>()
        {
            return Enum.GetNames(typeof(T));
        }

        /// <summary>
        /// 返回指定枚举类型的指定值的描述。
        /// </summary>
        /// <param name="t">枚举类型</param>
        /// <param name="v">枚举值</param>
        /// <returns></returns>
        public static string GetDescription(Enum value)
        {
            try
            {
                Type type = value.GetType();
                FieldInfo field = type.GetField(value.ToString());
                DescriptionAttribute[] attributes = (DescriptionAttribute[])field.GetCustomAttributes(typeof(DescriptionAttribute), false);
                return (attributes.Length > 0) ? attributes[0].Description : string.Empty;
            }
            catch
            {
                return string.Empty;
            }
        }

        /// <summary>
        /// 获取疾病或药品的Type和Value
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static List<EnumItem> GetItems<T>()
        {
            var result = new List<EnumItem>();
            Type t = typeof(T);
            Array arrays = Enum.GetValues(t);
            for (int i = 0; i < arrays.LongLength; i++)
            {
                object item = arrays.GetValue(i);
                FieldInfo fieldInfo = item.GetType().GetField(item.ToString());
                object[] attribArray = fieldInfo.GetCustomAttributes(false);
                if (attribArray == null || attribArray.Length == 0)
                {
                    result.Add(new EnumItem { Name = item.ToString(), Value = Convert.ToInt32(item), Description = item.ToString() });
                }
                else
                {
                    DescriptionAttribute attrib = (DescriptionAttribute)attribArray[0];
                    result.Add(new EnumItem { Name = item.ToString(), Value = Convert.ToInt32(item), Description = attrib.Description });
                }
            }
            return result;
        }
    }
}
