using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;

namespace NPP.SmartSchedue.Api.Contracts.Services.Integration.Input
{
    /// <summary>
    /// 人员分配验证输入
    /// 用于智能分配系统中验证人员分配方案的可行性和合规性
    /// 支持批量验证、多维度检查和灵活配置
    /// </summary>
    public class PersonnelAllocationValidationInput
    {
        #region 核心验证数据

        /// <summary>
        /// 待验证的人员分配列表
        /// 包含任务与人员的具体分配关系
        /// </summary>
        [Required(ErrorMessage = "人员分配列表不能为空")]
        [MinLength(1, ErrorMessage = "至少需要一个分配项")]
        public List<PersonnelAssignment> Assignments { get; set; } = new();

        #endregion

        #region 验证配置选项

        /// <summary>
        /// 验证级别
        /// 控制验证的严格程度和覆盖范围
        /// </summary>
        public ValidationLevel ValidationLevel { get; set; } = ValidationLevel.Standard;

        /// <summary>
        /// 验证范围配置
        /// 可选择验证的具体维度
        /// </summary>
        public ValidationScopeConfig ValidationScope { get; set; } = new();

        /// <summary>
        /// 是否包含冲突检测
        /// 检测分配间的相互冲突
        /// </summary>
        public bool IncludeConflictDetection { get; set; } = true;

        /// <summary>
        /// 是否包含性能分析
        /// 分析验证对系统性能的影响
        /// </summary>
        public bool IncludePerformanceAnalysis { get; set; } = false;

        /// <summary>
        /// 验证超时时间（秒）
        /// 防止验证过程过长影响用户体验
        /// </summary>
        [Range(5, 300, ErrorMessage = "验证超时时间应在5-300秒之间")]
        public int ValidationTimeoutSeconds { get; set; } = 30;

        #endregion

        #region 业务上下文信息

        /// <summary>
        /// 验证请求来源
        /// 标识验证触发的业务场景
        /// </summary>
        public ValidationSource RequestSource { get; set; } = ValidationSource.Manual;

        /// <summary>
        /// 操作员信息
        /// 记录执行验证的用户
        /// </summary>
        public OperatorInfo Operator { get; set; } = new();

        /// <summary>
        /// 验证批次标识
        /// 用于关联和追踪验证过程
        /// </summary>
        public string ValidationBatchId { get; set; } = Guid.NewGuid().ToString();

        /// <summary>
        /// 业务场景标识
        /// 标识具体的业务使用场景
        /// </summary>
        public string BusinessScenario { get; set; } = string.Empty;

        #endregion

        #region 时间范围控制

        /// <summary>
        /// 验证基准日期
        /// 作为验证计算的基准时间点
        /// </summary>
        public DateTime ValidationBaseDate { get; set; } = DateTime.Now;

        /// <summary>
        /// 验证时间范围
        /// 限制验证的时间窗口
        /// </summary>
        public DateTimeRange ValidationTimeRange { get; set; } = new();

        /// <summary>
        /// 是否忽略历史数据
        /// 是否跳过已过时的分配验证
        /// </summary>
        public bool IgnoreHistoricalData { get; set; } = true;

        #endregion

        #region 自定义验证规则

        /// <summary>
        /// 自定义验证规则列表
        /// 支持业务特定的验证逻辑
        /// </summary>
        public List<CustomValidationRule> CustomRules { get; set; } = new();

        /// <summary>
        /// 验证权重配置
        /// 各类验证项的重要性权重
        /// </summary>
        public ValidationWeights Weights { get; set; } = new();

        /// <summary>
        /// 排除验证的项目
        /// 明确不需要验证的特定项目
        /// </summary>
        public List<string> ExcludedValidationTypes { get; set; } = new();

        #endregion

        #region 辅助方法

