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

namespace NPP.SmartSchedue.Api.Contracts.Services.Integration.Models
{
    /// <summary>
    /// 验证违规信息
    /// 通用的验证违规模型，用于各类验证场景
    /// </summary>
    public class ValidationViolation
    {
        /// <summary>
        /// 违规ID
        /// </summary>
        public string ViolationId { get; set; } = Guid.NewGuid().ToString();

        /// <summary>
        /// 违规类型
        /// </summary>
        public string ViolationType { get; set; } = string.Empty;

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

        /// <summary>
        /// 违规严重程度
        /// </summary>
        public ViolationSeverity Severity { get; set; } = ViolationSeverity.Medium;

        /// <summary>
        /// 相关实体ID
        /// </summary>
        public long EntityId { get; set; }

        /// <summary>
        /// 相关实体类型
        /// </summary>
        public string EntityType { get; set; } = string.Empty;

        /// <summary>
        /// 违规详细信息
        /// </summary>
        public Dictionary<string, object> Details { get; set; } = new();

        /// <summary>
        /// 建议解决方案
        /// </summary>
        public List<string> SuggestedSolutions { get; set; } = new();

        /// <summary>
        /// 发现时间
        /// </summary>
        public DateTime DetectedAt { get; set; } = DateTime.Now;

        /// <summary>
        /// 是否为阻塞性问题
        /// </summary>
        public bool IsBlockingIssue { get; set; } = false;

        /// <summary>
        /// 业务影响度 (1-10)
        /// </summary>
        public int BusinessImpact { get; set; } = 5;

        /// <summary>
        /// 违规分类
        /// </summary>
        public ViolationCategory Category { get; set; } = ViolationCategory.General;

        /// <summary>
        /// 是否可通过审批强制执行
        /// </summary>
        public bool CanOverrideWithApproval { get; set; } = true;

        /// <summary>
        /// 所需审批级别
        /// </summary>
        public ApprovalLevel RequiredApprovalLevel { get; set; } = ApprovalLevel.None;

        /// <summary>
        /// 违规风险评估
        /// </summary>
        public ViolationRiskAssessment RiskAssessment { get; set; } = new();
    }

    /// <summary>
    /// 验证警告信息
    /// 通用的验证警告模型，用于各类验证场景
    /// </summary>
    public class ValidationWarning
    {
        /// <summary>
        /// 警告ID
        /// </summary>
        public string WarningId { get; set; } = Guid.NewGuid().ToString();

        /// <summary>
        /// 警告类型
        /// </summary>
        public string WarningType { get; set; } = string.Empty;

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

        /// <summary>
        /// 警告级别
        /// </summary>
        public WarningLevel Level { get; set; } = WarningLevel.Medium;

        /// <summary>
        /// 相关实体ID
        /// </summary>
        public long EntityId { get; set; }

        /// <summary>
        /// 相关实体类型
        /// </summary>
        public string EntityType { get; set; } = string.Empty;

        /// <summary>
        /// 建议关注程度 (1-10)
        /// </summary>
        public int AttentionLevel { get; set; } = 5;

        /// <summary>
        /// 相关任务ID列表
        /// </summary>
        public List<long> RelatedTaskIds { get; set; } = new();

        /// <summary>
        /// 建议操作
        /// </summary>
        public string SuggestedAction { get; set; } = string.Empty;

        /// <summary>
        /// 发现时间
        /// </summary>
        public DateTime DetectedAt { get; set; } = DateTime.Now;
    }

    /// <summary>
    /// 约束违规信息
    /// 专门用于约束评估过程中的违规记录，比通用违规类更轻量
    /// </summary>
    public class ConstraintViolation
    {
        /// <summary>
        /// 违规ID
        /// </summary>
        public string ViolationId { get; set; } = Guid.NewGuid().ToString();

        /// <summary>
        /// 违规类型
        /// </summary>
        public string ViolationType { get; set; } = string.Empty;

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

        /// <summary>
        /// 违规严重程度
        /// </summary>
        public ViolationSeverity Severity { get; set; } = ViolationSeverity.Medium;

        /// <summary>
        /// 违规详细信息
        /// </summary>
        public Dictionary<string, object> Details { get; set; } = new();

        /// <summary>
        /// 发现时间
        /// </summary>
        public DateTime DetectedAt { get; set; } = DateTime.Now;

