using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace Check.Main.Common
{
    /// 
    /// 一个自定义的类型转换器,用于让PropertyGrid等控件显示枚举成员的Description特性,而不是成员名。
    /// 
    public class EnumDescriptionTypeConverter : EnumConverter
    {
        /// 
        /// 构造函数,传入枚举类型。
        /// 
        /// 要进行转换的枚举类型。
        public EnumDescriptionTypeConverter(Type type) : base(type)
        {
        }
        /// 
        /// 重写此方法,将枚举值转换为其描述文本。
        /// 这是从 "数据" -> "UI显示" 的过程。
        /// 
        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
        {
            // 如果目标类型是字符串,并且我们有一个有效的枚举值
            if (destinationType == typeof(string) && value != null)
            {
                // 获取枚举值的字段信息
                FieldInfo fi = value.GetType().GetField(value.ToString());
                if (fi != null)
                {
                    // 查找该字段上的DescriptionAttribute
                    var attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
                    // 如果找到了Description特性,就返回它的描述文本;否则,返回基类的默认行为(即成员名)
                    return ((attributes.Length > 0) && (!String.IsNullOrEmpty(attributes[0].Description)))
                           ? attributes[0].Description
                           : value.ToString();
                }
            }
            // 对于其他所有情况,使用基类的默认转换逻辑
            return base.ConvertTo(context, culture, value, destinationType);
        }
        /// 
        /// 重写此方法,将描述文本转换回其对应的枚举值。
        /// 这是从 "UI显示" -> "数据" 的过程。
        /// 
        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            // 如果传入的值是字符串
            if (value is string)
            {
                // 遍历枚举类型的所有成员
                foreach (FieldInfo fi in EnumType.GetFields())
                {
                    // 查找该成员上的DescriptionAttribute
                    var attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
                    // 如果找到了Description,并且它的描述文本与传入的字符串匹配
                    if ((attributes.Length > 0) && (attributes[0].Description == (string)value))
                    {
                        // 返回这个字段(成员)对应的枚举值
                        return Enum.Parse(EnumType, fi.Name);
                    }
                }
            }
            // 如果没有找到匹配的描述,或者传入的不是字符串,使用基类的默认转换逻辑
            return base.ConvertFrom(context, culture, value);
        }
    }
}