        /// <summary>
        /// 验证输入数据的完整性
        /// </summary>
        public ValidationInputCheckResult ValidateInput()
        {
            var result = new ValidationInputCheckResult { IsValid = true, Issues = new List<string>() };

            // 基础数据验证
            if (!Assignments.Any())
            {
                result.IsValid = false;
                result.Issues.Add("分配列表不能为空");
            }

            // 分配数据完整性检查
            foreach (var assignment in Assignments)
            {
                if (assignment.WorkOrderId <= 0)
                {
                    result.IsValid = false;
                    result.Issues.Add($"无效的工作任务ID: {assignment.WorkOrderId}");
                }

                if (assignment.PersonnelId <= 0)
                {
                    result.IsValid = false;
                    result.Issues.Add($"无效的人员ID: {assignment.PersonnelId}");
                }

                if (assignment.AssignmentDate == default)
                {
                    result.IsValid = false;
                    result.Issues.Add($"任务ID {assignment.WorkOrderId} 的分配日期无效");
                }
            }

            // 时间范围合理性检查
            if (ValidationTimeRange.IsValid() && ValidationTimeRange.EndDate < ValidationTimeRange.StartDate)
            {
                result.IsValid = false;
                result.Issues.Add("验证时间范围配置错误");
            }

            // 超时时间合理性检查
            if (ValidationTimeoutSeconds < 5 || ValidationTimeoutSeconds > 300)
            {
                result.IsValid = false;
                result.Issues.Add("验证超时时间配置超出有效范围");
            }

            return result;
        }

        /// <summary>
        /// 获取验证统计信息
        /// </summary>
        public ValidationInputStatistics GetStatistics()
        {
            return new ValidationInputStatistics
            {
                TotalAssignments = Assignments.Count,
                UniquePersonnelCount = Assignments.Select(a => a.PersonnelId).Distinct().Count(),
                UniqueTaskCount = Assignments.Select(a => a.WorkOrderId).Distinct().Count(),
                DateRangeSpan = Assignments.Any() 
                    ? (Assignments.Max(a => a.AssignmentDate) - Assignments.Min(a => a.AssignmentDate)).Days 
                    : 0,
                ValidationScopeCount = ValidationScope.GetEnabledScopeCount(),
                CustomRuleCount = CustomRules.Count,
                EstimatedExecutionTimeSeconds = EstimateExecutionTime()
            };
        }

        /// <summary>
        /// 估算验证执行时间
        /// </summary>
        private int EstimateExecutionTime()
        {
            // 基础验证时间（每个分配项约0.1秒）
            var baseTime = Assignments.Count * 0.1;
            
            // 冲突检测额外时间
            if (IncludeConflictDetection)
                baseTime += Assignments.Count * 0.05;
                
            // 性能分析额外时间
            if (IncludePerformanceAnalysis)
                baseTime += 2;
                
            // 自定义规则额外时间
            baseTime += CustomRules.Count * 0.2;

            return Math.Max(1, (int)Math.Ceiling(baseTime));
        }

        #endregion
    }

    #region 支持类定义

    /// <summary>
    /// 人员分配项
    /// 定义具体的任务-人员分配关系
    /// </summary>
    public class PersonnelAssignment
    {
        /// <summary>
        /// 工作任务ID
        /// </summary>
        [Required]
        [Range(1, long.MaxValue, ErrorMessage = "工作任务ID必须大于0")]
        public long WorkOrderId { get; set; }

        /// <summary>
        /// 人员ID
        /// </summary>
        [Required]
        [Range(1, long.MaxValue, ErrorMessage = "人员ID必须大于0")]
        public long PersonnelId { get; set; }

        /// <summary>
        /// 分配日期
        /// </summary>
        [Required]
        public DateTime AssignmentDate { get; set; }

        /// <summary>
        /// 班次ID
        /// </summary>
        public long? ShiftId { get; set; }

        /// <summary>
        /// 预计工作小时数
        /// </summary>
        [Range(0.1, 24, ErrorMessage = "预计工作小时数应在0.1-24之间")]
        public decimal EstimatedWorkHours { get; set; }

