using System;
using System.Collections.Generic;
using System.Linq;
using NPP.SmartSchedue.Api.Contracts.Services.Integration.Models;

namespace NPP.SmartSchedue.Api.Contracts.Services.Integration.Output
{
    /// <summary>
    /// 人员分配验证结果
    /// 智能分配系统验证阶段的完整结果数据模型
    /// 包含验证状态、违规详情、统计分析、改进建议等全面信息
    /// </summary>
    public class PersonnelAllocationValidationResult
    {
        #region 核心验证结果

        /// <summary>
        /// 验证是否通过
        /// 整体验证结果的最终判定
        /// </summary>
        public bool IsValid { get; set; }

        /// <summary>
        /// 验证通过的分配数量
        /// </summary>
        public int PassedAssignmentCount { get; set; }

        /// <summary>
        /// 验证失败的分配数量
        /// </summary>
        public int FailedAssignmentCount { get; set; }

        /// <summary>
        /// 总分配数量
        /// </summary>
        public int TotalAssignmentCount => PassedAssignmentCount + FailedAssignmentCount;

        /// <summary>
        /// 验证通过率 (0-100)
        /// </summary>
        public double PassRate => TotalAssignmentCount > 0 
            ? (double)PassedAssignmentCount / TotalAssignmentCount * 100 
            : 0;

        #endregion

        #region 详细验证信息

        /// <summary>
        /// 验证违规列表
        /// 记录所有未通过验证的具体问题
        /// </summary>
        public List<ValidationViolation> Violations { get; set; } = new();

        /// <summary>
        /// 验证警告列表
        /// 记录潜在风险和建议关注的问题
        /// </summary>
        public List<ValidationWarning> Warnings { get; set; } = new();

        /// <summary>
        /// 验证详细结果列表
        /// 每个分配项的具体验证结果
        /// </summary>
        public List<AssignmentValidationDetail> ValidationDetails { get; set; } = new();

        #endregion

        #region 质量评估指标

        /// <summary>
        /// 验证质量评分 (0-100)
        /// 综合评估验证结果的质量水平
        /// </summary>
        public double ValidationScore { get; set; }

        /// <summary>
        /// 验证置信度 (0-100)
        /// 对验证结果准确性的信心程度
        /// </summary>
        public double ConfidenceLevel { get; set; }

        /// <summary>
        /// 风险等级
        /// </summary>
        public ValidationRiskLevel RiskLevel { get; set; } = ValidationRiskLevel.Low;

        /// <summary>
        /// 业务影响评估
        /// </summary>
        public BusinessImpactAssessment BusinessImpact { get; set; } = new();

        #endregion

        #region 统计分析数据

        /// <summary>
        /// 验证统计信息
        /// 各类验证项的统计汇总
        /// </summary>
        public ValidationStatistics Statistics { get; set; } = new();

        /// <summary>
        /// 违规类型分布
        /// Key: 违规类型, Value: 出现次数
        /// </summary>
        public Dictionary<string, int> ViolationTypeDistribution => AnalyzeViolationDistribution();

        /// <summary>
        /// 人员验证通过率分析
        /// Key: 人员ID, Value: 通过率
        /// </summary>
        public Dictionary<long, double> PersonnelPassRateAnalysis => AnalyzePersonnelPassRate();

        /// <summary>
        /// 任务验证难度分析
        /// Key: 任务ID, Value: 验证难度评分
        /// </summary>
        public Dictionary<long, double> TaskValidationDifficultyAnalysis => AnalyzeTaskDifficulty();

        #endregion

        #region 验证执行信息

        /// <summary>
        /// 验证执行开始时间
        /// </summary>
        public DateTime ValidationStartTime { get; set; }

        /// <summary>
        /// 验证执行结束时间
        /// </summary>
        public DateTime ValidationEndTime { get; set; }

        /// <summary>
        /// 验证执行耗时（毫秒）
        /// </summary>
        public long ExecutionTimeMs => (ValidationEndTime - ValidationStartTime).Ticks / TimeSpan.TicksPerMillisecond;

        /// <summary>
        /// 验证批次ID
        /// </summary>
        public string ValidationBatchId { get; set; } = string.Empty;

        /// <summary>
        /// 验证器版本
        /// </summary>
        public string ValidatorVersion { get; set; } = "1.0.0";

        #endregion

        #region 改进建议和报告

        /// <summary>
        /// 验证报告摘要
        /// 人性化的验证结果描述
        /// </summary>
        public string ValidationReport { get; set; } = string.Empty;

