using FreeSql;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using NPP.SmartSchedue.Api.Contracts.Core.Enums;
using NPP.SmartSchedue.Api.Contracts.Domain.Integration;
using NPP.SmartSchedue.Api.Contracts.Domain.Work;
using NPP.SmartSchedue.Api.Contracts.Services.Integration.Input;
using NPP.SmartSchedue.Api.Contracts.Services.Integration.Output;
using NPP.SmartSchedue.Api.Repositories.Work;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using ZhonTai.Admin.Services;
using ZhonTai.DynamicApi;
using ZhonTai.DynamicApi.Attributes;

namespace NPP.SmartSchedue.Api.Services.Integration
{
    /// <summary>
    /// 任务分配修改服务
    /// 专门处理任务人员分配的修改操作
    /// 深度业务思考：实现分配结果的精确修改，确保数据一致性和业务完整性
    /// </summary>
    [DynamicApi(Area = "app")]
    public class TaskAssignmentModificationService : BaseService, IDynamicApi
    {
        private readonly IIntegrationRecordRepository _integrationRecordRepository;
        private readonly WorkOrderRepository _workOrderRepository;
        private readonly ILogger<TaskAssignmentModificationService> _logger;

        public TaskAssignmentModificationService(
            IIntegrationRecordRepository integrationRecordRepository,
            WorkOrderRepository workOrderRepository,
            ILogger<TaskAssignmentModificationService> logger)
        {
            _integrationRecordRepository = integrationRecordRepository;
            _workOrderRepository = workOrderRepository;
            _logger = logger;
        }

        /// <summary>
        /// 修改任务人员分配
        /// 深度业务思考：根据选中的人员精确修改任务分配，同时保持整合记录的一致性
        /// 核心功能：
        /// 1. 根据选中的人员修改任务的指定人员ID和姓名
        /// 2. 更新整合记录的修改状态和备注
        /// 3. 记录修改历史和审计信息
        /// </summary>
        [HttpPost]
        public async Task<TaskAssignmentModificationResult> ModifyTaskAssignmentAsync(TaskAssignmentModificationInput input)
        {
            var result = new TaskAssignmentModificationResult
            {
                StartTime = DateTime.Now,
                IsSuccess = false
            };

            try
            {
                _logger.LogInformation("开始修改任务人员分配: IntegrationRecordId={IntegrationRecordId}, TaskCount={TaskCount}",
                    input.IntegrationRecordId, input.TaskAssignmentModifications.Count);

                // 第一步：验证整合记录存在性
                var integrationRecord = await ValidateIntegrationRecordAsync(input.IntegrationRecordId);
                if (integrationRecord == null)
                {
                    result.ErrorMessage = $"未找到ID为{input.IntegrationRecordId}的整合记录";
                    return result;
                }

                result.IntegrationBatchCode = integrationRecord.IntegrationBatchCode;

                // 第二步：获取和验证任务
                var validationResult = await ValidateAndGetTasksAsync(input.TaskAssignmentModifications);
                if (!validationResult.IsValid)
                {
                    result.ErrorMessage = validationResult.ErrorMessage;
                    result.ValidationErrors = validationResult.ValidationErrors;
                    return result;
                }

                var tasks = validationResult.Tasks;
                result.TotalTaskCount = tasks.Count;

                // 第三步：执行任务分配修改
                var modificationResults = await ExecuteTaskAssignmentModificationsAsync(
                    tasks, 
                    input.TaskAssignmentModifications, 
                    input.OperatorUserId, 
                    input.OperatorUserName);

                result.SuccessfulModifications = modificationResults.SuccessfulModifications;
                result.FailedModifications = modificationResults.FailedModifications;
                result.SuccessfulCount = modificationResults.SuccessfulModifications.Count;
                result.FailedCount = modificationResults.FailedModifications.Count;

                // 第四步：更新整合记录
                await UpdateIntegrationRecordAsync(integrationRecord, input, result);

                // 第五步：生成修改摘要
                result.ModificationSummary = GenerateModificationSummary(result);
                result.IsSuccess = result.FailedCount == 0;
                result.CompletedTime = DateTime.Now;
                result.ElapsedMilliseconds = (int)(result.CompletedTime - result.StartTime).TotalMilliseconds;

                _logger.LogInformation("任务人员分配修改完成: Success={IsSuccess}, SuccessCount={SuccessCount}, FailedCount={FailedCount}",
                    result.IsSuccess, result.SuccessfulCount, result.FailedCount);

                return result;
            }
            catch (Exception ex)
            {
                result.IsSuccess = false;
                result.ErrorMessage = $"修改任务人员分配时发生异常: {ex.Message}";
                result.CompletedTime = DateTime.Now;
                result.ElapsedMilliseconds = (int)(result.CompletedTime - result.StartTime).TotalMilliseconds;

                _logger.LogError(ex, "修改任务人员分配失败: IntegrationRecordId={IntegrationRecordId}, Error={Message}",
                    input.IntegrationRecordId, ex.Message);

                return result;
            }
        }

