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

namespace Edu.Common.Plugin
{
    /// <summary>
    /// 枚举帮助类
    /// </summary>
    public static class EnumHelper
    {
        /// <summary>
        /// 获取枚举列表
        /// </summary>
        /// <param name="enumType"></param>
        /// <returns></returns>
        public static List<EnumItem> EnumToList(Type enumType)
        {
            List<EnumItem> list = new List<EnumItem>();
            FieldInfo[] fieldinfos = enumType.GetFields();
            foreach (FieldInfo field in fieldinfos)
            {
                if (field.FieldType.IsEnum)
                {
                    Object[] objs = field.GetCustomAttributes(typeof(EnumFieldAttribute), false);
                    Int32.TryParse(field.GetRawConstantValue().ToString(), out int Id);
                    list.Add(new EnumItem()
                    {
                        Id = Id,
                        Name = ((EnumFieldAttribute)objs[0]).Name
                    });
                }
            }
            return list;
        }


        /// <summary>
        /// 获取枚举特性描述值
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ToName(this System.Enum obj)
        {
            if (obj == null)
            {
                return "";
            }
            try
            {
                Type type = obj.GetType();
                FieldInfo fild = type.GetField(obj.ToString());
                if (fild!=null && fild.IsDefined(typeof(EnumFieldAttribute), true))
                {
                    EnumFieldAttribute enumField = (EnumFieldAttribute)fild.GetCustomAttribute(typeof(EnumFieldAttribute), true);
                    return enumField.Name;
                }
                else
                {
                    return "";
                }
            }
            catch
            {
                return "";
            }
        }

        /// <summary>
        /// 获取枚举成员的值(this是扩展方法的标志)
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static int ToInt(this System.Enum obj)
        {
            return Convert.ToInt32(obj);
        }
    }

    /// <summary>
    /// 枚举特性标签
    /// </summary>
    public class EnumFieldAttribute : System.Attribute
    {
        /// <summary>
        /// 名称
        /// </summary>
        public string Name { get; set; }
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="name"></param>
        public EnumFieldAttribute(string name)
        {
            this.Name = name;
        }
    }

    /// <summary>
    /// 枚举项
    /// </summary>
    public class EnumItem
    {
        /// <summary>
        /// 编号
        /// </summary>
        public int Id { get; set; }

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