        /// <summary>
        /// 改进建议列表
        /// 针对验证问题的具体改进建议
        /// </summary>
        public List<ImprovementSuggestion> ImprovementSuggestions { get; set; } = new();

        /// <summary>
        /// 后续行动建议
        /// 基于验证结果的下一步操作建议
        /// </summary>
        public List<ActionRecommendation> ActionRecommendations { get; set; } = new();

        /// <summary>
        /// 关键问题摘要
        /// 最重要的验证问题汇总
        /// </summary>
        public List<string> CriticalIssuesSummary { get; set; } = new();

        #endregion

        #region 性能和监控数据

        /// <summary>
        /// 性能监控指标
        /// 验证过程的性能数据
        /// </summary>
        public Dictionary<string, object> PerformanceMetrics { get; set; } = new();

        /// <summary>
        /// 资源使用统计
        /// </summary>
        public ResourceUsageStatistics ResourceUsage { get; set; } = new();

        /// <summary>
        /// 验证缓存命中统计
        /// </summary>
        public CacheStatistics CacheStatistics { get; set; } = new();

        #endregion

        #region 辅助分析方法

        /// <summary>
        /// 分析违规类型分布
        /// </summary>
        private Dictionary<string, int> AnalyzeViolationDistribution()
        {
            return Violations
                .GroupBy(v => v.ViolationType)
                .ToDictionary(g => g.Key, g => g.Count());
        }

        /// <summary>
        /// 分析人员验证通过率
        /// </summary>
        private Dictionary<long, double> AnalyzePersonnelPassRate()
        {
            var personnelStats = ValidationDetails
                .GroupBy(d => d.PersonnelId)
                .ToDictionary(
                    g => g.Key,
                    g => g.Count(d => d.IsValid) / (double)g.Count() * 100
                );

            return personnelStats;
        }

        /// <summary>
        /// 分析任务验证难度
        /// </summary>
        private Dictionary<long, double> AnalyzeTaskDifficulty()
        {
            var taskDifficulty = ValidationDetails
                .GroupBy(d => d.WorkOrderId)
                .ToDictionary(
                    g => g.Key,
                    g => {
                        var details = g.ToList();
                        var failureRate = details.Count(d => !d.IsValid) / (double)details.Count();
                        var avgViolationCount = details.Average(d => d.ViolationCount);
                        return Math.Round((failureRate * 50) + (avgViolationCount * 10), 1);
                    }
                );

            return taskDifficulty;
        }

        /// <summary>
        /// 获取验证摘要信息
        /// </summary>
        public ValidationSummary GetValidationSummary()
        {
            return new ValidationSummary
            {
                IsValid = IsValid,
                PassRate = PassRate,
                TotalAssignments = TotalAssignmentCount,
                CriticalViolations = Violations.Count(v => v.Severity == ViolationSeverity.Critical),
                HighViolations = Violations.Count(v => v.Severity == ViolationSeverity.High),
                MediumViolations = Violations.Count(v => v.Severity == ViolationSeverity.Medium),
                LowViolations = Violations.Count(v => v.Severity == ViolationSeverity.Low),
                WarningCount = Warnings.Count,
                ExecutionTimeMs = ExecutionTimeMs,
                ValidationScore = ValidationScore,
                RiskLevel = RiskLevel
            };
        }

        /// <summary>
        /// 检查是否存在阻塞性问题
        /// </summary>
        public bool HasBlockingIssues()
        {
            return Violations.Any(v => v.Severity >= ViolationSeverity.High && v.IsBlockingIssue);
        }

        /// <summary>
        /// 获取最高优先级的违规问题
        /// </summary>
        public List<ValidationViolation> GetHighPriorityViolations()
        {
            return Violations
                .Where(v => v.Severity >= ViolationSeverity.High)
                .OrderByDescending(v => v.Severity)
                .ThenByDescending(v => v.BusinessImpact)
                .ToList();
        }

        /// <summary>
        /// 生成验证结果健康评分
        /// </summary>
        public ValidationHealthScore CalculateHealthScore()
        {
            var score = new ValidationHealthScore();
            
            // 基础通过率评分
            score.PassRateScore = PassRate;
            
            // 违规严重程度扣分
            score.ViolationImpactScore = 100 - Violations
                .Sum(v => (int)v.Severity * v.BusinessImpact) / Math.Max(1, Violations.Count);
            
            // 性能评分
            score.PerformanceScore = ExecutionTimeMs < 5000 ? 100 : Math.Max(0, 100 - (ExecutionTimeMs - 5000) / 100);
            
            // 综合评分
            score.OverallScore = (score.PassRateScore * 0.5 + score.ViolationImpactScore * 0.3 + score.PerformanceScore * 0.2);
            
            return score;
        }