        /// <summary>
        /// 分配优先级
        /// 用于冲突时的优先级判断
        /// </summary>
        [Range(1, 10, ErrorMessage = "优先级应在1-10之间")]
        public int Priority { get; set; } = 5;

        /// <summary>
        /// 分配标签
        /// 用于分类和筛选
        /// </summary>
        public List<string> Tags { get; set; } = new();

        /// <summary>
        /// 备注信息
        /// </summary>
        [MaxLength(500, ErrorMessage = "备注信息不能超过500字符")]
        public string Remarks { get; set; } = string.Empty;

        /// <summary>
        /// 是否为强制分配
        /// 强制分配将跳过某些验证规则
        /// </summary>
        public bool IsMandatoryAssignment { get; set; } = false;
    }

    /// <summary>
    /// 验证级别枚举
    /// </summary>
    public enum ValidationLevel
    {
        /// <summary>
        /// 基础验证 - 仅检查最基本的约束
        /// </summary>
        Basic = 1,

        /// <summary>
        /// 标准验证 - 包含常用的验证规则
        /// </summary>
        Standard = 2,

        /// <summary>
        /// 严格验证 - 全面的验证检查
        /// </summary>
        Strict = 3,

        /// <summary>
        /// 自定义验证 - 根据配置执行验证
        /// </summary>
        Custom = 4
    }

    /// <summary>
    /// 验证范围配置
    /// 控制具体验证的维度
    /// </summary>
    public class ValidationScopeConfig
    {
        /// <summary>
        /// 验证资质匹配
        /// </summary>
        public bool ValidateQualification { get; set; } = true;

        /// <summary>
        /// 验证时间冲突
        /// </summary>
        public bool ValidateTimeConflict { get; set; } = true;

        /// <summary>
        /// 验证工作限制
        /// </summary>
        public bool ValidateWorkLimit { get; set; } = true;

        /// <summary>
        /// 验证班次规则
        /// </summary>
        public bool ValidateShiftRule { get; set; } = true;

        /// <summary>
        /// 验证负载均衡
        /// </summary>
        public bool ValidateLoadBalance { get; set; } = false;

        /// <summary>
        /// 验证技能匹配
        /// </summary>
        public bool ValidateSkillMatch { get; set; } = false;

        /// <summary>
        /// 验证成本控制
        /// </summary>
        public bool ValidateCostControl { get; set; } = false;

        /// <summary>
        /// 获取启用的验证范围数量
        /// </summary>
        public int GetEnabledScopeCount()
        {
            int count = 0;
            if (ValidateQualification) count++;
            if (ValidateTimeConflict) count++;
            if (ValidateWorkLimit) count++;
            if (ValidateShiftRule) count++;
            if (ValidateLoadBalance) count++;
            if (ValidateSkillMatch) count++;
            if (ValidateCostControl) count++;
            return count;
        }
    }

    /// <summary>
    /// 验证来源枚举
    /// </summary>
    public enum ValidationSource
    {
        /// <summary>
        /// 手动验证
        /// </summary>
        Manual = 1,

        /// <summary>
        /// 自动验证
        /// </summary>
        Automatic = 2,

        /// <summary>
        /// 批量验证
        /// </summary>
        Batch = 3,

        /// <summary>
        /// 定时验证
        /// </summary>
        Scheduled = 4,

        /// <summary>
        /// API调用验证
        /// </summary>
        ApiCall = 5
    }

    /// <summary>
    /// 操作员信息
    /// </summary>
    public class OperatorInfo
    {
        /// <summary>
        /// 操作员ID
        /// </summary>
        public long OperatorId { get; set; }

        /// <summary>
        /// 操作员姓名
        /// </summary>
        public string OperatorName { get; set; } = string.Empty;

        /// <summary>
        /// 操作时间
        /// </summary>
        public DateTime OperationTime { get; set; } = DateTime.Now;

        /// <summary>
        /// 操作IP地址
        /// </summary>
        public string IpAddress { get; set; } = string.Empty;