        /// <summary>
        /// 批量修改任务设备分配
        /// 深度业务思考：支持批量设备分配修改，提高操作效率
        /// </summary>
        [HttpPost]
        public async Task<TaskAssignmentModificationResult> ModifyTaskEquipmentAssignmentAsync(TaskEquipmentAssignmentModificationInput input)
        {
            var result = new TaskAssignmentModificationResult
            {
                StartTime = DateTime.Now,
                IsSuccess = false
            };

            try
            {
                _logger.LogInformation("开始修改任务设备分配: IntegrationRecordId={IntegrationRecordId}, TaskCount={TaskCount}",
                    input.IntegrationRecordId, input.TaskEquipmentModifications.Count);

                // 验证整合记录
                var integrationRecord = await ValidateIntegrationRecordAsync(input.IntegrationRecordId);
                if (integrationRecord == null)
                {
                    result.ErrorMessage = $"未找到ID为{input.IntegrationRecordId}的整合记录";
                    return result;
                }

                result.IntegrationBatchCode = integrationRecord.IntegrationBatchCode;

                // 获取任务并执行设备分配修改
                var taskIds = input.TaskEquipmentModifications.Select(m => m.TaskId).ToList();
                var tasks = await GetTasksByIdsAsync(taskIds);

                result.TotalTaskCount = tasks.Count;
                var successfulModifications = new List<TaskModificationDetail>();
                var failedModifications = new List<TaskModificationFailure>();

                foreach (var modification in input.TaskEquipmentModifications)
                {
                    var task = tasks.FirstOrDefault(t => t.Id == modification.TaskId);
                    if (task == null)
                    {
                        failedModifications.Add(new TaskModificationFailure
                        {
                            TaskId = modification.TaskId,
                            TaskCode = modification.TaskCode ?? "未知",
                            FailureReason = "任务不存在",
                            ErrorDetails = "未找到指定的任务"
                        });
                        continue;
                    }

                    try
                    {
                        // 记录修改前的值
                        var previousEquipmentId = task.AssignedEquipmentId;
                        var previousEquipmentName = task.AssignedEquipmentName;

                        // 执行设备分配修改
                        task.AssignedEquipmentId = modification.NewEquipmentId;
                        task.AssignedEquipmentName = modification.NewEquipmentName ?? string.Empty;

                        // 添加修改备注
                        if (!string.IsNullOrWhiteSpace(modification.ModificationNote))
                        {
                            task.Remarks = string.IsNullOrWhiteSpace(task.Remarks)
                                ? $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] {modification.ModificationNote}"
                                : $"{task.Remarks}\n[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] {modification.ModificationNote}";
                        }

                        task.ModifiedTime = DateTime.Now;
                        task.ModifiedUserId = input.OperatorUserId;
                        task.ModifiedUserName = input.OperatorUserName;

                        successfulModifications.Add(new TaskModificationDetail
                        {
                            TaskId = task.Id,
                            TaskCode = task.WorkOrderCode ?? task.Code ?? $"TASK-{task.Id}",
                            ModificationType = "设备分配修改",
                            PreviousValue = $"设备ID:{previousEquipmentId}, 设备名:{previousEquipmentName}",
                            NewValue = $"设备ID:{task.AssignedEquipmentId}, 设备名:{task.AssignedEquipmentName}",
                            ModificationTime = DateTime.Now,
                            ModificationNote = modification.ModificationNote ?? ""
                        });
                    }
                    catch (Exception ex)
                    {
                        failedModifications.Add(new TaskModificationFailure
                        {
                            TaskId = modification.TaskId,
                            TaskCode = modification.TaskCode ?? "未知",
                            FailureReason = "修改异常",
                            ErrorDetails = ex.Message
                        });
                    }
                }

                // 批量更新任务
                if (successfulModifications.Any())
                {
                    var modifiedTasks = tasks.Where(t => successfulModifications.Any(s => s.TaskId == t.Id)).ToList();
                    await _workOrderRepository.UpdateAsync(modifiedTasks);
                }

                result.SuccessfulModifications = successfulModifications;
                result.FailedModifications = failedModifications;
                result.SuccessfulCount = successfulModifications.Count;
                result.FailedCount = failedModifications.Count;

                // 更新整合记录
                await UpdateIntegrationRecordForEquipmentModificationAsync(integrationRecord, input, result);

                result.ModificationSummary = $"设备分配修改完成：成功{result.SuccessfulCount}个，失败{result.FailedCount}个";
                result.IsSuccess = result.FailedCount == 0;
                result.CompletedTime = DateTime.Now;
                result.ElapsedMilliseconds = (int)(result.CompletedTime - result.StartTime).TotalMilliseconds;

                return result;
            }
            catch (Exception ex)
            {
                result.IsSuccess = false;
                result.ErrorMessage = $"修改任务设备分配时发生异常: {ex.Message}";
                result.CompletedTime = DateTime.Now;
                result.ElapsedMilliseconds = (int)(result.CompletedTime - result.StartTime).TotalMilliseconds;

                _logger.LogError(ex, "修改任务设备分配失败: IntegrationRecordId={IntegrationRecordId}, Error={Message}",
                    input.IntegrationRecordId, ex.Message);

                return result;
            }
        }