        #endregion
    }

    #region 支持类定义

    /// <summary>
    /// 人员分配验证违规信息
    /// 继承自通用ValidationViolation，增加人员分配特定字段
    /// </summary>
    public class PersonnelAllocationViolation : ValidationViolation
    {
        /// <summary>
        /// 工作任务ID
        /// </summary>
        public long WorkOrderId { get; set; }

        /// <summary>
        /// 人员ID
        /// </summary>
        public long PersonnelId { get; set; }


        /// <summary>
        /// 违规规则ID
        /// </summary>
        public string RuleId { get; set; } = string.Empty;

        /// <summary>
        /// 违规规则名称
        /// </summary>
        public string RuleName { get; set; } = string.Empty;
    }

    /// <summary>
    /// 人员分配验证警告信息
    /// 继承自通用ValidationWarning，增加人员分配特定字段
    /// </summary>
    public class PersonnelAllocationWarning : ValidationWarning
    {
        /// <summary>
        /// 工作任务ID
        /// </summary>
        public long WorkOrderId { get; set; }

        /// <summary>
        /// 人员ID
        /// </summary>
        public long PersonnelId { get; set; }

        /// <summary>
        /// 警告描述
        /// </summary>
        public string Description { get; set; } = string.Empty;

        /// <summary>
        /// 潜在风险描述
        /// </summary>
        public string PotentialRisk { get; set; } = string.Empty;

        /// <summary>
        /// 预防建议
        /// </summary>
        public List<string> PreventionSuggestions { get; set; } = new();
    }

    /// <summary>
    /// 分配验证详情
    /// </summary>
    public class AssignmentValidationDetail
    {
        /// <summary>
        /// 工作任务ID
        /// </summary>
        public long WorkOrderId { get; set; }

        /// <summary>
        /// 人员ID
        /// </summary>
        public long PersonnelId { get; set; }

        /// <summary>
        /// 该分配项是否验证通过
        /// </summary>
        public bool IsValid { get; set; }

        /// <summary>
        /// 违规数量
        /// </summary>
        public int ViolationCount { get; set; }

        /// <summary>
        /// 警告数量
        /// </summary>
        public int WarningCount { get; set; }

        /// <summary>
        /// 验证评分 (0-100)
        /// </summary>
        public double ValidationScore { get; set; }

        /// <summary>
        /// 验证耗时（毫秒）
        /// </summary>
        public long ValidationTimeMs { get; set; }

        /// <summary>
        /// 验证的具体项目
        /// </summary>
        public List<ValidationItem> ValidationItems { get; set; } = new();

        /// <summary>
        /// 验证状态
        /// </summary>
        public string ValidationStatus { get; set; } = string.Empty;

        /// <summary>
        /// 验证备注
        /// </summary>
        public string Remarks { get; set; } = string.Empty;
    }

    /// <summary>
    /// 验证项
    /// </summary>
    public class ValidationItem
    {
        /// <summary>
        /// 验证项名称
        /// </summary>
        public string ItemName { get; set; } = string.Empty;

        /// <summary>
        /// 验证结果
        /// </summary>
        public bool IsValid { get; set; }

        /// <summary>
        /// 验证消息
        /// </summary>
        public string Message { get; set; } = string.Empty;

        /// <summary>
        /// 验证耗时（毫秒）
        /// </summary>
        public long ExecutionTimeMs { get; set; }
    }

    /// <summary>
    /// 业务影响评估
    /// </summary>
    public class BusinessImpactAssessment
    {
        /// <summary>
        /// 对生产效率的影响 (1-10)
        /// </summary>
        public int ProductionEfficiencyImpact { get; set; }

        /// <summary>
        /// 对成本控制的影响 (1-10)
        /// </summary>
        public int CostControlImpact { get; set; }

        /// <summary>
        /// 对质量管控的影响 (1-10)
        /// </summary>
        public int QualityControlImpact { get; set; }

        /// <summary>
        /// 对安全管理的影响 (1-10)
        /// </summary>
        public int SafetyManagementImpact { get; set; }

        /// <summary>
        /// 对合规性的影响 (1-10)
        /// </summary>
        public int ComplianceImpact { get; set; }

        /// <summary>
        /// 综合业务影响评分 (1-10)
        /// </summary>
        public double OverallBusinessImpact => 
            (ProductionEfficiencyImpact + CostControlImpact + QualityControlImpact + 
             SafetyManagementImpact + ComplianceImpact) / 5.0;
    }

