using System;
using System.Collections.Generic;
using System.Linq;
using NPP.SmartSchedue.Api.Contracts.Domain.Work;
using NPP.SmartSchedue.Api.Contracts.Domain.Personnel;
using NPP.SmartSchedue.Api.Contracts.Services.Integration.Input;
using NPP.SmartSchedue.Api.Contracts.Services.Integration.Output;
using NPP.SmartSchedue.Api.Contracts.Services.Time.Output;

namespace NPP.SmartSchedue.Api.Contracts.Services.Integration.Internal
{
    /// <summary>
    /// 全局分配内部上下文
    /// 业务用途：封装遗传算法运行所需的完整环境信息，预加载数据避免重复查询
    /// </summary>
    public class GlobalAllocationContext
    {
        /// <summary>
        /// 待分配的任务列表
        /// </summary>
        public List<WorkOrderEntity> Tasks { get; set; } = new();
        
        /// <summary>
        /// 可用人员池
        /// </summary> 
        public List<GlobalPersonnelInfo> AvailablePersonnel { get; set; } = new();
        
        /// <summary>
        /// 全局优化配置
        /// </summary>
        public GlobalOptimizationConfig Config { get; set; } = new();
        
        /// <summary>
        /// 性能指标数据
        /// </summary>
        public Dictionary<string, object> Metrics { get; set; } = new();
        
        /// <summary>
        /// 处理日志记录
        /// </summary>
        public List<string> ProcessingLog { get; set; } = new();
        
        /// <summary>
        /// 当前正在处理的任务（用于规则验证时的精确项目信息获取）
        /// </summary>
        public WorkOrderEntity CurrentTask { get; set; }
        
        /// <summary>
        /// 班次编号映射缓存
        /// Key: ShiftId, Value: ShiftNumber
        /// </summary>
        public Dictionary<long, int> ShiftNumberMapping { get; set; } = new();

        /// <summary>
        /// 人员项目FL映射缓存
        /// Key: "PersonnelId_ProjectNumber", Value: 是否为FL
        /// </summary>
        public Dictionary<string, bool> PersonnelProjectFLMapping { get; set; } = new();
        
        /// <summary>
        /// 班次信息
        /// </summary>
        public List<ShiftGetPageOutput>  ShiftInformationCache { get; set; } = new();
        
        /// <summary>
        /// 班次规则
        /// </summary>
        public List<ShiftRuleGetPageOutput> ShiftRulesMapping { get; set; } = new();
        
        /// <summary>
        /// 【性能优化】预加载的人员历史任务数据 - 避免重复查询sse_work_order表
        /// Key: PersonnelId, Value: 该人员的历史任务列表（包含班次信息）
        /// </summary>
        public Dictionary<long, List<WorkOrderHistoryItem>> PersonnelHistoryTasks { get; set; } = new();
        
        /// <summary>
        /// 【性能优化】预加载的FL人员关系数据 - 避免重复查询sse_work_order_fl_personnel表
        /// Key: TaskId, Value: 该任务的FL人员列表
        /// </summary>
        public Dictionary<long, List<long>> TaskFLPersonnelMapping { get; set; } = new();
        
        /// <summary>
        /// 【性能优化】预加载的人员资质缓存 - 避免重复查询sse_personnel_qualification表
        /// Key: PersonnelId, Value: 该人员的资质信息列表
        /// 用于加速资质匹配计算，避免遗传算法中的重复资质查询
        /// </summary>
        public Dictionary<long, List<PersonnelQualificationCacheItem>> PersonnelQualificationsCache { get; set; } = new();
        
        /// <summary>
        /// 【性能优化】预筛选结果缓存 - 60%性能提升核心机制
        /// Key: "TaskId_PersonnelId" (复合键), Value: 预筛选评分和可行性结果
        /// 用于快速排除不可行的任务-人员组合，大幅减少遗传算法搜索空间
        /// </summary>
        public Dictionary<string, PersonnelTaskPrefilterResult> PrefilterResults { get; set; } = new();
        
        /// <summary>
        /// 【性能优化】高优先级任务-人员组合索引
        /// 用于加速遗传算法初始种群生成和变异操作
        /// </summary>
        public Dictionary<long, List<long>> HighPriorityTaskPersonnelMapping { get; set; } = new();
        
        /// <summary>
        /// 【并行计算】线程安全的缓存锁
        /// 用于并行计算时保护共享数据结构
        /// </summary>
        public readonly object CacheLock = new object();
        
        /// <summary>
        /// 【收敛检测】遗传算法收敛检测器 - 15%性能提升
        /// 用于智能监测算法收敛状态，提前终止无效迭代
        /// </summary>
        public ConvergenceDetector ConvergenceDetector { get; set; } = new();
        
        /// <summary>
        /// 【并行计算】并行计算分区列表 - 40%性能提升
        /// 用于多线程并行处理，充分利用多核处理器性能
        /// </summary>
        public List<ParallelComputePartition> ParallelPartitions { get; set; } = new();
        
        /// <summary>
        /// 【缓存优化】智能分层缓存管理器 - 20%性能提升
        /// 用于管理多层次缓存结构，提供智能缓存策略和生命周期管理
        /// </summary>
        public IntelligentCacheManager CacheManager { get; set; } = new();

        #region 班次规则验证专用缓存 - 新增