        /// <summary>
        /// 操作角色
        /// </summary>
        public string Role { get; set; } = string.Empty;
    }

    /// <summary>
    /// 日期时间范围
    /// </summary>
    public class DateTimeRange
    {
        /// <summary>
        /// 开始时间
        /// </summary>
        public DateTime StartDate { get; set; }

        /// <summary>
        /// 结束时间
        /// </summary>
        public DateTime EndDate { get; set; }

        /// <summary>
        /// 是否为有效的时间范围
        /// </summary>
        public bool IsValid()
        {
            return StartDate != default && EndDate != default && StartDate <= EndDate;
        }

        /// <summary>
        /// 获取时间跨度（天数）
        /// </summary>
        public int GetDaySpan()
        {
            return IsValid() ? (EndDate - StartDate).Days : 0;
        }
    }

    /// <summary>
    /// 自定义验证规则
    /// </summary>
    public class CustomValidationRule
    {
        /// <summary>
        /// 规则ID
        /// </summary>
        public string RuleId { get; set; } = string.Empty;

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

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

        /// <summary>
        /// 规则配置参数
        /// </summary>
        public Dictionary<string, object> Parameters { get; set; } = new();

        /// <summary>
        /// 规则权重
        /// </summary>
        [Range(0.1, 10.0, ErrorMessage = "规则权重应在0.1-10.0之间")]
        public double Weight { get; set; } = 1.0;

        /// <summary>
        /// 是否启用
        /// </summary>
        public bool IsEnabled { get; set; } = true;
    }

    /// <summary>
    /// 验证权重配置
    /// </summary>
    public class ValidationWeights
    {
        /// <summary>
        /// 资质验证权重
        /// </summary>
        [Range(0.0, 10.0)]
        public double QualificationWeight { get; set; } = 1.0;

        /// <summary>
        /// 时间冲突验证权重
        /// </summary>
        [Range(0.0, 10.0)]
        public double TimeConflictWeight { get; set; } = 1.0;

        /// <summary>
        /// 工作限制验证权重
        /// </summary>
        [Range(0.0, 10.0)]
        public double WorkLimitWeight { get; set; } = 1.0;

        /// <summary>
        /// 班次规则验证权重
        /// </summary>
        [Range(0.0, 10.0)]
        public double ShiftRuleWeight { get; set; } = 0.8;

        /// <summary>
        /// 负载均衡验证权重
        /// </summary>
        [Range(0.0, 10.0)]
        public double LoadBalanceWeight { get; set; } = 0.6;

        /// <summary>
        /// 技能匹配验证权重
        /// </summary>
        [Range(0.0, 10.0)]
        public double SkillMatchWeight { get; set; } = 0.7;
    }

    /// <summary>
    /// 验证输入检查结果
    /// </summary>
    public class ValidationInputCheckResult
    {
        /// <summary>
        /// 输入是否有效
        /// </summary>
        public bool IsValid { get; set; }

        /// <summary>
        /// 问题列表
        /// </summary>
        public List<string> Issues { get; set; } = new();
    }

    /// <summary>
    /// 验证输入统计信息
    /// </summary>
    public class ValidationInputStatistics
    {
        /// <summary>
        /// 总分配数量
        /// </summary>
        public int TotalAssignments { get; set; }

        /// <summary>
        /// 唯一人员数量
        /// </summary>
        public int UniquePersonnelCount { get; set; }

        /// <summary>
        /// 唯一任务数量
        /// </summary>
        public int UniqueTaskCount { get; set; }

        /// <summary>
        /// 日期范围跨度（天）
        /// </summary>
        public int DateRangeSpan { get; set; }

        /// <summary>
        /// 验证范围数量
        /// </summary>
        public int ValidationScopeCount { get; set; }

        /// <summary>
        /// 自定义规则数量
        /// </summary>
        public int CustomRuleCount { get; set; }

        /// <summary>
        /// 预估执行时间（秒）
        /// </summary>
        public int EstimatedExecutionTimeSeconds { get; set; }
    }

    #endregion
}