    /// <summary>
    /// 验证统计信息
    /// </summary>
    public class ValidationStatistics
    {
        /// <summary>
        /// 资质验证统计
        /// </summary>
        public ValidationTypeStatistics QualificationValidation { get; set; } = new();

        /// <summary>
        /// 时间冲突验证统计
        /// </summary>
        public ValidationTypeStatistics TimeConflictValidation { get; set; } = new();

        /// <summary>
        /// 工作限制验证统计
        /// </summary>
        public ValidationTypeStatistics WorkLimitValidation { get; set; } = new();

        /// <summary>
        /// 班次规则验证统计
        /// </summary>
        public ValidationTypeStatistics ShiftRuleValidation { get; set; } = new();

        /// <summary>
        /// 自定义规则验证统计
        /// </summary>
        public ValidationTypeStatistics CustomRuleValidation { get; set; } = new();
    }

    /// <summary>
    /// 验证类型统计
    /// </summary>
    public class ValidationTypeStatistics
    {
        /// <summary>
        /// 验证项总数
        /// </summary>
        public int TotalCount { get; set; }

        /// <summary>
        /// 通过数量
        /// </summary>
        public int PassedCount { get; set; }

        /// <summary>
        /// 失败数量
        /// </summary>
        public int FailedCount { get; set; }

        /// <summary>
        /// 跳过数量
        /// </summary>
        public int SkippedCount { get; set; }

        /// <summary>
        /// 通过率 (0-100)
        /// </summary>
        public double PassRate => TotalCount > 0 ? (double)PassedCount / TotalCount * 100 : 0;

        /// <summary>
        /// 平均验证耗时（毫秒）
        /// </summary>
        public double AverageExecutionTimeMs { get; set; }
    }

    /// <summary>
    /// 改进建议
    /// </summary>
    public class ImprovementSuggestion
    {
        /// <summary>
        /// 建议ID
        /// </summary>
        public string SuggestionId { get; set; } = Guid.NewGuid().ToString();

        /// <summary>
        /// 建议类型
        /// </summary>
        public SuggestionType Type { get; set; } = SuggestionType.Process;

        /// <summary>
        /// 建议标题
        /// </summary>
        public string Title { get; set; } = string.Empty;

        /// <summary>
        /// 建议描述
        /// </summary>
        public string Description { get; set; } = string.Empty;

        /// <summary>
        /// 优先级 (1-10)
        /// </summary>
        public int Priority { get; set; } = 5;

        /// <summary>
        /// 预期收益描述
        /// </summary>
        public string ExpectedBenefit { get; set; } = string.Empty;

        /// <summary>
        /// 实施难度 (1-10)
        /// </summary>
        public int ImplementationDifficulty { get; set; } = 5;

        /// <summary>
        /// 相关的违规ID列表
        /// </summary>
        public List<string> RelatedViolationIds { get; set; } = new();
    }

    /// <summary>
    /// 行动建议
    /// </summary>
    public class ActionRecommendation
    {
        /// <summary>
        /// 行动类型
        /// </summary>
        public ActionType ActionType { get; set; } = ActionType.Review;

        /// <summary>
        /// 行动描述
        /// </summary>
        public string Description { get; set; } = string.Empty;

        /// <summary>
        /// 紧急程度 (1-10)
        /// </summary>
        public int UrgencyLevel { get; set; } = 5;

        /// <summary>
        /// 建议执行时间
        /// </summary>
        public DateTime RecommendedExecutionTime { get; set; }

        /// <summary>
        /// 负责人角色
        /// </summary>
        public string ResponsibleRole { get; set; } = string.Empty;
    }

    /// <summary>
    /// 资源使用统计
    /// </summary>
    public class ResourceUsageStatistics
    {
        /// <summary>
        /// 峰值内存使用（字节）
        /// </summary>
        public long PeakMemoryUsageBytes { get; set; }

        /// <summary>
        /// CPU使用时间（毫秒）
        /// </summary>
        public long CpuTimeMs { get; set; }

        /// <summary>
        /// 数据库查询次数
        /// </summary>
        public int DatabaseQueryCount { get; set; }

        /// <summary>
        /// 缓存查询次数
        /// </summary>
        public int CacheQueryCount { get; set; }

        /// <summary>
        /// 网络请求次数
        /// </summary>
        public int NetworkRequestCount { get; set; }
    }