        /// <summary>
        /// 【班次规则优化】人员历史工作日期缓存 - 15天时间窗口
        /// Key: PersonnelId, Value: 工作日期列表
        /// 用途: 加速连续工作天数、次日休息等规则验证，避免重复查询
        /// </summary>
        public Dictionary<long, List<DateTime>> PersonnelWorkDatesCache { get; set; } = new();
        
        /// <summary>
        /// 【班次规则优化】项目FL人员映射 - 项目FL优先规则专用
        /// Key: "PersonnelId_ProjectNumber", Value: 是否为该项目FL
        /// 用途: 快速判断人员在项目中的FL身份，优化规则10验证性能
        /// </summary>
        public Dictionary<string, bool> PersonnelProjectFLCache { get; set; } = new();
        
        /// <summary>
        /// 【班次规则优化】人员项目FL统计 - 综合评分专用
        /// Key: PersonnelId, Value: 该人员所有项目FL关联信息
        /// 用途: 支持规则10的综合评分算法，考虑多项目FL经验
        /// </summary>
        public Dictionary<long, List<ProjectFLSummary>> PersonnelAllProjectFLsCache { get; set; } = new();

        /// <summary>
        /// 时间窗口起始日期 - 15天历史数据范围
        /// </summary>
        public DateTime TimeWindowStartDate { get; set; }
        
        /// <summary>
        /// 时间窗口结束日期 - 15天未来数据范围
        /// </summary>
        public DateTime TimeWindowEndDate { get; set; }
        
        /// <summary>
        /// 已加载缓存数据的人员ID集合 - 避免重复加载
        /// </summary>
        public HashSet<long> CachedPersonnelIds { get; set; } = new();
        
        /// <summary>
        /// 已加载缓存数据的项目集合 - 避免重复加载
        /// </summary>
        public HashSet<string> CachedProjects { get; set; } = new();

        #endregion
        
        #region 班次不可用性缓存 - 新增高价值缓存
        
        /// <summary>
        /// 【高价值缓存】班次不可用性数据 - 85%+性能提升核心
        /// Key: "Date_ShiftId" (复合键), Value: 该日期班次不可用的人员ID集合
        /// 业务用途: 快速排除在指定日期班次不可用的人员，避免无效分配
        /// 缓存策略: 基于任务时间范围的智能窗口加载，避免全量数据
        /// </summary>
        public Dictionary<string, HashSet<long>> DateShiftUnavailablePersonnel { get; set; } = new();
        
        /// <summary>
        /// 【性能优化】人员不可用性快速索引 - 支持人员维度的快速查询
        /// Key: PersonnelId, Value: 该人员的不可用时间-班次映射
        /// 业务用途: 在遗传算法中快速检查人员在特定时间的可用性
        /// </summary>
        public Dictionary<long, Dictionary<DateTime, HashSet<long>>> PersonnelUnavailabilityIndex { get; set; } = new();
        
        /// <summary>
        /// 【详细信息】班次不可用性详细数据缓存 - 支持复杂业务逻辑
        /// Key: "Date_ShiftId_PersonnelId", Value: 不可用性详细信息
        /// 业务用途: 提供不可用原因、优先级、时间段等详细信息，支持智能调度决策
        /// </summary>
        public Dictionary<string, ShiftUnavailabilityCacheItem> UnavailabilityDetails { get; set; } = new();
        
        /// <summary>
        /// 不可用性缓存的时间窗口起始日期
        /// 基于任务组的最早日期计算
        /// </summary>
        public DateTime UnavailabilityTimeWindowStart { get; set; }
        
        /// <summary>
        /// 不可用性缓存的时间窗口结束日期
        /// 基于任务组的最晚日期计算  
        /// </summary>
        public DateTime UnavailabilityTimeWindowEnd { get; set; }
        
        /// <summary>
        /// 缓存命中率统计 - 性能监控用
        /// </summary>
        public UnavailabilityCacheStats CacheStats { get; set; } = new();

        #endregion

        #region 人员工作限制和请假缓存

        /// <summary>
        /// 人员工作限制规则缓存
        /// Key: PersonnelId, Value: 工作限制规则列表
        /// </summary>
        public Dictionary<long, PersonnelWorkLimitEntity> PersonnelWorkLimitsRuleCache { get; set; } = new();

        /// <summary>
        /// 人员请假记录缓存
        /// Key: PersonnelId, Value: 请假记录列表
        /// </summary>
        public Dictionary<long, List<EmployeeLeaveRecord>> PersonnelLeaveRecordsCache { get; set; } = new();

        #endregion
    }

    /// <summary>
    /// 工作任务历史记录项 - 优化数据结构
    /// 用于缓存人员历史任务，减少数据库查询
    /// </summary>
    public class WorkOrderHistoryItem
    {
        public long TaskId { get; set; }
        public DateTime WorkDate { get; set; }
        public long? ShiftId { get; set; }
        public int? ShiftNumber { get; set; }
        public string ShiftName { get; set; }
        public string TaskCode { get; set; }
        public string ProjectNumber { get; set; }
        public int Status { get; set; }
    }

    /// <summary>
    /// 班次规则项 - 优化数据结构
    /// 用于缓存班次规则，减少数据库查询
    /// </summary>
    public class ShiftRuleItem
    {
        public long RuleId { get; set; }
        public string RuleType { get; set; }
        public string RuleName { get; set; }
        public bool IsEnabled { get; set; }
        public string RuleDescription { get; set; }
    }

