using Hotline.Share.Attributes;
using Hotline.Share.Enums.Order;
using System.ComponentModel;
using System.Reflection;

namespace Hotline.Share.Tools;
public static class EnumExtensions
{
    /// <summary>
    /// 获取枚举项上的<see cref="FileExtensionAttribute"/>特性的文字描述
    /// </summary>
    /// <param name="value">枚举</param>
    /// <returns>属性值</returns>
    public static string GetFileExtension(this Enum value)
    {
        var type = value.GetType();
        var member = type.GetMember(value.ToString()).FirstOrDefault();
        var desc = member?.GetAttribute<FileExtensionAttribute>();
        if (desc != null)
        {
            return desc.FileExtension;
        }
        return string.Empty;
    }

    /// <summary>
    /// 获取枚举项上的<see cref="ContentTypeAttribute"/>特性的文字描述
    /// </summary>
    /// <param name="value">枚举</param>
    /// <returns>属性值</returns>
    public static string GetContentType(this Enum value)
    {
        var type = value.GetType();
        var member = type.GetMember(value.ToString()).FirstOrDefault();
        var desc = member?.GetAttribute<ContentTypeAttribute>();
        if (desc != null)
        {
            return desc.ContentType;
        }
        return string.Empty;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <typeparam name="TEnum"></typeparam>
    /// <returns></returns>
    public static List<KeyValuePair<int, string>> GetEnumKeyValueList<TEnum>() where TEnum : Enum
    {
        // 按照枚举定义的顺序获取键值对
        return typeof(TEnum)
             .GetFields()
             .Where(f => f.IsLiteral) // 过滤出枚举字段
             .Select(f =>
             {
                 var value = (int)f.GetValue(null); // 枚举值
                 var description = f.GetCustomAttribute<DescriptionAttribute>()?.Description ?? f.Name; // Description 属性值
                 return new KeyValuePair<int, string>(value, description);
             })
             .ToList();
    }
}