    /// <summary>
    /// 缓存统计
    /// </summary>
    public class CacheStatistics
    {
        /// <summary>
        /// 缓存命中次数
        /// </summary>
        public int HitCount { get; set; }

        /// <summary>
        /// 缓存未命中次数
        /// </summary>
        public int MissCount { get; set; }

        /// <summary>
        /// 缓存命中率 (0-100)
        /// </summary>
        public double HitRate => (HitCount + MissCount) > 0 
            ? (double)HitCount / (HitCount + MissCount) * 100 
            : 0;

        /// <summary>
        /// 缓存更新次数
        /// </summary>
        public int UpdateCount { get; set; }

        /// <summary>
        /// 缓存清理次数
        /// </summary>
        public int EvictionCount { get; set; }
    }

    /// <summary>
    /// 验证摘要
    /// </summary>
    public class ValidationSummary
    {
        public bool IsValid { get; set; }
        public double PassRate { get; set; }
        public int TotalAssignments { get; set; }
        public int CriticalViolations { get; set; }
        public int HighViolations { get; set; }
        public int MediumViolations { get; set; }
        public int LowViolations { get; set; }
        public int WarningCount { get; set; }
        public long ExecutionTimeMs { get; set; }
        public double ValidationScore { get; set; }
        public ValidationRiskLevel RiskLevel { get; set; }
    }

    /// <summary>
    /// 验证健康评分
    /// </summary>
    public class ValidationHealthScore
    {
        /// <summary>
        /// 通过率评分 (0-100)
        /// </summary>
        public double PassRateScore { get; set; }

        /// <summary>
        /// 违规影响评分 (0-100)
        /// </summary>
        public double ViolationImpactScore { get; set; }

        /// <summary>
        /// 性能评分 (0-100)
        /// </summary>
        public double PerformanceScore { get; set; }

        /// <summary>
        /// 综合评分 (0-100)
        /// </summary>
        public double OverallScore { get; set; }

        /// <summary>
        /// 健康等级
        /// </summary>
        public HealthGrade Grade => DetermineGrade();

        /// <summary>
        /// 确定健康等级
        /// </summary>
        private HealthGrade DetermineGrade()
        {
            if (OverallScore >= 90) return HealthGrade.Excellent;
            if (OverallScore >= 80) return HealthGrade.Good;
            if (OverallScore >= 70) return HealthGrade.Fair;
            if (OverallScore >= 60) return HealthGrade.Poor;
            return HealthGrade.Critical;
        }
    }

    #endregion

    #region 枚举定义


    /// <summary>
    /// 验证风险等级枚举
    /// </summary>
    public enum ValidationRiskLevel
    {
        /// <summary>
        /// 低风险
        /// </summary>
        Low = 1,

        /// <summary>
        /// 中风险
        /// </summary>
        Medium = 2,

        /// <summary>
        /// 高风险
        /// </summary>
        High = 3,

        /// <summary>
        /// 极高风险
        /// </summary>
        Critical = 4
    }

    /// <summary>
    /// 建议类型枚举
    /// </summary>
    public enum SuggestionType
    {
        /// <summary>
        /// 流程改进
        /// </summary>
        Process = 1,

        /// <summary>
        /// 系统配置
        /// </summary>
        Configuration = 2,

        /// <summary>
        /// 人员培训
        /// </summary>
        Training = 3,

        /// <summary>
        /// 技术升级
        /// </summary>
        Technology = 4,

        /// <summary>
        /// 政策调整
        /// </summary>
        Policy = 5
    }

    /// <summary>
    /// 行动类型枚举
    /// </summary>
    public enum ActionType
    {
        /// <summary>
        /// 立即处理
        /// </summary>
        Immediate = 1,

        /// <summary>
        /// 审查复核
        /// </summary>
        Review = 2,

        /// <summary>
        /// 计划改进
        /// </summary>
        Improve = 3,

        /// <summary>
        /// 监控观察
        /// </summary>
        Monitor = 4,

        /// <summary>
        /// 忽略接受
        /// </summary>
        Accept = 5
    }

    /// <summary>
    /// 健康等级枚举
    /// </summary>
    public enum HealthGrade
    {
        /// <summary>
        /// 危险
        /// </summary>
        Critical = 1,

        /// <summary>
        /// 差
        /// </summary>
        Poor = 2,

        /// <summary>
        /// 一般
        /// </summary>
        Fair = 3,

        /// <summary>
        /// 良好
        /// </summary>
        Good = 4,

        /// <summary>
        /// 优秀
        /// </summary>
        Excellent = 5
    }

    #endregion
}