    /// <summary>
    /// 全局分配人员信息
    /// 业务用途：算法层使用的简化人员信息结构
    /// </summary>
    public class GlobalPersonnelInfo
    {
        /// <summary>
        /// 人员ID
        /// </summary>
        public long Id { get; set; }
        
        /// <summary>
        /// 人员姓名
        /// </summary>
        public string Name { get; set; } = string.Empty;
        
        /// <summary>
        /// 是否激活
        /// </summary>
        public bool IsActive { get; set; } = true;
    }

    /// <summary>
    /// 输入验证结果
    /// 业务用途：封装输入参数验证的结果信息
    /// </summary>
    public class GlobalInputValidationResult
    {
        /// <summary>
        /// 验证是否通过
        /// </summary>
        public bool IsValid { get; set; }
        
        /// <summary>
        /// 错误消息
        /// </summary>
        public string ErrorMessage { get; set; } = string.Empty;
        
        /// <summary>
        /// 已验证的工作任务列表
        /// </summary>
        public List<WorkOrderEntity> WorkOrders { get; set; } = new();
    }

    /// <summary>
    /// 遗传算法优化解决方案
    /// 业务用途：封装遗传算法的优化结果和性能指标
    /// </summary>
    public class GlobalOptimizedSolution
    {
        /// <summary>
        /// 解决方案是否有效
        /// </summary>
        public bool IsValid { get; set; }
        
        /// <summary>
        /// 最佳分配方案 (TaskId -> PersonnelId)
        /// </summary>
        public Dictionary<long, long> BestSolution { get; set; } = new();
        
        /// <summary>
        /// 失败的任务ID列表
        /// </summary>
        public List<long> FailedTasks { get; set; } = new();
        
        /// <summary>
        /// 人员工作负载分布 (PersonnelId -> Workload)
        /// </summary>
        public Dictionary<long, decimal> PersonnelWorkloadDistribution { get; set; } = new();
        
        /// <summary>
        /// 实际执行的遗传代数
        /// </summary>
        public int ActualGenerations { get; set; }
        
        /// <summary>
        /// 收敛水平 (0-1)
        /// </summary>
        public double ConvergenceLevel { get; set; }
        
        /// <summary>
        /// 最佳适应度分数
        /// </summary>
        public double BestFitness { get; set; }
        
        /// <summary>
        /// 平均适应度分数
        /// </summary>
        public double AverageFitness { get; set; }
        
        /// <summary>
        /// 约束满足率
        /// </summary>
        public double ConstraintSatisfactionRate { get; set; }

        /// <summary>
        /// 获取指定人员分配的任务数量
        /// </summary>
        /// <param name="personnelId">人员ID</param>
        /// <returns>任务数量</returns>
        public int GetTaskCountForPersonnel(long personnelId)
        {
            return BestSolution.Count(kvp => kvp.Value == personnelId);
        }

        /// <summary>
        /// 获取指定人员分配的任务ID列表
        /// </summary>
        /// <param name="personnelId">人员ID</param>
        /// <returns>任务ID列表</returns>
        public List<long> GetAssignedTaskIds(long personnelId)
        {
            return BestSolution.Where(kvp => kvp.Value == personnelId).Select(kvp => kvp.Key).ToList();
        }
    }

    /// <summary>
    /// 智能协商结果
    /// 业务用途：封装协商引擎的执行结果
    /// </summary>
    public class GlobalNegotiationResult
    {
        /// <summary>
        /// 协商操作列表
        /// </summary>
        public List<GlobalNegotiationAction> Actions { get; set; } = new();
        
        /// <summary>
        /// 冲突检测信息列表
        /// </summary>
        public List<GlobalConflictDetectionInfo> ConflictDetections { get; set; } = new();
    }

    /// <summary>
    /// 人员任务预筛选结果 - 核心性能优化数据结构
    /// 业务用途：缓存任务-人员组合的预筛选评估结果，避免重复计算
    /// 性能价值：将O(n²)的适应度计算优化为O(1)的缓存查找
    /// </summary>
    public class PersonnelTaskPrefilterResult
    {
        /// <summary>
        /// 任务ID
        /// </summary>
        public long TaskId { get; set; }
        
        /// <summary>
        /// 人员ID
        /// </summary>
        public long PersonnelId { get; set; }
        
        /// <summary>
        /// 是否可行（硬约束检查结果）
        /// </summary>
        public bool IsFeasible { get; set; }
        
        /// <summary>
        /// 预筛选评分（0-100分，综合软约束评估）
        /// </summary>
        public double PrefilterScore { get; set; }
        
        /// <summary>
        /// 约束违规类型列表
        /// </summary>
        public List<string> ConstraintViolations { get; set; } = new();
        
        /// <summary>
        /// 评分详细分解
        /// </summary>
        public Dictionary<string, double> ScoreBreakdown { get; set; } = new();
        
        /// <summary>
        /// 缓存时间戳（用于缓存过期管理）
        /// </summary>
        public DateTime CacheTimestamp { get; set; } = DateTime.Now;
        
        /// <summary>
        /// 是否为高优先级组合
        /// </summary>
        public bool IsHighPriority { get; set; }
    }

    /// <summary>
    /// 遗传算法收敛检测器 - 15%性能提升机制
    /// 业务用途：监测遗传算法收敛状态，提前终止无效迭代
    /// 性能价值：避免无意义的计算资源浪费，智能调整迭代次数
    /// </summary>
    public class ConvergenceDetector
    {
        /// <summary>
        /// 历史最佳适应度记录（最近N代）
        /// </summary>
        public List<double> FitnessHistory { get; set; } = new();
        