        /// <summary>
        /// 是否为阻塞性问题
        /// </summary>
        public bool IsBlockingIssue { get; set; } = false;

        /// <summary>
        /// 业务影响度 (1-10)
        /// </summary>
        public int BusinessImpact { get; set; } = 5;

        /// <summary>
        /// 违规分类
        /// </summary>
        public ViolationCategory Category { get; set; } = ViolationCategory.General;

        /// <summary>
        /// 是否可通过审批强制执行
        /// </summary>
        public bool CanOverrideWithApproval { get; set; } = true;

        /// <summary>
        /// 所需审批级别
        /// </summary>
        public ApprovalLevel RequiredApprovalLevel { get; set; } = ApprovalLevel.None;

        /// <summary>
        /// 建议解决方案
        /// </summary>
        public List<string> SuggestedSolutions { get; set; } = new();

        /// <summary>
        /// 违规风险评估
        /// </summary>
        public ViolationRiskAssessment RiskAssessment { get; set; } = new();

        /// <summary>
        /// 创建新的约束违规实例
        /// </summary>
        public static ConstraintViolation Create(string violationType, string description, ViolationSeverity severity = ViolationSeverity.Medium)
        {
            return new ConstraintViolation
            {
                ViolationType = violationType,
                Description = description,
                Severity = severity,
                DetectedAt = DateTime.Now
            };
        }

        /// <summary>
        /// 创建阻塞性违规
        /// </summary>
        public static ConstraintViolation CreateBlocking(string violationType, string description, ViolationSeverity severity = ViolationSeverity.High)
        {
            return new ConstraintViolation
            {
                ViolationType = violationType,
                Description = description,
                Severity = severity,
                IsBlockingIssue = true,
                DetectedAt = DateTime.Now
            };
        }
    }

    /// <summary>
    /// 违规类型枚举
    /// 定义人员分配过程中可能出现的各种违规类型
    /// </summary>
    public enum ViolationType
    {
        /// <summary>
        /// 通用违规
        /// </summary>
        General = 0,

        /// <summary>
        /// 资质不匹配
        /// 业务场景：人员资质与任务要求不符
        /// </summary>
        QualificationMismatch = 1,

        /// <summary>
        /// 时间冲突
        /// 业务场景：人员在同一时间段被分配多个任务
        /// </summary>
        TimeConflict = 2,

        /// <summary>
        /// 工作量超限
        /// 业务场景：人员工作负载超过限制
        /// </summary>
        WorkloadExceeded = 3,

        /// <summary>
        /// 班次规则冲突
        /// 业务场景：违反班次连续性、同天班次等规则
        /// </summary>
        ShiftRuleViolation = 4,

        /// <summary>
        /// 工作限制违规
        /// 业务场景：违反连续工作天数、周班次数等限制
        /// </summary>
        WorkLimitViolation = 5,

        /// <summary>
        /// 系统状态违规
        /// 业务场景：人员状态异常、系统配置问题等
        /// </summary>
        SystemStateViolation = 6,

        /// <summary>
        /// 业务规则冲突
        /// 业务场景：违反项目特定规则、部门限制等
        /// </summary>
        BusinessRuleViolation = 7
    }

    /// <summary>
    /// 违规严重程度枚举
    /// 定义违规的严重程度级别，用于决策和审批流程
    /// </summary>
    public enum ViolationSeverity
    {
        /// <summary>
        /// 信息级 - 纯信息提示，不影响分配
        /// 业务场景：建议性信息、优化提示、统计数据
        /// 处理方式：记录但不影响分配决策
        /// </summary>
        Info = 0,

        /// <summary>
        /// 低级 - 轻微问题，可接受
        /// 业务场景：次优选择、轻微偏好违背、资源利用率稍低
        /// 处理方式：允许分配，但降低优先级
        /// </summary>
        Low = 1,

        /// <summary>
        /// 警告级 - 需要关注但不阻止
        /// 业务场景：连续工作天数较多、工作负载偏高、非首选班次
        /// 处理方式：允许分配，但给出明确警告
        /// </summary>
        Warning = 2,

        /// <summary>
        /// 中级 - 需要关注的问题
        /// 业务场景：技能匹配度不理想、班次连续性问题、资源冲突风险
        /// 处理方式：默认阻止分配，可通过管理员审批
        /// </summary>
        Medium = 3,

