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

namespace Siger.Middlelayer.Common.Helpers
{
    public class EnumHelper
    {
        /// <summary>
        /// 返回枚举项的描述信息。
        /// </summary>
        /// <param name="e">要获取描述信息的枚举项。</param>
        /// <returns>枚举项的描述信息,如果没有描述，则返回自身String。</returns>
        public static string GetEnumDesc(Enum e)
        {
            if (e == null)
            {
                return string.Empty;
            }
            Type enumType = e.GetType();
            DescriptionAttribute attr = null;

            // 获取枚举字段。
            FieldInfo fieldInfo = enumType.GetField(e.ToString());
            if (fieldInfo != null)
            {
                // 获取描述的属性。
                attr = Attribute.GetCustomAttribute(fieldInfo, typeof(DescriptionAttribute), false) as DescriptionAttribute;
            }

            // 返回结果
            return !string.IsNullOrEmpty(attr?.Description) ? attr.Description : e.ToString();
        }

        public static List<EnumberEntity> EnumToList<T>()
        {
            var list = new List<EnumberEntity>();

            foreach (var e in Enum.GetValues(typeof(T)))
            {
                EnumberEntity m = new EnumberEntity();
                object[] objArr = e.GetType().GetField(e.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), true);
                if (objArr.Length > 0)
                {
                    DescriptionAttribute da = objArr[0] as DescriptionAttribute;
                    m.Description = da.Description;
                }
                m.EnumValue = Convert.ToInt32(e);
                m.EnumName = e.ToString();
                list.Add(m);
            }
            return list;
        }

        public static List<EnumberEntity> EnumToList(Type type)
        {
            List<EnumberEntity> list = new List<EnumberEntity>();
            foreach (var obj in Enum.GetValues(type))
            {
                list.Add(new EnumberEntity((Enum)obj));
            }
            return list;
        }
    }

    public class EnumberEntity
    {
        /// <summary>  
        /// 枚举的描述  
        /// </summary>  
        public string Description { set; get; }

        /// <summary>  
        /// 枚举名称  
        /// </summary>  
        public string EnumName { set; get; }

        /// <summary>  
        /// 枚举对象的值  
        /// </summary>  
        public int EnumValue { set; get; }

        public EnumberEntity()
        {

        }

        public EnumberEntity(Enum um)
        {
            EnumValue = (int)Convert.ChangeType(um, typeof(int));
            EnumName = um.ToString();
            Description = EnumHelper.GetEnumDesc(um);
        }
    }
}