        /// <summary>
        /// 收敛检测窗口大小
        /// </summary>
        public int WindowSize { get; set; } = 10;
        
        /// <summary>
        /// 收敛阈值（适应度改善低于此值认为收敛）
        /// </summary>
        public double ConvergenceThreshold { get; set; } = 0.001;
        
        /// <summary>
        /// 当前收敛状态
        /// </summary>
        public bool IsConverged { get; set; }
        
        /// <summary>
        /// 收敛检测开始的最小代数
        /// </summary>
        public int MinGenerationsBeforeCheck { get; set; } = 20;
        
        /// <summary>
        /// 平台期持续代数（适应度无显著改善的连续代数）
        /// </summary>
        public int PlateauGenerations { get; set; }
        
        /// <summary>
        /// 最大允许的平台期代数
        /// </summary>
        public int MaxPlateauGenerations { get; set; } = 15;
        
        /// <summary>
        /// 当前最佳适应度
        /// </summary>
        public double CurrentBestFitness { get; set; }
        
        /// <summary>
        /// 上一次显著改善时的代数
        /// </summary>
        public int LastImprovementGeneration { get; set; }
    }

    /// <summary>
    /// 并行计算任务分区 - 40%性能提升机制
    /// 业务用途：将计算任务合理分区，支持多线程并行处理
    /// 性能价值：充分利用多核处理器，显著提升计算速度
    /// </summary>
    public class ParallelComputePartition
    {
        /// <summary>
        /// 分区ID
        /// </summary>
        public int PartitionId { get; set; }
        
        /// <summary>
        /// 分区包含的任务ID列表
        /// </summary>
        public List<long> TaskIds { get; set; } = new();
        
        /// <summary>
        /// 分区包含的人员ID列表
        /// </summary>
        public List<long> PersonnelIds { get; set; } = new();
        
        /// <summary>
        /// 分区的预筛选结果
        /// </summary>
        public List<PersonnelTaskPrefilterResult> PartitionPrefilterResults { get; set; } = new();
        
        /// <summary>
        /// 分区处理状态
        /// </summary>
        public ParallelPartitionStatus Status { get; set; } = ParallelPartitionStatus.Pending;
        
        /// <summary>
        /// 分区处理开始时间
        /// </summary>
        public DateTime StartTime { get; set; }
        
        /// <summary>
        /// 分区处理结束时间
        /// </summary>
        public DateTime EndTime { get; set; }
        
        /// <summary>
        /// 分区处理异常信息
        /// </summary>
        public string ErrorMessage { get; set; } = string.Empty;
    }

    /// <summary>
    /// 并行分区处理状态枚举
    /// </summary>
    public enum ParallelPartitionStatus
    {
        /// <summary>
        /// 等待处理
        /// </summary>
        Pending,
        
        /// <summary>
        /// 正在处理
        /// </summary>
        Processing,
        
        /// <summary>
        /// 处理完成
        /// </summary>
        Completed,
        
        /// <summary>
        /// 处理失败
        /// </summary>
        Failed
    }

    /// <summary>
    /// 智能分层缓存管理器 - 20%性能提升核心组件
    /// 业务用途：提供多层次缓存架构，优化数据访问模式，减少重复计算
    /// 技术特点：L1高速缓存、L2常规缓存、L3持久缓存、智能淘汰策略
    /// 性能价值：显著减少数据库访问、计算重复执行，提升整体响应速度
    /// </summary>
    public class IntelligentCacheManager
    {
        /// <summary>
        /// L1高速缓存 - 最频繁访问的数据（内存中，容量小，速度最快）
        /// 适用：当前分配过程中的热点数据，如活跃的班次规则、FL关系等
        /// </summary>
        public Dictionary<string, CacheItem<object>> L1Cache { get; set; } = new();
        
        /// <summary>
        /// L2常规缓存 - 一般频率访问的数据（内存中，容量中等）
        /// 适用：预筛选结果、人员历史数据、计算结果等
        /// </summary>
        public Dictionary<string, CacheItem<object>> L2Cache { get; set; } = new();
        
        /// <summary>
        /// L3持久缓存 - 低频率但重要的数据（可持久化，容量大）
        /// 适用：基础配置数据、长期统计数据等
        /// </summary>
        public Dictionary<string, CacheItem<object>> L3Cache { get; set; } = new();
        
        /// <summary>
        /// 缓存访问统计 - 用于智能缓存策略优化
        /// </summary>
        public Dictionary<string, CacheAccessStats> AccessStats { get; set; } = new();
        
        /// <summary>
        /// L1缓存最大容量
        /// </summary>
        public int L1MaxSize { get; set; } = 100;
        
        /// <summary>
        /// L2缓存最大容量
        /// </summary>
        public int L2MaxSize { get; set; } = 500;
        
        /// <summary>
        /// L3缓存最大容量
        /// </summary>
        public int L3MaxSize { get; set; } = 2000;
        
        /// <summary>
        /// 缓存清理间隔（秒）
        /// </summary>
        public int CleanupIntervalSeconds { get; set; } = 300;
        
        /// <summary>
        /// 上次清理时间
        /// </summary>
        public DateTime LastCleanupTime { get; set; } = DateTime.Now;
        