        /// <summary>
        /// 高级 - 重要问题，建议阻止
        /// 业务场景：工作限制超出、重要资质缺失、严重时间冲突
        /// 处理方式：强烈建议阻止，需要高级权限审批
        /// </summary>
        High = 4,

        /// <summary>
        /// 错误级 - 业务规则违反，必须处理
        /// 业务场景：违反硬性约束、安全规定冲突、合规性问题
        /// 处理方式：阻止分配，必须修复后重试
        /// </summary>
        Error = 5,

        /// <summary>
        /// 严重级 - 系统级问题，完全阻止
        /// 业务场景：数据完整性问题、系统状态异常、关键资源不可用
        /// 处理方式：完全阻止分配，需要系统级修复
        /// </summary>
        Critical = 6
    }

    /// <summary>
    /// 警告级别枚举
    /// </summary>
    public enum WarningLevel
    {
        /// <summary>
        /// 低级警告
        /// </summary>
        Low = 1,

        /// <summary>
        /// 中级警告
        /// </summary>
        Medium = 2,

        /// <summary>
        /// 高级警告
        /// </summary>
        High = 3
    }

    /// <summary>
    /// 违规分类枚举
    /// </summary>
    public enum ViolationCategory
    {
        /// <summary>
        /// 通用违规
        /// </summary>
        General = 0,

        /// <summary>
        /// 资质相关违规
        /// </summary>
        Qualification = 1,

        /// <summary>
        /// 时间冲突违规
        /// </summary>
        TimeConflict = 2,

        /// <summary>
        /// 工作限制违规
        /// </summary>
        WorkLimit = 3,

        /// <summary>
        /// 班次规则违规
        /// </summary>
        ShiftRule = 4,

        /// <summary>
        /// 业务规则违规
        /// </summary>
        BusinessRule = 5,

        /// <summary>
        /// 安全规定违规
        /// </summary>
        Safety = 6,

        /// <summary>
        /// 合规性违规
        /// </summary>
        Compliance = 7,

        /// <summary>
        /// 系统状态违规
        /// </summary>
        SystemState = 8
    }

    /// <summary>
    /// 审批级别枚举
    /// </summary>
    public enum ApprovalLevel
    {
        /// <summary>
        /// 无需审批
        /// </summary>
        None = 0,

        /// <summary>
        /// 自动审批
        /// </summary>
        Automatic = 1,

        /// <summary>
        /// 主管审批
        /// </summary>
        Supervisor = 2,

        /// <summary>
        /// 管理员审批
        /// </summary>
        Manager = 3,

        /// <summary>
        /// 高级管理员审批
        /// </summary>
        SeniorManager = 4,

        /// <summary>
        /// 系统管理员审批
        /// </summary>
        SystemAdmin = 5
    }

    /// <summary>
    /// 违规风险评估
    /// </summary>
    public class ViolationRiskAssessment
    {
        /// <summary>
        /// 安全风险等级 (1-10)
        /// </summary>
        public int SafetyRiskLevel { get; set; } = 1;

        /// <summary>
        /// 合规风险等级 (1-10)
        /// </summary>
        public int ComplianceRiskLevel { get; set; } = 1;

        /// <summary>
        /// 运营风险等级 (1-10)
        /// </summary>
        public int OperationalRiskLevel { get; set; } = 1;

        /// <summary>
        /// 财务风险等级 (1-10)
        /// </summary>
        public int FinancialRiskLevel { get; set; } = 1;

        /// <summary>
        /// 综合风险评分 (1-10)
        /// </summary>
        public double OverallRiskScore => (SafetyRiskLevel + ComplianceRiskLevel + OperationalRiskLevel + FinancialRiskLevel) / 4.0;

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

        /// <summary>
        /// 缓解措施建议
        /// </summary>
        public List<string> MitigationSuggestions { get; set; } = new();
    }

