using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;

namespace NavisworksTransport.Core.Config
{
    /// <summary>
    /// 自定义物流类别配置管理器
    /// 从 ConfigManager 获取配置，不再使用独立的配置文件
    /// </summary>
    public class CustomCategoryConfig
    {
        /// <summary>
        /// 获取所有类别（包括内置和自定义）
        /// </summary>
        public IEnumerable<CategoryDefinition> GetAllCategories()
        {
            // 内置类别
            foreach (var builtIn in BuiltInCategories.All)
                yield return builtIn;

            // 自定义类别（从 ConfigManager 获取）
            foreach (var custom in GetCustomCategories())
                yield return custom;
        }

        /// <summary>
        /// 根据名称获取类别定义
        /// </summary>
        public CategoryDefinition GetCategory(string name)
        {
            if (string.IsNullOrEmpty(name))
                return null;

            // 先查内置
            var builtIn = BuiltInCategories.GetById(name);
            if (builtIn != null)
                return builtIn;

            // 再查自定义（按名称匹配）
            return GetCustomCategories().FirstOrDefault(c => 
                c.DisplayName.Equals(name, StringComparison.OrdinalIgnoreCase));
        }

        /// <summary>
        /// 检查是否为内置类别
        /// </summary>
        public bool IsBuiltIn(string id)
        {
            return BuiltInCategories.GetById(id) != null;
        }

        /// <summary>
        /// 检查类别是否存在
        /// </summary>
        public bool CategoryExists(string id)
        {
            return GetCategory(id) != null;
        }

        /// <summary>
        /// 添加自定义类别
        /// </summary>
        public void AddCategory(string name)
        {
            if (string.IsNullOrEmpty(name))
                throw new ArgumentException("类别名称不能为空");

            if (CategoryExists(name))
                throw new InvalidOperationException($"类别 '{name}' 已存在");

            var config = ConfigManager.Instance.Current;
            config.CustomCategories.Add(new CustomCategoryConfigItem
            {
                Name = name
            });
            
            ConfigManager.Instance.SaveConfig(config);
            LogManager.Info($"[CustomCategoryConfig] 已添加自定义类别: {name}");
        }

        /// <summary>
        /// 删除自定义类别
        /// </summary>
        public void RemoveCategory(string name)
        {
            if (IsBuiltIn(name))
                throw new InvalidOperationException("不能删除内置类别");

            var config = ConfigManager.Instance.Current;
            var category = config.CustomCategories.FirstOrDefault(c => 
                c.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
            
            if (category != null)
            {
                config.CustomCategories.Remove(category);
                ConfigManager.Instance.SaveConfig(config);
                LogManager.Info($"[CustomCategoryConfig] 已删除自定义类别: {name}");
            }
        }

        /// <summary>
        /// 从 ConfigManager 获取自定义类别列表
        /// </summary>
        private IEnumerable<CustomCategoryDefinition> GetCustomCategories()
        {
            var config = ConfigManager.Instance.Current;
            if (config.CustomCategories == null)
                yield break;

            foreach (var item in config.CustomCategories)
            {
                yield return new CustomCategoryDefinition
                {
                    Id = item.Name,  // 名称同时作为ID
                    DisplayName = item.Name
                };
            }
        }
    }

    /// <summary>
    /// 类别定义基类（内置和自定义共用接口）
    /// 简化版，仅保留核心属性
    /// </summary>
    public abstract class CategoryDefinition
    {
        public abstract string Id { get; set; }
        public abstract string DisplayName { get; set; }
    }

    /// <summary>
    /// 自定义类别定义（简化版）
    /// </summary>
    public class CustomCategoryDefinition : CategoryDefinition
    {
        public override string Id { get; set; }
        public override string DisplayName { get; set; }
    }

    /// <summary>
    /// 内置类别定义（包装 LogisticsElementType 枚举）
    /// 简化版，仅保留核心属性
    /// </summary>
    public class BuiltInCategoryDefinition : CategoryDefinition
    {
        private readonly CategoryAttributeManager.LogisticsElementType _elementType;

        public BuiltInCategoryDefinition(CategoryAttributeManager.LogisticsElementType elementType)
        {
            _elementType = elementType;
        }

        public override string Id { get => _elementType.ToString(); set => throw new NotSupportedException("内置类别不支持修改"); }
        public override string DisplayName { get => _elementType.ToString(); set => throw new NotSupportedException("内置类别不支持修改"); }

        public CategoryAttributeManager.LogisticsElementType ElementType => _elementType;
    }

    /// <summary>
    /// 内置类别管理器
    /// </summary>
    public static class BuiltInCategories
    {
        private static readonly Dictionary<string, BuiltInCategoryDefinition> _categories;

        static BuiltInCategories()
        {
            _categories = new Dictionary<string, BuiltInCategoryDefinition>(StringComparer.OrdinalIgnoreCase);

            foreach (CategoryAttributeManager.LogisticsElementType type in 
                Enum.GetValues(typeof(CategoryAttributeManager.LogisticsElementType)))
            {
                var definition = new BuiltInCategoryDefinition(type);
                _categories[type.ToString()] = definition;
            }
        }

        /// <summary>
        /// 获取所有内置类别
        /// </summary>
        public static IEnumerable<BuiltInCategoryDefinition> All => _categories.Values;

        /// <summary>
        /// 根据ID获取内置类别
        /// </summary>
        public static BuiltInCategoryDefinition GetById(string id)
        {
            _categories.TryGetValue(id ?? "", out var category);
            return category;
        }

        /// <summary>
        /// 根据枚举类型获取定义
        /// </summary>
        public static BuiltInCategoryDefinition GetByType(CategoryAttributeManager.LogisticsElementType type)
        {
            return GetById(type.ToString());
        }
    }

}