        /// <summary>
        /// 缓存命中率统计
        /// </summary>
        public CachePerformanceStats PerformanceStats { get; set; } = new();
    }

    /// <summary>
    /// 缓存项 - 包含数据和元数据的封装结构
    /// </summary>
    public class CacheItem<T>
    {
        /// <summary>
        /// 缓存的数据
        /// </summary>
        public T Data { get; set; }
        
        /// <summary>
        /// 创建时间
        /// </summary>
        public DateTime CreatedTime { get; set; } = DateTime.Now;
        
        /// <summary>
        /// 最后访问时间
        /// </summary>
        public DateTime LastAccessTime { get; set; } = DateTime.Now;
        
        /// <summary>
        /// 访问次数
        /// </summary>
        public int AccessCount { get; set; } = 0;
        
        /// <summary>
        /// 过期时间（可选）
        /// </summary>
        public DateTime? ExpiryTime { get; set; }
        
        /// <summary>
        /// 缓存优先级
        /// </summary>
        public CachePriority Priority { get; set; } = CachePriority.Normal;
        
        /// <summary>
        /// 数据大小估算（用于内存管理）
        /// </summary>
        public long EstimatedSize { get; set; } = 0;
        
        /// <summary>
        /// 是否已过期
        /// </summary>
        public bool IsExpired => ExpiryTime.HasValue && DateTime.Now > ExpiryTime.Value;
        
        /// <summary>
        /// 缓存效价值评分（访问频率 × 优先级 × 时效性）
        /// </summary>
        public double ValueScore => (AccessCount + 1) * (int)Priority * GetTimeWeight();
        
        /// <summary>
        /// 计算时间权重（越新的数据权重越高）
        /// </summary>
        private double GetTimeWeight()
        {
            var ageHours = (DateTime.Now - LastAccessTime).TotalHours;
            return Math.Max(0.1, 1.0 - (ageHours / 24.0)); // 24小时内的数据权重从1.0递减到0.1
        }
    }

    /// <summary>
    /// 缓存访问统计
    /// </summary>
    public class CacheAccessStats
    {
        /// <summary>
        /// 总访问次数
        /// </summary>
        public long TotalAccesses { get; set; }
        
        /// <summary>
        /// 缓存命中次数
        /// </summary>
        public long HitCount { get; set; }
        
        /// <summary>
        /// 缓存未命中次数
        /// </summary>
        public long MissCount { get; set; }
        
        /// <summary>
        /// 缓存命中率
        /// </summary>
        public double HitRate => TotalAccesses > 0 ? (double)HitCount / TotalAccesses : 0.0;
        
        /// <summary>
        /// 平均访问时间（毫秒）
        /// </summary>
        public double AverageAccessTimeMs { get; set; }
        
        /// <summary>
        /// 最后统计重置时间
        /// </summary>
        public DateTime LastResetTime { get; set; } = DateTime.Now;
    }

    /// <summary>
    /// 缓存性能统计
    /// </summary>
    public class CachePerformanceStats
    {
        /// <summary>
        /// L1缓存命中率
        /// </summary>
        public double L1HitRate { get; set; }
        
        /// <summary>
        /// L2缓存命中率
        /// </summary>
        public double L2HitRate { get; set; }
        
        /// <summary>
        /// L3缓存命中率
        /// </summary>
        public double L3HitRate { get; set; }
        
        /// <summary>
        /// 整体缓存命中率
        /// </summary>
        public double OverallHitRate { get; set; }
        
        /// <summary>
        /// 缓存节省的数据库查询次数
        /// </summary>
        public long SavedDatabaseQueries { get; set; }
        
        /// <summary>
        /// 缓存节省的计算时间（毫秒）
        /// </summary>
        public long SavedComputationMs { get; set; }
        
        /// <summary>
        /// 内存使用量估算（字节）
        /// </summary>
        public long MemoryUsageBytes { get; set; }
    }

    /// <summary>
    /// 缓存优先级枚举
    /// </summary>
    public enum CachePriority
    {
        /// <summary>
        /// 低优先级 - 可随时清理
        /// </summary>
        Low = 1,
        
        /// <summary>
        /// 普通优先级 - 常规清理策略
        /// </summary>
        Normal = 2,
        
        /// <summary>
        /// 高优先级 - 优先保留
        /// </summary>
        High = 3,
        
        /// <summary>
        /// 关键优先级 - 尽量不清理
        /// </summary>
        Critical = 4
    }

    #region 性能测试相关数据结构

    /// <summary>
    /// 性能基准测试结果
    /// 业务用途：封装性能测试的完整结果，包含优化前后对比
    /// </summary>
    public class PerformanceBenchmarkResult
    {
        /// <summary>
        /// 测试是否成功
        /// </summary>
        public bool IsSuccess { get; set; }
        
        /// <summary>
        /// 错误消息（如果测试失败）
        /// </summary>
        public string ErrorMessage { get; set; } = string.Empty;
        
        /// <summary>
        /// 测试配置信息
        /// </summary>
        public PerformanceTestConfig TestConfiguration { get; set; } = new();
        
        /// <summary>
        /// 优化后的性能指标
        /// </summary>
        public PerformanceMetrics OptimizedPerformance { get; set; } = new();
        
        /// <summary>
        /// 基线性能指标（优化前估算）
        /// </summary>
        public PerformanceMetrics BaselinePerformance { get; set; } = new();
        