    /// <summary>
    /// 违规严重程度判定辅助类
    /// 智能排班系统违规严重程度业务逻辑判定器
    /// 深度业务思考：根据不同业务场景智能判定违规的真实严重程度和处理方式
    /// </summary>
    public static class ViolationSeverityJudge
    {
        /// <summary>
        /// 判定是否为阻塞性违规
        /// 深度业务思考：根据严重程度和业务影响综合判断是否应该阻止分配
        /// </summary>
        public static bool IsBlockingViolation(ViolationSeverity severity, int businessImpact = 5, ViolationCategory category = ViolationCategory.General)
        {
            // 信息级和低级违规不阻塞
            if (severity <= ViolationSeverity.Low) return false;

            // 警告级违规根据业务影响和分类判断
            if (severity == ViolationSeverity.Warning)
            {
                // 安全和合规相关的警告需要阻塞
                if (category == ViolationCategory.Safety || category == ViolationCategory.Compliance)
                    return businessImpact >= 7;
                
                // 其他警告不阻塞
                return false;
            }

            // 中级违规根据分类判断
            if (severity == ViolationSeverity.Medium)
            {
                // 资质和安全相关的中级违规需要阻塞
                return category == ViolationCategory.Qualification || 
                       category == ViolationCategory.Safety || 
                       category == ViolationCategory.Compliance;
            }

            // 高级及以上违规都需要阻塞
            return severity >= ViolationSeverity.High;
        }

        /// <summary>
        /// 计算违规失败阈值
        /// 深度业务思考：不同业务场景下的违规容忍度不同
        /// </summary>
        public static ViolationSeverity GetFailureThreshold(ValidationContext context)
        {
            // 紧急情况下提高容忍度
            if (context.IsEmergencyMode)
                return ViolationSeverity.Error;

            // 关键任务降低容忍度  
            if (context.IsCriticalTask)
                return ViolationSeverity.Medium;

            // 安全相关任务严格控制
            if (context.IsSafetyRelated)
                return ViolationSeverity.Warning;

            // 默认阈值：高级违规
            return ViolationSeverity.High;
        }

        /// <summary>
        /// 获取所需审批级别
        /// </summary>
        public static ApprovalLevel GetRequiredApprovalLevel(ViolationSeverity severity, ViolationCategory category)
        {
            return (severity, category) switch
            {
                (ViolationSeverity.Info or ViolationSeverity.Low, _) => ApprovalLevel.None,
                (ViolationSeverity.Warning, ViolationCategory.Safety or ViolationCategory.Compliance) => ApprovalLevel.Supervisor,
                (ViolationSeverity.Warning, _) => ApprovalLevel.Automatic,
                (ViolationSeverity.Medium, ViolationCategory.Safety) => ApprovalLevel.Manager,
                (ViolationSeverity.Medium, _) => ApprovalLevel.Supervisor,
                (ViolationSeverity.High, ViolationCategory.Safety or ViolationCategory.Compliance) => ApprovalLevel.SeniorManager,
                (ViolationSeverity.High, _) => ApprovalLevel.Manager,
                (ViolationSeverity.Error, ViolationCategory.SystemState) => ApprovalLevel.SystemAdmin,
                (ViolationSeverity.Error, _) => ApprovalLevel.SeniorManager,
                (ViolationSeverity.Critical, _) => ApprovalLevel.SystemAdmin,
                _ => ApprovalLevel.None
            };
        }

        /// <summary>
        /// 判断是否可以通过审批强制执行
        /// </summary>
        public static bool CanOverrideWithApproval(ViolationSeverity severity, ViolationCategory category)
        {
            // 系统状态和关键安全违规不能强制执行
            if (category == ViolationCategory.SystemState && severity >= ViolationSeverity.Error)
                return false;

            if (category == ViolationCategory.Safety && severity >= ViolationSeverity.Critical)
                return false;

            // 严重级系统违规不能强制执行
            if (severity == ViolationSeverity.Critical && 
                (category == ViolationCategory.SystemState || category == ViolationCategory.Compliance))
                return false;

            return true;
        }

        /// <summary>
        /// 计算违规权重
        /// 用于验证评分计算
        /// </summary>
        public static double GetViolationWeight(ViolationSeverity severity)
        {
            return severity switch
            {
                ViolationSeverity.Info => 0.5,
                ViolationSeverity.Low => 1.0,
                ViolationSeverity.Warning => 2.0,
                ViolationSeverity.Medium => 5.0,
                ViolationSeverity.High => 10.0,
                ViolationSeverity.Error => 20.0,
                ViolationSeverity.Critical => 50.0,
                _ => 1.0
            };
        }
    }