        /// <summary>
        /// 查询任务分配修改历史
        /// 深度业务思考：提供完整的修改历史追踪，支持审计和分析
        /// </summary>
        [HttpGet]
        public async Task<List<TaskAssignmentModificationHistory>> GetTaskAssignmentModificationHistoryAsync(long integrationRecordId)
        {
            try
            {
                // 查询整合记录
                var integrationRecord = await _integrationRecordRepository.GetAsync(integrationRecordId);
                if (integrationRecord == null)
                {
                    return new List<TaskAssignmentModificationHistory>();
                }

                // 获取相关任务的修改历史
                var taskIds = integrationRecord.GetTaskIds();
                if (!taskIds.Any())
                {
                    return new List<TaskAssignmentModificationHistory>();
                }

                var tasks = await _workOrderRepository.Select
                    .Where(t => taskIds.Contains(t.Id))
                    .Where(t => !string.IsNullOrEmpty(t.Remarks) && t.Remarks.Contains("人员分配修改"))
                    .OrderByDescending(t => t.ModifiedTime)
                    .ToListAsync();

                // 解析修改历史
                var histories = new List<TaskAssignmentModificationHistory>();
                foreach (var task in tasks)
                {
                    var history = ParseModificationHistory(task);
                    if (history != null)
                    {
                        histories.Add(history);
                    }
                }

                return histories;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询任务分配修改历史失败: IntegrationRecordId={IntegrationRecordId}, Error={Message}",
                    integrationRecordId, ex.Message);
                return new List<TaskAssignmentModificationHistory>();
            }
        }

        #region 私有辅助方法

        /// <summary>
        /// 验证整合记录存在性
        /// </summary>
        private async Task<IntegrationRecordEntity> ValidateIntegrationRecordAsync(long integrationRecordId)
        {
            return await _integrationRecordRepository.GetAsync(integrationRecordId);
        }

        /// <summary>
        /// 验证和获取任务
        /// </summary>
        private async Task<TaskValidationResult> ValidateAndGetTasksAsync(List<TaskAssignmentModification> modifications)
        {
            var result = new TaskValidationResult { IsValid = true };

            if (!modifications.Any())
            {
                result.IsValid = false;
                result.ErrorMessage = "没有提供需要修改的任务";
                return result;
            }

            var taskIds = modifications.Select(m => m.TaskId).ToList();
            var tasks = await GetTasksByIdsAsync(taskIds);

            if (tasks.Count != taskIds.Count)
            {
                var foundTaskIds = tasks.Select(t => t.Id).ToList();
                var missingTaskIds = taskIds.Except(foundTaskIds).ToList();
                result.IsValid = false;
                result.ErrorMessage = $"未找到以下任务: {string.Join(", ", missingTaskIds)}";
                result.ValidationErrors = missingTaskIds.Select(id => $"任务ID {id} 不存在").ToList();
                return result;
            }

            result.Tasks = tasks;
            return result;
        }

        /// <summary>
        /// 根据任务ID列表获取任务
        /// </summary>
        private async Task<List<WorkOrderEntity>> GetTasksByIdsAsync(List<long> taskIds)
        {
            return await _workOrderRepository.Select
                .Where(t => taskIds.Contains(t.Id))
                .ToListAsync();
        }

        /// <summary>
        /// 执行任务分配修改
        /// </summary>
        private async Task<TaskModificationExecutionResult> ExecuteTaskAssignmentModificationsAsync(
            List<WorkOrderEntity> tasks, 
            List<TaskAssignmentModification> modifications,
            long operatorUserId,
            string operatorUserName)
        {
            var result = new TaskModificationExecutionResult();

            foreach (var modification in modifications)
            {
                var task = tasks.FirstOrDefault(t => t.Id == modification.TaskId);
                if (task == null) continue;

                try
                {
                    _logger.LogInformation("修改任务人员分配: TaskId={TaskId}, TaskCode={TaskCode}, NewPersonnelId={PersonnelId}",
                        modification.TaskId, task.WorkOrderCode ?? task.Code, modification.NewPersonnelId);

                    // 记录修改前的值
                    var previousPersonnelId = task.AssignedPersonnelId;
                    var previousPersonnelName = task.AssignedPersonnelName;

                    // 执行人员分配修改
                    task.AssignedPersonnelId = modification.NewPersonnelId;
                    task.AssignedPersonnelName = modification.NewPersonnelName ?? string.Empty;

                    // 如果同时修改设备分配
                    var previousEquipmentId = task.AssignedEquipmentId;
                    var previousEquipmentName = task.AssignedEquipmentName;

                    if (modification.NewEquipmentId.HasValue)
                    {
                        task.AssignedEquipmentId = modification.NewEquipmentId;
                        task.AssignedEquipmentName = modification.NewEquipmentName ?? string.Empty;
                    }

                    // 更新任务备注
                    var modificationNote = $"人员分配修改：{previousPersonnelName}({previousPersonnelId}) → {task.AssignedPersonnelName}({task.AssignedPersonnelId})";
                    
                    if (modification.NewEquipmentId.HasValue)
                    {
                        modificationNote += $"；设备分配修改：{previousEquipmentName}({previousEquipmentId}) → {task.AssignedEquipmentName}({task.AssignedEquipmentId})";
                    }

                    if (!string.IsNullOrWhiteSpace(modification.ModificationNote))
                    {
                        modificationNote += $"；备注：{modification.ModificationNote}";
                    }

                    task.Remarks = string.IsNullOrWhiteSpace(task.Remarks)
                        ? $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] {modificationNote}"
                        : $"{task.Remarks}\n[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] {modificationNote}";

                    task.ModifiedTime = DateTime.Now;
                    task.ModifiedUserId = operatorUserId;
                    task.ModifiedUserName = operatorUserName;

                    result.SuccessfulModifications.Add(new TaskModificationDetail
                    {
                        TaskId = task.Id,
                        TaskCode = task.WorkOrderCode ?? task.Code ?? $"TASK-{task.Id}",
                        ModificationType = "人员分配修改",
                        PreviousValue = $"人员ID:{previousPersonnelId}, 人员名:{previousPersonnelName}",
                        NewValue = $"人员ID:{task.AssignedPersonnelId}, 人员名:{task.AssignedPersonnelName}",
                        ModificationTime = DateTime.Now,
                        ModificationNote = modification.ModificationNote ?? ""
                    });
                }
                catch (Exception ex)
                {
                    result.FailedModifications.Add(new TaskModificationFailure
                    {
                        TaskId = modification.TaskId,
                        TaskCode = task.WorkOrderCode ?? task.Code ?? $"TASK-{task.Id}",
                        FailureReason = "修改异常",
                        ErrorDetails = ex.Message
                    });

                    _logger.LogError(ex, "修改任务人员分配失败: TaskId={TaskId}, Error={Message}",
                        modification.TaskId, ex.Message);
                }
            }

            // 批量更新成功修改的任务
            if (result.SuccessfulModifications.Any())
            {
                var modifiedTasks = tasks.Where(t => result.SuccessfulModifications.Any(s => s.TaskId == t.Id)).ToList();
                await _workOrderRepository.UpdateAsync(modifiedTasks);
            }

            return result;
        }

        /// <summary>
        /// 更新整合记录
        /// </summary>
        private async Task UpdateIntegrationRecordAsync(
            IntegrationRecordEntity integrationRecord, 
            TaskAssignmentModificationInput input, 
            TaskAssignmentModificationResult result)
        {
            try
            {
                // 更新整合记录的修改信息
                var modificationSummary = $"任务人员分配修改：成功{result.SuccessfulCount}个，失败{result.FailedCount}个";
                
                if (!string.IsNullOrWhiteSpace(input.ModificationReason))
                {
                    modificationSummary = $"{input.ModificationReason} - {modificationSummary}";
                }

                integrationRecord.Remarks = string.IsNullOrWhiteSpace(integrationRecord.Remarks)
                    ? $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] {modificationSummary}"
                    : $"{integrationRecord.Remarks}\n[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] {modificationSummary}";

                integrationRecord.ModifiedTime = DateTime.Now;
                integrationRecord.ModifiedUserId = input.OperatorUserId;
                integrationRecord.ModifiedUserName = input.OperatorUserName;

                // 更新人员分配结果中的successfulMatches
                if (result.SuccessfulModifications.Any())
                {
                    try
                    {
                        // 反序列化现有的人员分配结果
                        if (!string.IsNullOrEmpty(integrationRecord.PersonnelAllocationResultJson))
                        {
                            var personnelAllocationResult = JsonSerializer.Deserialize<PersonnelAllocationResult>(
                                integrationRecord.PersonnelAllocationResultJson,
                                new JsonSerializerOptions { PropertyNameCaseInsensitive = true });

                            if (personnelAllocationResult?.SuccessfulMatches != null)
                            {
                                // 更新successfulMatches中对应的匹配信息
                                foreach (var modification in result.SuccessfulModifications)
                                {
                                    var existingMatch = personnelAllocationResult.SuccessfulMatches
                                        .FirstOrDefault(m => m.TaskId == modification.TaskId);
                                    
                                    if (existingMatch != null)
                                    {
                                        // 更新人员信息
                                        existingMatch.PersonnelId = modification.NewValue.Contains("人员ID:")
                                            ? long.Parse(modification.NewValue.Split(',')[0].Split(':')[1])
                                            : existingMatch.PersonnelId;
                                        
                                        existingMatch.PersonnelName = modification.NewValue.Contains("人员名:")
                                            ? modification.NewValue.Split(',')[1].Split(':')[1]
                                            : existingMatch.PersonnelName;
                                    }
                                }

                                // 重新序列化并更新
                                integrationRecord.PersonnelAllocationResultJson = JsonSerializer.Serialize(
                                    personnelAllocationResult,
                                    new JsonSerializerOptions 
                                    { 
                                        PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
                                        WriteIndented = true 
                                    });
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        _logger.LogWarning(ex, "更新人员分配结果失败: IntegrationRecordId={IntegrationRecordId}, Error={Message}",
                            integrationRecord.Id, ex.Message);
                    }

                    // 更新设备分配结果中的successfulMatches（如果同时修改了设备）
                    try
                    {
                        // 反序列化现有的设备分配结果
                        if (!string.IsNullOrEmpty(integrationRecord.EquipmentAllocationResultJson))
                        {
                            var equipmentAllocationResult = JsonSerializer.Deserialize<EquipmentAllocationResult>(
                                integrationRecord.EquipmentAllocationResultJson,
                                new JsonSerializerOptions { PropertyNameCaseInsensitive = true });

                            if (equipmentAllocationResult?.SuccessfulMatches != null)
                            {
                                // 更新successfulMatches中对应的匹配信息
                                foreach (var modification in result.SuccessfulModifications)
                                {
                                    // 检查修改备注中是否包含设备信息
                                    if (modification.NewValue.Contains("设备分配修改"))
                                    {
                                        var existingMatch = equipmentAllocationResult.SuccessfulMatches
                                            .FirstOrDefault(m => m.TaskId == modification.TaskId);
                                        
                                        if (existingMatch != null)
                                        {
                                            // 从备注中提取设备信息
                                            var equipmentInfo = ExtractEquipmentInfoFromModification(modification.NewValue);
                                            if (equipmentInfo.HasValue)
                                            {
                                                existingMatch.EquipmentId = equipmentInfo.Value.equipmentId;
                                                existingMatch.EquipmentName = equipmentInfo.Value.equipmentName;
                                            }
                                        }
                                    }
                                }

                                // 重新序列化并更新
                                integrationRecord.EquipmentAllocationResultJson = JsonSerializer.Serialize(
                                    equipmentAllocationResult,
                                    new JsonSerializerOptions 
                                    { 
                                        PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
                                        WriteIndented = true 
                                    });
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        _logger.LogWarning(ex, "更新设备分配结果失败: IntegrationRecordId={IntegrationRecordId}, Error={Message}",
                            integrationRecord.Id, ex.Message);
                    }
                }

                await _integrationRecordRepository.UpdateAsync(integrationRecord);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新整合记录失败: IntegrationRecordId={IntegrationRecordId}, Error={Message}",
                    integrationRecord.Id, ex.Message);
            }
        }

        /// <summary>
        /// 从修改备注中提取设备信息
        /// </summary>
        private (long equipmentId, string equipmentName)? ExtractEquipmentInfoFromModification(string modificationValue)
        {
            try
            {
                // 解析类似 "设备分配修改：设备ID:1001, 设备名:设备A" 的字符串
                if (modificationValue.Contains("设备ID:") && modificationValue.Contains("设备名:"))
                {
                    var equipmentIdStr = modificationValue.Split(new[] { "设备ID:", "," }, StringSplitOptions.None)[1];
                    var equipmentNameStr = modificationValue.Split(new[] { "设备名:" }, StringSplitOptions.None)[1];
                    
                    if (long.TryParse(equipmentIdStr, out long equipmentId))
                    {
                        return (equipmentId, equipmentNameStr);
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, "解析设备信息失败: ModificationValue={ModificationValue}", modificationValue);
            }
            
            return null;
        }

        /// <summary>
        /// 为设备修改更新整合记录
        /// </summary>
        private async Task UpdateIntegrationRecordForEquipmentModificationAsync(
            IntegrationRecordEntity integrationRecord,
            TaskEquipmentAssignmentModificationInput input,
            TaskAssignmentModificationResult result)
        {
            try
            {
                var modificationSummary = $"任务设备分配修改：成功{result.SuccessfulCount}个，失败{result.FailedCount}个";
                
                if (!string.IsNullOrWhiteSpace(input.ModificationReason))
                {
                    modificationSummary = $"{input.ModificationReason} - {modificationSummary}";
                }

                integrationRecord.Remarks = string.IsNullOrWhiteSpace(integrationRecord.Remarks)
                    ? $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] {modificationSummary}"
                    : $"{integrationRecord.Remarks}\n[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] {modificationSummary}";

                integrationRecord.ModifiedTime = DateTime.Now;
                integrationRecord.ModifiedUserId = input.OperatorUserId;
                integrationRecord.ModifiedUserName = input.OperatorUserName;

                // 更新设备分配结果中的successfulMatches
                if (result.SuccessfulModifications.Any())
                {
                    try
                    {
                        // 反序列化现有的设备分配结果
                        if (!string.IsNullOrEmpty(integrationRecord.EquipmentAllocationResultJson))
                        {
                            var equipmentAllocationResult = JsonSerializer.Deserialize<EquipmentAllocationResult>(
                                integrationRecord.EquipmentAllocationResultJson,
                                new JsonSerializerOptions { PropertyNameCaseInsensitive = true });

                            if (equipmentAllocationResult?.SuccessfulMatches != null)
                            {
                                // 更新successfulMatches中对应的匹配信息
                                foreach (var modification in result.SuccessfulModifications)
                                {
                                    var existingMatch = equipmentAllocationResult.SuccessfulMatches
                                        .FirstOrDefault(m => m.TaskId == modification.TaskId);
                                    
                                    if (existingMatch != null)
                                    {
                                        // 更新设备信息
                                        existingMatch.EquipmentId = modification.NewValue.Contains("设备ID:")
                                            ? long.Parse(modification.NewValue.Split(',')[0].Split(':')[1])
                                            : existingMatch.EquipmentId;
                                        
                                        existingMatch.EquipmentName = modification.NewValue.Contains("设备名:")
                                            ? modification.NewValue.Split(',')[1].Split(':')[1]
                                            : existingMatch.EquipmentName;
                                    }
                                }

                                // 重新序列化并更新
                                integrationRecord.EquipmentAllocationResultJson = JsonSerializer.Serialize(
                                    equipmentAllocationResult,
                                    new JsonSerializerOptions 
                                    { 
                                        PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
                                        WriteIndented = true 
                                    });
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        _logger.LogWarning(ex, "更新设备分配结果失败: IntegrationRecordId={IntegrationRecordId}, Error={Message}",
                            integrationRecord.Id, ex.Message);
                    }
                }

                await _integrationRecordRepository.UpdateAsync(integrationRecord);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新整合记录失败: IntegrationRecordId={IntegrationRecordId}, Error={Message}",
                    integrationRecord.Id, ex.Message);
            }
        }

        /// <summary>
        /// 生成修改摘要
        /// </summary>
        private string GenerateModificationSummary(TaskAssignmentModificationResult result)
        {
            var summary = $"任务分配修改完成：总计{result.TotalTaskCount}个任务，成功{result.SuccessfulCount}个，失败{result.FailedCount}个";
            
            if (result.FailedCount > 0)
            {
                var failureReasons = result.FailedModifications
                    .GroupBy(f => f.FailureReason)
                    .Select(g => $"{g.Key}({g.Count()}个)")
                    .ToList();
                summary += $"。失败原因：{string.Join("、", failureReasons)}";
            }

            summary += $"。耗时{result.ElapsedMilliseconds}毫秒";
            return summary;
        }

        /// <summary>
        /// 解析修改历史
        /// </summary>
        private TaskAssignmentModificationHistory ParseModificationHistory(WorkOrderEntity task)
        {
            try
            {
                // 简单的历史解析实现
                return new TaskAssignmentModificationHistory
                {
                    TaskId = task.Id,
                    TaskCode = task.WorkOrderCode ?? task.Code ?? $"TASK-{task.Id}",
                    ModificationTime = task.ModifiedTime ?? DateTime.Now,
                    ModificationDetails = task.Remarks ?? "",
                    ModifiedByUserId = task.ModifiedUserId,
                    ModifiedByUserName = task.ModifiedUserName ?? "",
                    CurrentPersonnelId = task.AssignedPersonnelId,
                    CurrentPersonnelName = task.AssignedPersonnelName ?? "",
                    CurrentEquipmentId = task.AssignedEquipmentId,
                    CurrentEquipmentName = task.AssignedEquipmentName ?? ""
                };
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, "解析任务修改历史失败: TaskId={TaskId}, Error={Message}", task.Id, ex.Message);
                return null;
            }
        }

        #endregion

        #region 内部数据模型

        /// <summary>
        /// 任务验证结果
        /// </summary>
        private class TaskValidationResult
        {
            public bool IsValid { get; set; }
            public string ErrorMessage { get; set; } = "";
            public List<string> ValidationErrors { get; set; } = new();
            public List<WorkOrderEntity> Tasks { get; set; } = new();
        }

        /// <summary>
        /// 任务修改执行结果
        /// </summary>
        private class TaskModificationExecutionResult
        {
            public List<TaskModificationDetail> SuccessfulModifications { get; set; } = new();
            public List<TaskModificationFailure> FailedModifications { get; set; } = new();
        }

        #endregion
    }

    #region 输入输出模型

    /// <summary>
    /// 任务人员分配修改输入
    /// </summary>
    public class TaskAssignmentModificationInput
    {
        /// <summary>
        /// 整合记录ID
        /// </summary>
        public long IntegrationRecordId { get; set; }

        /// <summary>
        /// 操作员用户ID
        /// </summary>
        public long OperatorUserId { get; set; }

        /// <summary>
        /// 操作员用户名
        /// </summary>
        public string OperatorUserName { get; set; } = string.Empty;

        /// <summary>
        /// 任务分配修改列表
        /// </summary>
        public List<TaskAssignmentModification> TaskAssignmentModifications { get; set; } = new();

        /// <summary>
        /// 修改原因说明
        /// </summary>
        public string ModificationReason { get; set; } = string.Empty;

        /// <summary>
        /// 是否强制执行（忽略部分警告）
        /// </summary>
        public bool ForceExecute { get; set; } = false;
    }

    /// <summary>
    /// 任务设备分配修改输入
    /// </summary>
    public class TaskEquipmentAssignmentModificationInput
    {
        /// <summary>
        /// 整合记录ID
        /// </summary>
        public long IntegrationRecordId { get; set; }

        /// <summary>
        /// 操作员用户ID
        /// </summary>
        public long OperatorUserId { get; set; }

        /// <summary>
        /// 操作员用户名
        /// </summary>
        public string OperatorUserName { get; set; } = string.Empty;

        /// <summary>
        /// 任务设备分配修改列表
        /// </summary>
        public List<TaskEquipmentAssignmentModification> TaskEquipmentModifications { get; set; } = new();

        /// <summary>
        /// 修改原因说明
        /// </summary>
        public string ModificationReason { get; set; } = string.Empty;

        /// <summary>
        /// 是否强制执行（忽略部分警告）
        /// </summary>
        public bool ForceExecute { get; set; } = false;
    }

    /// <summary>
    /// 单个任务人员分配修改
    /// </summary>
    public class TaskAssignmentModification
    {
        /// <summary>
        /// 任务ID
        /// </summary>
        public long TaskId { get; set; }

        /// <summary>
        /// 任务代码（可选，用于显示）
        /// </summary>
        public string? TaskCode { get; set; }

        /// <summary>
        /// 新的人员ID
        /// </summary>
        public long? NewPersonnelId { get; set; }

        /// <summary>
        /// 新的人员姓名
        /// </summary>
        public string? NewPersonnelName { get; set; }

        /// <summary>
        /// 新的设备ID（可选，支持同时修改设备）
        /// </summary>
        public long? NewEquipmentId { get; set; }

        /// <summary>
        /// 新的设备名称（可选）
        /// </summary>
        public string? NewEquipmentName { get; set; }

        /// <summary>
        /// 修改备注
        /// </summary>
        public string ModificationNote { get; set; } = string.Empty;
    }

    /// <summary>
    /// 单个任务设备分配修改
    /// </summary>
    public class TaskEquipmentAssignmentModification
    {
        /// <summary>
        /// 任务ID
        /// </summary>
        public long TaskId { get; set; }

        /// <summary>
        /// 任务代码（可选，用于显示）
        /// </summary>
        public string? TaskCode { get; set; }

        /// <summary>
        /// 新的设备ID
        /// </summary>
        public long? NewEquipmentId { get; set; }

        /// <summary>
        /// 新的设备名称
        /// </summary>
        public string? NewEquipmentName { get; set; }

        /// <summary>
        /// 修改备注
        /// </summary>
        public string ModificationNote { get; set; } = string.Empty;
    }

    /// <summary>
    /// 任务分配修改结果
    /// </summary>
    public class TaskAssignmentModificationResult
    {
        /// <summary>
        /// 是否修改成功
        /// </summary>
        public bool IsSuccess { get; set; }

        /// <summary>
        /// 开始时间
        /// </summary>
        public DateTime StartTime { get; set; }

        /// <summary>
        /// 完成时间
        /// </summary>
        public DateTime CompletedTime { get; set; }

        /// <summary>
        /// 耗时毫秒数
        /// </summary>
        public int ElapsedMilliseconds { get; set; }

        /// <summary>
        /// 整合批次编码
        /// </summary>
        public string IntegrationBatchCode { get; set; } = string.Empty;

        /// <summary>
        /// 总任务数量
        /// </summary>
        public int TotalTaskCount { get; set; }

        /// <summary>
        /// 成功修改数量
        /// </summary>
        public int SuccessfulCount { get; set; }

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

        /// <summary>
        /// 成功修改的任务详情
        /// </summary>
        public List<TaskModificationDetail> SuccessfulModifications { get; set; } = new();

        /// <summary>
        /// 失败修改的任务详情
        /// </summary>
        public List<TaskModificationFailure> FailedModifications { get; set; } = new();

        /// <summary>
        /// 修改摘要
        /// </summary>
        public string ModificationSummary { get; set; } = string.Empty;

        /// <summary>
        /// 错误消息
        /// </summary>
        public string ErrorMessage { get; set; } = string.Empty;

        /// <summary>
        /// 验证错误列表
        /// </summary>
        public List<string> ValidationErrors { get; set; } = new();
    }

    /// <summary>
    /// 任务修改详情
    /// </summary>
    public class TaskModificationDetail
    {
        /// <summary>
        /// 任务ID
        /// </summary>
        public long TaskId { get; set; }

        /// <summary>
        /// 任务代码
        /// </summary>
        public string TaskCode { get; set; } = string.Empty;

        /// <summary>
        /// 修改类型
        /// </summary>
        public string ModificationType { get; set; } = string.Empty;

        /// <summary>
        /// 修改前的值
        /// </summary>
        public string PreviousValue { get; set; } = string.Empty;

        /// <summary>
        /// 修改后的值
        /// </summary>
        public string NewValue { get; set; } = string.Empty;

        /// <summary>
        /// 修改时间
        /// </summary>
        public DateTime ModificationTime { get; set; }

        /// <summary>
        /// 修改备注
        /// </summary>
        public string ModificationNote { get; set; } = string.Empty;
    }

    /// <summary>
    /// 任务修改失败详情
    /// </summary>
    public class TaskModificationFailure
    {
        /// <summary>
        /// 任务ID
        /// </summary>
        public long TaskId { get; set; }

        /// <summary>
        /// 任务代码
        /// </summary>
        public string TaskCode { get; set; } = string.Empty;

        /// <summary>
        /// 失败原因
        /// </summary>
        public string FailureReason { get; set; } = string.Empty;

        /// <summary>
        /// 错误详情
        /// </summary>
        public string ErrorDetails { get; set; } = string.Empty;
    }

    /// <summary>
    /// 任务分配修改历史
    /// </summary>
    public class TaskAssignmentModificationHistory
    {
        /// <summary>
        /// 任务ID
        /// </summary>
        public long TaskId { get; set; }

        /// <summary>
        /// 任务代码
        /// </summary>
        public string TaskCode { get; set; } = string.Empty;

        /// <summary>
        /// 修改时间
        /// </summary>
        public DateTime ModificationTime { get; set; }

        /// <summary>
        /// 修改详情
        /// </summary>
        public string ModificationDetails { get; set; } = string.Empty;

        /// <summary>
        /// 修改人用户ID
        /// </summary>
        public long? ModifiedByUserId { get; set; }

        /// <summary>
        /// 修改人用户名
        /// </summary>
        public string ModifiedByUserName { get; set; } = string.Empty;

        /// <summary>
        /// 当前人员ID
        /// </summary>
        public long? CurrentPersonnelId { get; set; }

        /// <summary>
        /// 当前人员姓名
        /// </summary>
        public string CurrentPersonnelName { get; set; } = string.Empty;

        /// <summary>
        /// 当前设备ID
        /// </summary>
        public long? CurrentEquipmentId { get; set; }

        /// <summary>
        /// 当前设备名称
        /// </summary>
        public string CurrentEquipmentName { get; set; } = string.Empty;
    }

    #endregion
}