        /// <summary>
        /// 性能改进报告
        /// </summary>
        public PerformanceImprovementReport PerformanceImprovement { get; set; } = new();
        
        /// <summary>
        /// 测试执行总时间（毫秒）
        /// </summary>
        public long TestExecutionTimeMs { get; set; }
        
        /// <summary>
        /// 测试执行时间戳
        /// </summary>
        public DateTime TestTimestamp { get; set; } = DateTime.Now;
    }

    /// <summary>
    /// 性能测试配置
    /// </summary>
    public class PerformanceTestConfig
    {
        /// <summary>
        /// 测试任务数量
        /// </summary>
        public int TaskCount { get; set; }
        
        /// <summary>
        /// 种群大小
        /// </summary>
        public int PopulationSize { get; set; }
        
        /// <summary>
        /// 最大迭代代数
        /// </summary>
        public int MaxGenerations { get; set; }
        
        /// <summary>
        /// 最大执行时间（秒）
        /// </summary>
        public int MaxExecutionTimeSeconds { get; set; }
        
        /// <summary>
        /// 测试环境信息
        /// </summary>
        public string TestEnvironment { get; set; } = Environment.MachineName;
        
        /// <summary>
        /// CPU核心数
        /// </summary>
        public int CpuCores { get; set; } = Environment.ProcessorCount;
    }

    /// <summary>
    /// 性能指标
    /// 业务用途：详细记录各阶段的性能数据
    /// </summary>
    public class PerformanceMetrics
    {
        /// <summary>
        /// 总执行时间（毫秒）
        /// </summary>
        public long TotalExecutionTimeMs { get; set; }
        
        /// <summary>
        /// 上下文构建时间（毫秒）
        /// </summary>
        public long ContextBuildTimeMs { get; set; }
        
        /// <summary>
        /// 预筛选时间（毫秒）
        /// </summary>
        public long PrefilteringTimeMs { get; set; }
        
        /// <summary>
        /// 遗传算法执行时间（毫秒）
        /// </summary>
        public long GeneticAlgorithmTimeMs { get; set; }
        
        /// <summary>
        /// 协商时间（毫秒）
        /// </summary>
        public long NegotiationTimeMs { get; set; }
        
        /// <summary>
        /// 实际执行代数
        /// </summary>
        public int ActualGenerations { get; set; }
        
        /// <summary>
        /// 最佳适应度
        /// </summary>
        public double BestFitness { get; set; }
        
        /// <summary>
        /// 约束满足率
        /// </summary>
        public double ConstraintSatisfactionRate { get; set; }
        
        /// <summary>
        /// 收敛水平
        /// </summary>
        public double ConvergenceLevel { get; set; }
        
        /// <summary>
        /// 复杂度因子（用于算法复杂度分析）
        /// </summary>
        public long ComplexityFactor { get; set; }
        
        /// <summary>
        /// 是否为估算值
        /// </summary>
        public bool IsEstimate { get; set; }
        
        /// <summary>
        /// 是否有错误
        /// </summary>
        public bool HasError { get; set; }
        
        /// <summary>
        /// 错误消息
        /// </summary>
        public string ErrorMessage { get; set; } = string.Empty;
        
        /// <summary>
        /// 内存使用峰值（字节）
        /// </summary>
        public long PeakMemoryUsageBytes { get; set; }
        
        /// <summary>
        /// CPU使用率（百分比）
        /// </summary>
        public double CpuUsagePercent { get; set; }
    }

    /// <summary>
    /// 性能改进报告
    /// 业务用途：量化优化效果，提供详细的对比分析
    /// </summary>
    public class PerformanceImprovementReport
    {
        /// <summary>
        /// 时间改进百分比
        /// </summary>
        public double TimeImprovementPercent { get; set; }
        
        /// <summary>
        /// 加速倍数
        /// </summary>
        public double SpeedupFactor { get; set; }
        
        /// <summary>
        /// 预筛选时间改进（毫秒）
        /// </summary>
        public long PrefilteringImprovementMs { get; set; }
        
        /// <summary>
        /// 遗传算法时间改进（毫秒）
        /// </summary>
        public long GeneticAlgorithmImprovementMs { get; set; }
        
        /// <summary>
        /// 质量改进百分比
        /// </summary>
        public double QualityImprovementPercent { get; set; }
        
        /// <summary>
        /// 约束满足率改进百分比
        /// </summary>
        public double ConstraintImprovementPercent { get; set; }
        
        /// <summary>
        /// 综合改进百分比
        /// </summary>
        public double OverallImprovementPercent { get; set; }
        
        /// <summary>
        /// 改进总结报告
        /// </summary>
        public string ImprovementSummary { get; set; } = string.Empty;
        
        /// <summary>
        /// 关键优化点列表
        /// </summary>
        public List<string> KeyOptimizations { get; set; } = new();
        
        /// <summary>
        /// 进一步优化建议
        /// </summary>
        public List<string> FurtherOptimizationSuggestions { get; set; } = new();
    }

    #endregion
    
    #region 人员数据缓存项定义
    
    /// <summary>
    /// 人员工作限制缓存项
    /// 业务用途：缓存sse_personnel_work_limit表数据，避免遗传算法中的重复查询
    /// </summary>
    public class PersonnelWorkLimitCacheItem
    {
        /// <summary>
        /// 主键ID
        /// </summary>
        public long Id { get; set; }
        