    /// <summary>
    /// 验证上下文
    /// 用于判定违规严重程度的业务上下文
    /// </summary>
    public class ValidationContext
    {
        /// <summary>
        /// 是否为紧急模式
        /// </summary>
        public bool IsEmergencyMode { get; set; } = false;

        /// <summary>
        /// 是否为关键任务
        /// </summary>
        public bool IsCriticalTask { get; set; } = false;

        /// <summary>
        /// 是否与安全相关
        /// </summary>
        public bool IsSafetyRelated { get; set; } = false;

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

        /// <summary>
        /// 验证模式
        /// </summary>
        public ValidationMode Mode { get; set; } = ValidationMode.Standard;

        /// <summary>
        /// 额外上下文信息
        /// </summary>
        public Dictionary<string, object> AdditionalContext { get; set; } = new();
    }

    /// <summary>
    /// 验证模式枚举
    /// </summary>
    public enum ValidationMode
    {
        /// <summary>
        /// 标准验证
        /// </summary>
        Standard = 0,

        /// <summary>
        /// 严格验证
        /// </summary>
        Strict = 1,

        /// <summary>
        /// 宽松验证
        /// </summary>
        Lenient = 2,

        /// <summary>
        /// 紧急验证
        /// </summary>
        Emergency = 3
    }

    /// <summary>
    /// 优化评分结果
    /// 用于记录人员分配优化过程中的各项评分和决策信息
    /// </summary>
    public class OptimizationScoreResult
    {
        /// <summary>
        /// 候选人信息
        /// </summary>
        public object Candidate { get; set; }

        /// <summary>
        /// 各维度评分
        /// </summary>
        public Dictionary<string, double> DimensionScores { get; set; } = new();

        /// <summary>
        /// 优化总分
        /// </summary>
        public double OptimizationScore { get; set; }

        /// <summary>
        /// 置信度
        /// </summary>
        public double Confidence { get; set; }

        /// <summary>
        /// 推荐等级
        /// </summary>
        public RecommendationLevel RecommendationLevel { get; set; }

        /// <summary>
        /// 优化理由
        /// </summary>
        public string OptimizationReason { get; set; } = string.Empty;

        /// <summary>
        /// 风险评估
        /// </summary>
        public RiskAssessment RiskAssessment { get; set; } = new();
    }

    /// <summary>
    /// 推荐等级枚举
    /// </summary>
    public enum RecommendationLevel
    {
        /// <summary>
        /// 强烈推荐
        /// </summary>
        HighlyRecommended = 5,

        /// <summary>
        /// 推荐
        /// </summary>
        Recommended = 4,

        /// <summary>
        /// 可接受
        /// </summary>
        Acceptable = 3,

        /// <summary>
        /// 不推荐
        /// </summary>
        NotRecommended = 2,

        /// <summary>
        /// 不可行
        /// </summary>
        NotFeasible = 1
    }

    /// <summary>
    /// 风险评估
    /// </summary>
    public class RiskAssessment
    {
        /// <summary>
        /// 风险因子列表
        /// </summary>
        public List<RiskFactor> RiskFactors { get; set; } = new();

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

        /// <summary>
        /// 风险评分
        /// </summary>
        public double RiskScore { get; set; }

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

        /// <summary>
        /// 缓解建议
        /// </summary>
        public List<string> MitigationSuggestions { get; set; } = new();
    }

    /// <summary>
    /// 风险因子
    /// </summary>
    public class RiskFactor
    {
        /// <summary>
        /// 风险类型
        /// </summary>
        public string RiskType { get; set; } = string.Empty;

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

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

        /// <summary>
        /// 发生概率 (0-100)
        /// </summary>
        public double Probability { get; set; }

        /// <summary>
        /// 影响程度 (0-100)
        /// </summary>
        public double Impact { get; set; }
    }

    /// <summary>
    /// 决策评分
    /// </summary>
    public class DecisionScore
    {
        /// <summary>
        /// 最终评分
        /// </summary>
        public double FinalScore { get; set; }

        /// <summary>
        /// 置信度
        /// </summary>
        public double ConfidenceLevel { get; set; }

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

        /// <summary>
        /// 决策理由
        /// </summary>
        public string DecisionReason { get; set; } = string.Empty;
    }
}