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

namespace QYZH.InteractiveMagazine.Common.Extensions
{
    /// <summary>
    /// 枚举扩展方法
    /// </summary>
    public static class EnumExtension
    {
        /// <summary>
        /// 获取枚举的DescriptionAttribute描述
        /// </summary>
        /// <typeparam name="T">枚举类型</typeparam>
        /// <param name="enumValue">枚举值</param>
        /// <returns>描述文本,如果没有DescriptionAttribute则返回枚举名称</returns>
        public static string GetDescription<T>(this T enumValue) where T : Enum
        {
            System.Reflection.FieldInfo? field = enumValue.GetType().GetField(enumValue.ToString());
            if (field == null)
            {
                return enumValue.ToString();
            }

            var attribute = (DescriptionAttribute?)Attribute.GetCustomAttribute(
                field, typeof(DescriptionAttribute));

            return attribute?.Description ?? enumValue.ToString();
        }

        /// <summary>
        /// 获取枚举名称
        /// </summary>
        /// <typeparam name="T">枚举类型</typeparam>
        /// <param name="enumValue">枚举值</param>
        /// <returns>枚举名称</returns>
        public static string GetName<T>(this T enumValue) where T : Enum
        {
            return enumValue.ToString();
        }

        /// <summary>
        /// 获取所有枚举名称列表
        /// </summary>
        /// <typeparam name="T">枚举类型</typeparam>
        /// <returns>枚举名称列表</returns>
        public static List<string> GetNames<T>() where T : Enum
        {
            return Enum.GetNames(typeof(T)).ToList();
        }

        /// <summary>
        /// 获取所有枚举描述列表
        /// </summary>
        /// <typeparam name="T">枚举类型</typeparam>
        /// <returns>枚举描述列表</returns>
        public static List<string> GetDescriptions<T>() where T : Enum
        {
            return Enum.GetValues(typeof(T))
                .Cast<T>()
                .Select(e => e.GetDescription())
                .ToList();
        }

        /// <summary>
        /// 将枚举转换为字典(名称,值)
        /// </summary>
        /// <typeparam name="T">枚举类型</typeparam>
        /// <returns>枚举字典</returns>
        public static Dictionary<string, int> ToDictionary<T>() where T : Enum
        {
            return Enum.GetValues(typeof(T))
                .Cast<T>()
                .ToDictionary(e => e.GetDescription(), e => Convert.ToInt32(e));
        }
    }
}