        /// <summary>
        /// 人员ID
        /// </summary>
        public long PersonnelId { get; set; }
        
        /// <summary>
        /// 最大连续工作天数
        /// </summary>
        public int? MaxContinuousWorkDays { get; set; }
        
        /// <summary>
        /// 当周最大排班次数
        /// </summary>
        public int? MaxShiftsPerWeek { get; set; }
        
        /// <summary>
        /// 特殊限制规则
        /// </summary>
        public string? SpecialRule { get; set; }
    }
    
    /// <summary>
    /// 人员资质缓存项
    /// 业务用途：缓存sse_personnel_qualification表数据，用于快速资质匹配
    /// </summary>
    public class PersonnelQualificationCacheItem
    {
        /// <summary>
        /// 主键ID
        /// </summary>
        public long Id { get; set; }
        
        /// <summary>
        /// 人员ID
        /// </summary>
        public long PersonnelId { get; set; }
        
        /// <summary>
        /// 人员姓名
        /// </summary>
        public string PersonnelName { get; set; } = string.Empty;
        
        /// <summary>
        /// 资质ID
        /// </summary>
        public long QualificationId { get; set; }

        /// <summary>
        /// 岗位负责人
        /// </summary>
        public bool HighLevel { get; set; } = false;
        
        /// <summary>
        /// 有效期
        /// </summary>
        public DateTime? ExpiryDate { get; set; }
        
        /// <summary>
        /// 有效期预警天数
        /// </summary>
        public int? ExpiryWarningDays { get; set; }
        
        /// <summary>
        /// 续期日期
        /// </summary>
        public DateTime? RenewalDate { get; set; }
        
        /// <summary>
        /// 绑定状态
        /// </summary>
        public bool IsActive { get; set; }
    }
    
    #endregion

    #region 班次规则验证相关数据结构 - 新增

    /// <summary>
    /// 人员工作限制实体 - 缓存版本
    /// 用途：缓存sse_personnel_work_limit表数据，避免频繁数据库查询
    /// </summary>
    public class PersonnelWorkLimitEntity
    {
        public long Id { get; set; }
        public long PersonnelId { get; set; }
        public int? MaxContinuousWorkDays { get; set; }
        public int? MaxShiftsPerWeek { get; set; }
        public string? SpecialRules { get; set; }
        public bool IsActive { get; set; } = true;
    }

    /// <summary>
    /// 员工请假记录 - 缓存版本
    /// 用途：缓存请假信息，快速验证时间可用性
    /// </summary>
    public class EmployeeLeaveRecord
    {
        public long Id { get; set; }
        public long PersonnelId { get; set; }
        public DateTime StartDate { get; set; }
        public DateTime EndDate { get; set; }
        public string LeaveType { get; set; } = string.Empty;
        public bool IsApproved { get; set; }
    }

    /// <summary>
    /// 项目FL汇总信息
    /// 用途：支持规则10的综合评分算法
    /// </summary>
    public class ProjectFLSummary
    {
        /// <summary>
        /// 项目号
        /// </summary>
        public string ProjectNumber { get; set; } = string.Empty;
        
        /// <summary>
        /// 在该项目中的任务数量
        /// </summary>
        public int TaskCount { get; set; }
        
        /// <summary>
        /// 最后参与该项目的时间
        /// </summary>
        public DateTime LastAssignmentDate { get; set; }
        
        /// <summary>
        /// 项目活跃度评分
        /// </summary>
        public double ActivityScore { get; set; }
    }
    
    #region 班次不可用性相关数据结构

    /// <summary>
    /// 班次不可用性缓存项 - 优化数据结构
    /// 用于缓存人员在特定日期班次的不可用性详细信息
    /// </summary>
    public class ShiftUnavailabilityCacheItem
    {
        /// <summary>
        /// 人员ID
        /// </summary>
        public long PersonnelId { get; set; }
        
        /// <summary>
        /// 日期
        /// </summary>
        public DateTime Date { get; set; }
        
        /// <summary>
        /// 班次ID
        /// </summary>
        public long ShiftId { get; set; }
        
        /// <summary>
        /// 不可用原因类型
        /// 1=个人意愿, 2=培训任务, 3=会议任务, 4=设备维护, 7=临时请假, 8=计划请假, 9=医疗原因, 10=家庭事务, 11=轮岗安排, 12=技能认证, 99=其他原因
        /// </summary>
        public int ReasonType { get; set; }
        
        /// <summary>
        /// 优先级权重
        /// </summary>
        public int Priority { get; set; }
        
        /// <summary>
        /// 生效开始时间（可选）
        /// </summary>
        public TimeSpan? EffectiveStartTime { get; set; }
        
        /// <summary>
        /// 生效结束时间（可选）
        /// </summary>
        public TimeSpan? EffectiveEndTime { get; set; }
        
        /// <summary>
        /// 备注信息
        /// </summary>
        public string Remark { get; set; }
        
        /// <summary>
        /// 是否为硬约束（不可违反）
        /// </summary>
        public bool IsHardConstraint => ReasonType is 7 or 8 or 9; // 请假和医疗原因为硬约束
        
