using SWRIS.Enums;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Windows.Data;
using System.Windows.Media;

namespace SWRIS.Converters
{
    public class RiskLevelToColorConverter : IValueConverter
    {
        private static readonly Dictionary<string, SolidColorBrush> _brushCache = new Dictionary<string, SolidColorBrush>();
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is RiskLevel risk)
            {
                double opacity = parameter != null ? System.Convert.ToDouble(parameter) : 1;
                string cacheKey = $"{risk}_{opacity}";
                // 如果缓存中存在，直接返回
                if (_brushCache.TryGetValue(cacheKey, out var cachedBrush))
                {
                    return cachedBrush;
                }
                SolidColorBrush colorBrush;
                switch (risk)
                {
                    case RiskLevel.Normal:
                    case RiskLevel.Mild:
                        colorBrush = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#00FF78"));
                        break;
                    case RiskLevel.Light:
                        colorBrush = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#FFF000"));
                        break;
                    case RiskLevel.Moderate:
                        colorBrush = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#FF9400"));
                        break;
                    case RiskLevel.Severe:
                        colorBrush = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#FF6C00"));
                        break;
                    case RiskLevel.Critical:
                        colorBrush = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#FF0000"));
                        break;
                    case RiskLevel.ExceededLimit:
                        colorBrush = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#FF008A"));
                        break;
                    default:
                        colorBrush = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#00FF78"));
                        break;
                }
                colorBrush.Opacity = opacity;
                colorBrush.Freeze();
                _brushCache[cacheKey] = colorBrush;
                return colorBrush;
            }
            return Brushes.Transparent;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}