        /// <summary>
        /// 约束权重评分（用于遗传算法评分）
        /// </summary>
        public double ConstraintScore
        {
            get
            {
                return ReasonType switch
                {
                    1 => 0.3,  // 个人意愿 - 软约束
                    2 => 0.2,  // 培训任务 - 可协调
                    3 => 0.4,  // 会议任务 - 中等约束
                    4 => 0.6,  // 设备维护 - 较强约束
                    7 => 0.0,  // 临时请假 - 硬约束
                    8 => 0.0,  // 计划请假 - 硬约束
                    9 => 0.0,  // 医疗原因 - 硬约束
                    10 => 0.1, // 家庭事务 - 弱约束
                    11 => 0.3, // 轮岗安排 - 软约束
                    12 => 0.5, // 技能认证 - 中等约束
                    _ => 0.2   // 其他原因 - 默认软约束
                };
            }
        }
    }

    /// <summary>
    /// 不可用性缓存统计信息
    /// </summary>
    public class UnavailabilityCacheStats
    {
        /// <summary>
        /// 缓存命中次数
        /// </summary>
        public long HitCount { get; set; }
        
        /// <summary>
        /// 缓存未命中次数
        /// </summary>
        public long MissCount { get; set; }
        
        /// <summary>
        /// 缓存命中率
        /// </summary>
        public double HitRate => HitCount + MissCount == 0 ? 0 : (double)HitCount / (HitCount + MissCount);
        
        /// <summary>
        /// 缓存的记录总数
        /// </summary>
        public int CachedRecordCount { get; set; }
        
        /// <summary>
        /// 覆盖的人员数量
        /// </summary>
        public int CoveredPersonnelCount { get; set; }
        
        /// <summary>
        /// 覆盖的日期范围天数
        /// </summary>
        public int CoveredDays { get; set; }
        
        /// <summary>
        /// 硬约束记录数量
        /// </summary>
        public int HardConstraintCount { get; set; }
        
        /// <summary>
        /// 软约束记录数量
        /// </summary>
        public int SoftConstraintCount { get; set; }
    }

    #endregion

    /// <summary>
    /// 规则验证结果 - 与PersonnelAllocationService保持一致
    /// </summary>
    public class ShiftRuleValidationResult
    {
        /// <summary>
        /// 是否验证通过
        /// </summary>
        public bool IsValid { get; set; }
        
        /// <summary>
        /// 合规评分 (0-100)
        /// </summary>
        public double ComplianceScore { get; set; }
        
        /// <summary>
        /// 是否为关键违规
        /// </summary>
        public bool IsCritical { get; set; }
        
        /// <summary>
        /// 违规信息
        /// </summary>
        public string ViolationMessage { get; set; } = string.Empty;
    }

    /// <summary>
    /// 班次规则验证汇总结果
    /// </summary>
    public class ShiftRulesValidationSummary
    {
        /// <summary>
        /// 整体是否合规
        /// </summary>
        public bool IsCompliant { get; set; }
        
        /// <summary>
        /// 综合评分
        /// </summary>
        public double OverallScore { get; set; }
        
        /// <summary>
        /// 验证详情
        /// </summary>
        public string ValidationReason { get; set; } = string.Empty;
        
        /// <summary>
        /// 是否有关键违规
        /// </summary>
        public bool HasCriticalViolations { get; set; }
        
        /// <summary>
        /// 个别规则验证结果
        /// </summary>
        public List<ShiftRuleValidationResult> IndividualResults { get; set; } = new();
    }

    /// <summary>
    /// 规则类型和配置信息
    /// </summary>
    public class ShiftRuleConfig
    {
        public string RuleType { get; set; } = string.Empty;
        public int Priority { get; set; }
        public bool IsCritical { get; set; }
        public string RuleName { get; set; } = string.Empty;
        public string Description { get; set; } = string.Empty;
    }

    /// <summary>
    /// 规则优先级配置 - 与用户决策保持一致
    /// </summary>
    public static class ShiftRulePriorityConfig
    {
        public static readonly Dictionary<string, ShiftRuleConfig> Rules = new()
        {
            ["1"] = new() { RuleType = "1", Priority = 5, IsCritical = false, RuleName = "指定人员优先", Description = "优先分配指定人员" },
            ["2"] = new() { RuleType = "2", Priority = 2, IsCritical = true, RuleName = "周任务限制", Description = "限制人员周任务数量" },
            ["3"] = new() { RuleType = "3", Priority = 3, IsCritical = true, RuleName = "早中班连续性", Description = "同天禁止早班和中班同时存在" },
            ["4"] = new() { RuleType = "4", Priority = 3, IsCritical = true, RuleName = "中夜班连续性", Description = "同天禁止中班和夜班同时存在" },
            ["5"] = new() { RuleType = "5", Priority = 4, IsCritical = true, RuleName = "跨周末连续性", Description = "禁止周日/下周六连续工作" },
            ["6"] = new() { RuleType = "6", Priority = 4, IsCritical = true, RuleName = "周末连续性", Description = "禁止周六/周日连续工作" },
            ["7"] = new() { RuleType = "7", Priority = 2, IsCritical = true, RuleName = "连续工作天数", Description = "限制连续工作天数" },
            ["8"] = new() { RuleType = "8", Priority = 1, IsCritical = true, RuleName = "夜班后休息", Description = "夜班后次日必须休息" },
            ["9"] = new() { RuleType = "9", Priority = 1, IsCritical = true, RuleName = "中班后休息", Description = "中班后次日必须休息" },
            ["10"] = new() { RuleType = "10", Priority = 5, IsCritical = false, RuleName = "项目FL优先", Description = "优先分配本项目FL人员" }
        };
    }

    #endregion
}