package com.aps.controller;

import com.aps.llm.LLMClient;
import com.aps.model.ChromosomeData;
import com.aps.model.MachineOption;
import com.aps.model.Operation;
import com.aps.parser.ChromosomeParser;
import com.aps.service.plan.SceneService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 诊断API控制器
 */
@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "*")
public class DiagnosisController {
    
    @Autowired
    private LLMClient llmClient;
    
    private static final String UPLOAD_DIR = "uploads";

    @Autowired
    private SceneService sceneService;

    // 移除成员变量，改用Session存储
    // 注意：ChromosomeParser不再使用@Autowired注入，而是每次请求创建新实例
    
    /**
     * 获取会话数据（从Session中）
     */
    @SuppressWarnings("unchecked")
    private Map<String, Object> getSessionData(javax.servlet.http.HttpSession session) {
        Map<String, Object> data = (Map<String, Object>) session.getAttribute("sessionData");
        if (data == null) {
            data = new HashMap<>();
            session.setAttribute("sessionData", data);
        }
        return data;
    }
    
    /**
     * 获取对话历史（从Session中）
     */
    @SuppressWarnings("unchecked")
    private List<Map<String, String>> getConversationHistory(javax.servlet.http.HttpSession session) {
        List<Map<String, String>> history = (List<Map<String, String>>) session.getAttribute("conversationHistory");
        if (history == null) {
            history = new ArrayList<>();
            session.setAttribute("conversationHistory", history);
        }
        return history;
    }
    
    /**
     * 获取当前用户上传的文件列表（从Session中）
     */
    @SuppressWarnings("unchecked")
    private List<String> getUserUploadedFiles(javax.servlet.http.HttpSession session) {
        List<String> files = (List<String>) session.getAttribute("userUploadedFiles");
        if (files == null) {
            files = new ArrayList<>();
            session.setAttribute("userUploadedFiles", files);
        }
        return files;
    }
    
    /**
     * 保存当前用户上传的文件列表（到Session中）
     */
    private void saveUserUploadedFiles(javax.servlet.http.HttpSession session, List<String> files) {
        session.setAttribute("userUploadedFiles", files);
    }
    
    /**
     * 清空会话数据
     */
    private void clearSessionData(javax.servlet.http.HttpSession session) {
        session.removeAttribute("sessionData");
        session.removeAttribute("conversationHistory");
        session.removeAttribute("userUploadedFiles");
    }
    
    /**
     * 获取可用的JSON文件列表（仅显示当前用户上传的文件）
     */
    @GetMapping("/files")
    public ResponseEntity<Map<String, Object>> getAvailableFiles(javax.servlet.http.HttpSession session) {
        try {
            // 从Session中获取当前用户上传的文件列表
            List<String> userFiles = getUserUploadedFiles(session);
            
            if (userFiles.isEmpty()) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", true);
                response.put("files", new ArrayList<>());
                return ResponseEntity.ok(response);
            }
            
            File uploadDir = new File(UPLOAD_DIR);
            List<Map<String, Object>> fileList = new ArrayList<>();
            
            for (String fileName : userFiles) {
                File file = new File(uploadDir, fileName);
                if (file.exists() && file.isFile()) {
                    Map<String, Object> fileInfo = new HashMap<>();
                    fileInfo.put("name", file.getName());
                    fileInfo.put("path", file.getAbsolutePath());
                    fileInfo.put("size", file.length());
                    fileInfo.put("lastModified", file.lastModified());
                    fileList.add(fileInfo);
                }
            }
            
            // 按修改时间排序，最新的在前
            fileList.sort((a, b) -> 
                Long.compare((Long) b.get("lastModified"), (Long) a.get("lastModified")));
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("files", fileList);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", e.getMessage());
            return ResponseEntity.status(500).body(error);
        }
    }
    
    /**
     * 上传JSON文件（绑定到当前用户Session）
     */
    @PostMapping("/upload")
    public ResponseEntity<Map<String, Object>> uploadFile(@RequestParam("file") MultipartFile file,
                                                           javax.servlet.http.HttpSession session) {
        try {
            // 创建上传目录
            Path uploadPath = Paths.get(UPLOAD_DIR);
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }
            
            // 保存文件
            String fileName = file.getOriginalFilename();
            if (fileName == null || fileName.isEmpty()) {
                throw new IllegalArgumentException("文件名不能为空");
            }
            
            // 确保文件名以.json结尾
            if (!fileName.toLowerCase().endsWith(".json")) {
                fileName += ".json";
            }
            
            Path filePath = uploadPath.resolve(fileName);
            Files.write(filePath, file.getBytes());
            
            // 将文件添加到当前用户的文件列表中
            List<String> userFiles = getUserUploadedFiles(session);
            if (!userFiles.contains(fileName)) {
                userFiles.add(fileName);
                saveUserUploadedFiles(session, userFiles);
            }
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("fileName", fileName);
            response.put("filePath", filePath.toString());
            response.put("message", "文件上传成功");
            
            return ResponseEntity.ok(response);
        } catch (IOException e) {
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", "文件上传失败: " + e.getMessage());
            return ResponseEntity.status(500).body(error);
        }
    }
    
    /**
     * 加载并解析JSON文件
     */
    @PostMapping("/load")
    public ResponseEntity<Map<String, Object>> loadFile(@RequestBody Map<String, String> request, 
                                                         javax.servlet.http.HttpSession session) {
        try {
            String filePath = request.get("filePath");
            if (filePath == null || filePath.isEmpty()) {
                throw new IllegalArgumentException("文件路径不能为空");
            }
            
            // 创建新的Parser实例（避免多用户数据共享）
            ChromosomeParser parser = new ChromosomeParser();
            
            // 解析数据
            parser.loadFromFile(filePath);
            
            // 获取基本信息和指标
            Map<String, Object> basicInfo = parser.getBasicInfo();
            Map<String, Object> metrics = parser.calculateMetrics();
            String summary = parser.generateSummary();
            
            // 将Parser实例存储到Session中，供后续操作使用
            Map<String, Object> sessionData = getSessionData(session);
            sessionData.put("parser", parser);  // ← 存储Parser实例
            sessionData.put("filePath", filePath);
            sessionData.put("summary", summary);
            sessionData.put("basicInfo", basicInfo);
            sessionData.put("metrics", metrics);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("basicInfo", basicInfo);
            response.put("metrics", metrics);
            response.put("message", "数据加载成功");
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", "数据加载失败: " + e.getMessage());
            return ResponseEntity.status(500).body(error);
        }
    }

    /**
     * 加载并解析JSON文件
     */
    private Map<String, Object> loadChromosomeFile(String sceneId,javax.servlet.http.HttpSession session) {
        try {

            if (sceneId == null || sceneId.isEmpty()) {
                throw new IllegalArgumentException("场景ID不能为空");
            }

            File file =sceneService.getCurrentChromosomeFile(sceneId);

            String filePath = file.getPath();
            if (filePath == null || filePath.isEmpty()) {
                throw new IllegalArgumentException("文件路径不能为空");
            }

            // 创建新的Parser实例（避免多用户数据共享）
            ChromosomeParser parser = new ChromosomeParser();

            // 解析数据
            parser.loadFromFile(filePath);

            // 获取基本信息和指标
            Map<String, Object> basicInfo = parser.getBasicInfo();
            Map<String, Object> metrics = parser.calculateMetrics();
            String summary = parser.generateSummary();

            // 将Parser实例存储到Session中，供后续操作使用
            Map<String, Object> sessionData = getSessionData(session);
            sessionData.put("parser", parser);  // ← 存储Parser实例
            sessionData.put("filePath", filePath);
            sessionData.put("summary", summary);
            sessionData.put("basicInfo", basicInfo);
            sessionData.put("metrics", metrics);

            return sessionData;

        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", "数据加载失败: " + e.getMessage());
            return error;
        }
    }

    /**
     * 执行AI诊断
     */
    @PostMapping("/diagnoseChromosome")
    public ResponseEntity<Map<String, Object>> diagnoseChromosome(@RequestBody Map<String, Object> params,javax.servlet.http.HttpSession session) {
        try {

            // 从参数中获取sceneId
            String sceneId = (String) params.get("sceneId");

            // 校验sceneId是否存在
            if (sceneId == null || sceneId.isEmpty()) {
                throw new IllegalArgumentException("场景ID不能为空");
            }

            Map<String, Object> sessionData = loadChromosomeFile(sceneId,session);
            if (!sessionData.containsKey("summary")) {
                throw new IllegalStateException("请先加载数据");
            }

            // 从Session中获取Parser实例
            ChromosomeParser parser = (ChromosomeParser) sessionData.get("parser");
            if (parser == null) {
                throw new IllegalStateException("解析器未初始化，请重新加载数据");
            }

            String summary = (String) sessionData.get("summary");

            // 调用AI诊断
            String rulesContext = "无特定规则约束。\n\n" +
                    "请作为APS(高级计划与排程)系统专家,基于您的专业知识对以下排产方案进行自由诊断分析。\n\n" +
                    "您可以从以下角度进行分析:\n" +
                    "- 整体评估\n" +
                    "- 瓶颈识别\n" +
                    "- 效率分析\n" +
                    "- 优化建议\n" +
                    "- 风险评估\n";

            List<String> diagnosisFocus = Arrays.asList("全面分析");

            String report = llmClient.diagnoseSchedule(summary, rulesContext, diagnosisFocus);

            // 保存诊断报告（使用Session隔离）
            sessionData.put("diagnosisReport", report);

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("report", report);
            response.put("message", "诊断完成");

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", "诊断失败: " + e.getMessage());
            e.printStackTrace();
            return ResponseEntity.status(500).body(error);
        }
    }


    /**
     * 执行AI诊断
     */
    @PostMapping("/diagnose")
    public ResponseEntity<Map<String, Object>> diagnose(javax.servlet.http.HttpSession session) {
        try {
            Map<String, Object> sessionData = getSessionData(session);
            if (!sessionData.containsKey("summary")) {
                throw new IllegalStateException("请先加载数据");
            }
            
            // 从Session中获取Parser实例
            ChromosomeParser parser = (ChromosomeParser) sessionData.get("parser");
            if (parser == null) {
                throw new IllegalStateException("解析器未初始化，请重新加载数据");
            }
            
            String summary = (String) sessionData.get("summary");
            
            // 调用AI诊断
            String rulesContext = "无特定规则约束。\n\n" +
                    "请作为APS(高级计划与排程)系统专家,基于您的专业知识对以下排产方案进行自由诊断分析。\n\n" +
                    "您可以从以下角度进行分析:\n" +
                    "- 整体评估\n" +
                    "- 瓶颈识别\n" +
                    "- 效率分析\n" +
                    "- 优化建议\n" +
                    "- 风险评估\n";
            
            List<String> diagnosisFocus = Arrays.asList("全面分析");
            
            String report = llmClient.diagnoseSchedule(summary, rulesContext, diagnosisFocus);
            
            // 保存诊断报告（使用Session隔离）
            sessionData.put("diagnosisReport", report);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("report", report);
            response.put("message", "诊断完成");
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", "诊断失败: " + e.getMessage());
            e.printStackTrace();
            return ResponseEntity.status(500).body(error);
        }
    }
    
    /**
     * 交互式提问
     */
    @PostMapping("/ask")
    public ResponseEntity<Map<String, Object>> askQuestion(@RequestBody Map<String, String> request,
                                                            javax.servlet.http.HttpSession session) {
        try {
            String question = request.get("question");
            if (question == null || question.isEmpty()) {
                throw new IllegalArgumentException("问题不能为空");
            }
            
            // 获取会话数据和对话历史（使用Session隔离）
            Map<String, Object> sessionData = getSessionData(session);
            List<Map<String, String>> conversationHistory = getConversationHistory(session);
            
            // 添加用户问题到对话历史
            conversationHistory.add(createMessage("user", question));
            
            String answer;
            
            // 如果有加载数据，使用上下文信息；否则进行通用对话
            if (sessionData.containsKey("summary")) {
                String contextInfo = (String) sessionData.get("summary");
                answer = llmClient.interactiveChat(conversationHistory, contextInfo);
            } else {
                // 没有加载数据时，进行通用APS对话
                answer = llmClient.generalChat(conversationHistory);
            }
            
            // 添加AI回答到对话历史
            conversationHistory.add(createMessage("assistant", answer));
            
            // 限制对话历史长度，避免超出token限制（保留最近10轮对话）
            if (conversationHistory.size() > 20) {
                conversationHistory = conversationHistory.subList(conversationHistory.size() - 20, conversationHistory.size());
            }
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("answer", answer);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", "回答失败: " + e.getMessage());
            return ResponseEntity.status(500).body(error);
        }
    }
    
    /**
     * 清空对话历史
     */
    @PostMapping("/clear-chat")
    public ResponseEntity<Map<String, Object>> clearChat(javax.servlet.http.HttpSession session) {
        // 使用Session隔离，只清空当前用户的对话历史
        List<Map<String, String>> conversationHistory = getConversationHistory(session);
        conversationHistory.clear();
        
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "对话历史已清空");
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 优化排产方案
     */
    @PostMapping("/optimize")
    public ResponseEntity<Map<String, Object>> optimize(javax.servlet.http.HttpSession session) {
        try {
            Map<String, Object> sessionData = getSessionData(session);
            if (!sessionData.containsKey("summary")) {
                throw new IllegalStateException("请先加载数据");
            }
            
            // 从Session中获取Parser实例
            ChromosomeParser parser = (ChromosomeParser) sessionData.get("parser");
            if (parser == null) {
                throw new IllegalStateException("解析器未初始化，请重新加载数据");
            }
            
            String summary = (String) sessionData.get("summary");
            String filePath = (String) sessionData.get("filePath");
            
            // 获取当前解析器数据
            Map<String, Object> basicInfo = parser.getBasicInfo();
            Map<String, Object> metrics = parser.calculateMetrics();
            Map<Integer, ChromosomeParser.MachineStats> oldStats = parser.getMachineUsageStats();
            
            // 提取旧负载数据
            List<Integer> oldLoads = oldStats.values().stream()
                    .map(ChromosomeParser.MachineStats::getCount)
                    .collect(Collectors.toList());
            
            // 第1步：让AI分析并给出优化策略和参数建议
            String optimizationPrompt = buildOptimizationPrompt(summary, basicInfo, metrics, oldLoads);
            
            List<Map<String, String>> messages = new ArrayList<>();
            messages.add(createMessage("system", "你是一个专业的APS排产优化专家，擅长分析和优化生产调度方案。"));
            messages.add(createMessage("user", optimizationPrompt));
            
            String optimizationAdvice = llmClient.chatCompletion(messages, 0.3, 2500, null);
            
            // 第2步：从AI建议中提取优化参数
            OptimizationParams params = extractOptimizationParams(optimizationAdvice, oldLoads);
            
            // 第3步：根据AI建议的参数执行优化算法
            List<Integer> newMachineSelection = performLoadBalancingOptimization(parser, params);
            List<Integer> newOperationSequence = optimizeOperationSequence(parser, params);
            
            // 验证优化方案
            if (!validateOptimization(parser, newMachineSelection)) {
                throw new RuntimeException("优化方案验证失败");
            }
            
            // 保存优化后的文件
            String outputFilePath = saveOptimizedFile(parser, filePath, newMachineSelection, newOperationSequence, optimizationAdvice);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "优化完成");
            response.put("outputFile", outputFilePath);
            response.put("optimizationAdvice", optimizationAdvice);
            response.put("newMachineSelection", newMachineSelection);
            response.put("optimizationStrategy", params.getStrategy());
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", "优化失败: " + e.getMessage());
            e.printStackTrace();
            return ResponseEntity.status(500).body(error);
        }
    }
    
    /**
     * 构建优化提示词
     */
    private String buildOptimizationPrompt(String summary, Map<String, Object> basicInfo, 
                                           Map<String, Object> metrics, List<Integer> oldLoads) {
        StringBuilder prompt = new StringBuilder();
        prompt.append("你是APS(高级计划与排程)系统专家。\n\n");
        prompt.append("## 当前排产方案数据摘要\n");
        prompt.append(summary).append("\n\n");
        prompt.append("## 任务要求\n");
        prompt.append("请分析当前排产方案的问题，并给出具体的优化策略和参数建议。\n\n");
        
        prompt.append("### 当前问题\n");
        prompt.append(String.format("- 工序总数: %s\n", basicInfo.get("operationCount")));
        prompt.append(String.format("- 使用机器数: %s\n", metrics.get("totalMachinesUsed")));
        
        if (!oldLoads.isEmpty()) {
            prompt.append(String.format("- 最大负载: %d 工序\n", Collections.max(oldLoads)));
            prompt.append(String.format("- 最小负载: %d 工序\n", Collections.min(oldLoads)));
            int avgLoad = oldLoads.stream().mapToInt(Integer::intValue).sum() / oldLoads.size();
            prompt.append(String.format("- 平均负载: %d 工序\n", avgLoad));
        }
        
        prompt.append("\n### 请给出以下优化建议\n");
        prompt.append("1. **优化策略**: 从以下策略中选择最适合的一个：\n");
        prompt.append("   - BALANCED: 负载均衡优先（适合负载不均的情况）\n");
        prompt.append("   - EFFICIENCY: 效率优先（适合追求最短完工时间）\n");
        prompt.append("   - HYBRID: 混合策略（平衡负载和效率）\n\n");
        
        prompt.append("2. **负载均衡权重** (0-1之间): \n");
        prompt.append("   - 如果选择BALANCED策略，建议0.8-1.0\n");
        prompt.append("   - 如果选择EFFICIENCY策略，建议0.3-0.5\n");
        prompt.append("   - 如果选择HYBRID策略，建议0.6-0.7\n\n");
        
        prompt.append("3. **工序排序策略**: \n");
        prompt.append("   - SPT: 最短处理时间优先\n");
        prompt.append("   - LPT: 最长处理时间优先\n");
        prompt.append("   - EDD: 最早交期优先\n");
        prompt.append("   - FCFS: 先来先服务（保持原序）\n\n");
        
        prompt.append("4. **具体操作步骤**: 详细说明应该如何优化\n\n");
        
        prompt.append("### 输出格式\n");
        prompt.append("请用中文详细说明优化策略，包括:\n");
        prompt.append("- 当前存在的主要问题\n");
        prompt.append("- 推荐的优化策略及原因\n");
        prompt.append("- 预期的改善效果\n\n");
        
        prompt.append("**重要**: 请在回答中明确说明你选择的策略、权重和排序方法。");
        
        return prompt.toString();
    }
    
    /**
     * 执行负载均衡优化
     */
    private List<Integer> performLoadBalancingOptimization(ChromosomeParser parser, OptimizationParams params) {
        List<Operation> operations = parser.getGlobalOperations();
        
        // 构建机器可选映射
        Map<Integer, List<MachineOption>> machineOptionsMap = new HashMap<>();
        for (int i = 0; i < operations.size(); i++) {
            Operation op = operations.get(i);
            if (op.getMachineOptions() != null) {
                machineOptionsMap.put(i, op.getMachineOptions());
            }
        }
        
        // 统计每台机器的可用次数
        Map<Integer, Integer> machineAvailability = new HashMap<>();
        for (List<MachineOption> options : machineOptionsMap.values()) {
            for (MachineOption option : options) {
                Integer machineId = option.getMachineId();
                if (machineId != null) {
                    machineAvailability.put(machineId, 
                        machineAvailability.getOrDefault(machineId, 0) + 1);
                }
            }
        }
        
        // 根据策略调整优化目标
        Map<Integer, Integer> machineLoad = new HashMap<>();
        for (Integer machineId : machineAvailability.keySet()) {
            machineLoad.put(machineId, 0);
        }
        
        List<Integer> newMachineSelection = new ArrayList<>();
        double balanceWeight = params.getBalanceWeight();
        
        for (int i = 0; i < operations.size(); i++) {
            List<MachineOption> options = machineOptionsMap.get(i);
            if (options == null || options.isEmpty()) {
                newMachineSelection.add(1); // 默认选择第一个
                continue;
            }
            
            // 根据平衡权重计算得分
            int bestOptionIndex = 1;
            double bestScore = Double.MAX_VALUE;
            
            for (int j = 0; j < options.size(); j++) {
                Integer machineId = options.get(j).getMachineId();
                if (machineId != null) {
                    int currentLoad = machineLoad.getOrDefault(machineId, 0);
                    
                    // 综合得分 = 负载得分 * 权重 + 效率得分 * (1-权重)
                    double loadScore = currentLoad * balanceWeight;
                    // 使用工序的runtime作为效率指标（如果没有则用默认值1.0）
                    Operation currentOp = operations.get(i);
                    double runtime = currentOp.getRuntime() != null ? currentOp.getRuntime() : 1.0;
                    double efficiencyScore = runtime * (1 - balanceWeight);
                    double totalScore = loadScore + efficiencyScore;
                    
                    if (totalScore < bestScore) {
                        bestScore = totalScore;
                        bestOptionIndex = j + 1; // 从1开始计数
                    }
                }
            }
            
            newMachineSelection.add(bestOptionIndex);
            
            // 更新机器负载
            Integer selectedMachineId = options.get(bestOptionIndex - 1).getMachineId();
            if (selectedMachineId != null) {
                machineLoad.put(selectedMachineId, machineLoad.get(selectedMachineId) + 1);
            }
        }
        
        return newMachineSelection;
    }
    
    /**
     * 优化工序排序
     */
    private List<Integer> optimizeOperationSequence(ChromosomeParser parser, OptimizationParams params) {
        List<Operation> operations = parser.getGlobalOperations();
        String strategy = params.getSequencingStrategy();
        
        // 如果选择FCFS，保持原序
        if ("FCFS".equals(strategy)) {
            return parser.getRawData().getOperationSequencing();
        }
        
        // 创建索引列表
        List<Integer> indices = new ArrayList<>();
        for (int i = 0; i < operations.size(); i++) {
            indices.add(i);
        }
        
        // 根据策略排序
        switch (strategy) {
            case "SPT": // 最短处理时间优先
                indices.sort((a, b) -> {
                    double timeA = getProcessingTime(operations.get(a));
                    double timeB = getProcessingTime(operations.get(b));
                    return Double.compare(timeA, timeB);
                });
                break;
            case "LPT": // 最长处理时间优先
                indices.sort((a, b) -> {
                    double timeA = getProcessingTime(operations.get(a));
                    double timeB = getProcessingTime(operations.get(b));
                    return Double.compare(timeB, timeA);
                });
                break;
            case "EDD": // 最早交期优先（使用订单编码排序作为替代）
                indices.sort((a, b) -> {
                    String orderA = operations.get(a).getOrderCode();
                    String orderB = operations.get(b).getOrderCode();
                    if (orderA == null) return 1;
                    if (orderB == null) return -1;
                    return orderA.compareTo(orderB);
                });
                break;
            default:
                // 默认保持原序
                return parser.getRawData().getOperationSequencing();
        }
        
        // 将索引转换为工序ID
        List<Integer> newSequence = new ArrayList<>();
        for (Integer index : indices) {
            Operation op = operations.get(index);
            if (op.getId() != null) {
                newSequence.add(op.getId());
            }
        }
        
        return newSequence;
    }
    
    /**
     * 获取工序的处理时间
     */
    private double getProcessingTime(Operation operation) {
        // 使用runtime作为处理时间
        if (operation.getRuntime() != null) {
            return operation.getRuntime();
        }
        return 1.0; // 默认值
    }
    
    /**
     * 验证优化方案
     */
    private boolean validateOptimization(ChromosomeParser parser, List<Integer> newMachineSelection) {
        List<Operation> operations = parser.getGlobalOperations();
        
        // 检查长度
        if (newMachineSelection.size() != operations.size()) {
            return false;
        }
        
        // 检查值范围
        for (int i = 0; i < newMachineSelection.size(); i++) {
            Integer selectionValue = newMachineSelection.get(i);
            Operation op = operations.get(i);
            
            if (op.getMachineOptions() != null) {
                int optionCount = op.getMachineOptions().size();
                if (selectionValue < 1 || selectionValue > optionCount) {
                    return false;
                }
            }
        }
        
        return true;
    }
    
    /**
     * 验证优化后数据的完整性
     */
    private void validateOptimizationData(ChromosomeParser parser, ChromosomeData originalData,
                                          List<Integer> newMachineSelection, List<Integer> newOperationSequence) {
        System.out.println("\n========== 优化数据完整性验证 ==========");
        
        // 1. 验证工序数量
        int originalOpCount = originalData.getGlobalOpList() != null ? originalData.getGlobalOpList().size() : 0;
        int optimizedOpCount = parser.getGlobalOperations().size();
        System.out.println(String.format("✓ 原始工序数: %d", originalOpCount));
        System.out.println(String.format("✓ 优化后工序数: %d", optimizedOpCount));
        if (originalOpCount != optimizedOpCount) {
            throw new RuntimeException(String.format("工序数量不匹配！原始: %d, 优化后: %d", originalOpCount, optimizedOpCount));
        }
        
        // 2. 验证机器选择数组长度
        int machineSelectionSize = newMachineSelection.size();
        System.out.println(String.format("✓ 机器选择数组长度: %d", machineSelectionSize));
        if (machineSelectionSize != optimizedOpCount) {
            throw new RuntimeException(String.format("机器选择数组长度不匹配！期望: %d, 实际: %d", optimizedOpCount, machineSelectionSize));
        }
        
        // 3. 验证工序排序数组长度
        int sequenceSize = newOperationSequence.size();
        System.out.println(String.format("✓ 工序排序数组长度: %d", sequenceSize));
        if (sequenceSize != optimizedOpCount) {
            throw new RuntimeException(String.format("工序排序数组长度不匹配！期望: %d, 实际: %d", optimizedOpCount, sequenceSize));
        }
        
        // 4. 验证机器选择的合法性
        List<Operation> operations = parser.getGlobalOperations();
        int invalidSelections = 0;
        for (int i = 0; i < newMachineSelection.size(); i++) {
            Integer selectionValue = newMachineSelection.get(i);
            Operation op = operations.get(i);
            
            if (op.getMachineOptions() != null && !op.getMachineOptions().isEmpty()) {
                int optionCount = op.getMachineOptions().size();
                if (selectionValue < 1 || selectionValue > optionCount) {
                    invalidSelections++;
                    System.err.println(String.format("✗ 工序%d的机器选择无效: %d (可选范围: 1-%d)", 
                        op.getId(), selectionValue, optionCount));
                }
            }
        }
        if (invalidSelections > 0) {
            throw new RuntimeException(String.format("发现%d个无效的机器选择！", invalidSelections));
        }
        System.out.println("✓ 所有机器选择均合法");
        
        // 5. 验证工序ID的唯一性
        Set<Integer> uniqueIds = new HashSet<>(newOperationSequence);
        if (uniqueIds.size() != newOperationSequence.size()) {
            throw new RuntimeException("工序排序中存在重复的工序ID！");
        }
        System.out.println("✓ 工序排序中无重复ID");
        
        // 6. 统计信息
        System.out.println(String.format("\n========== 优化效果统计 =========="));
        System.out.println(String.format("• 总工序数: %d", optimizedOpCount));
        System.out.println(String.format("• 优化前版本: %d", originalData.getVersion()));
        System.out.println(String.format("• 优化后版本: %d", originalData.getVersion() + 1));
        System.out.println("==========================================\n");
    }
    
    /**
     * 保存优化后的文件
     */
    private String saveOptimizedFile(ChromosomeParser parser, String originalFilePath, List<Integer> newMachineSelection,
                                     List<Integer> newOperationSequence, String optimizationAdvice) throws Exception {
        // 读取原始数据
        ChromosomeData originalData = parser.getRawData();
        
        // 生成输出文件名
        String baseName = originalFilePath;
        if (baseName.contains(".")) {
            baseName = baseName.substring(0, baseName.lastIndexOf("."));
        }
        String outputFilePath = baseName + "_optimized.json";
        
        // 读取原始文件的完整JSON内容（保留所有字段）
        com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper();
        com.fasterxml.jackson.databind.JsonNode rootNode = objectMapper.readTree(new File(originalFilePath));
        
        // 创建可变的ObjectNode
        com.fasterxml.jackson.databind.node.ObjectNode objectNode = (com.fasterxml.jackson.databind.node.ObjectNode) rootNode;
        
        // 只更新需要修改的字段（纯排产数据，不包含AI建议）
        objectNode.set("machineSelection", objectMapper.valueToTree(newMachineSelection));
        objectNode.set("operationSequencing", objectMapper.valueToTree(newOperationSequence));
        
        // 版本号+1
        Integer version = objectNode.has("version") ? objectNode.get("version").asInt() : 0;
        objectNode.put("version", version + 1);
        
        // 添加AI优化标记（仅标记是否经过AI优化，不保存建议文本）
        objectNode.put("optimized_by_ai", true);
        
        // 写入文件（不使用pretty printer，保持与原始文件相同的紧凑格式）
        objectMapper.writeValue(new File(outputFilePath), objectNode);
        
        // 验证数据完整性
        validateOptimizationData(parser, originalData, newMachineSelection, newOperationSequence);
        
        // 打印文件大小对比
        File originalFile = new File(originalFilePath);
        File optimizedFile = new File(outputFilePath);
        long originalSize = originalFile.length();
        long optimizedSize = optimizedFile.length();
        double ratio = (double)optimizedSize / originalSize * 100;
        System.out.println(String.format("\n========== 文件大小对比 =========="));
        System.out.println(String.format("• 原始文件大小: %.2f MB (%d bytes)", originalSize / (1024.0 * 1024.0), originalSize));
        System.out.println(String.format("• 优化后文件大小: %.2f MB (%d bytes)", optimizedSize / (1024.0 * 1024.0), optimizedSize));
        System.out.println(String.format("• 大小比例: %.2f%%", ratio));
        System.out.println(String.format("• 差异: %+.2f MB (%+.2f%%)", 
            (optimizedSize - originalSize) / (1024.0 * 1024.0), ratio - 100));
        System.out.println("==========================================\n");
        
        return outputFilePath;
    }
    
    /**
     * 辅助方法：创建消息对象
     */
    private Map<String, String> createMessage(String role, String content) {
        Map<String, String> message = new HashMap<>();
        message.put("role", role);
        message.put("content", content);
        return message;
    }
    
    /**
     * 优化参数类
     */
    private static class OptimizationParams {
        private String strategy = "HYBRID"; // BALANCED, EFFICIENCY, HYBRID
        private double balanceWeight = 0.7; // 负载均衡权重 0-1
        private String sequencingStrategy = "FCFS"; // SPT, LPT, EDD, FCFS
        
        public String getStrategy() { return strategy; }
        public void setStrategy(String strategy) { this.strategy = strategy; }
        public double getBalanceWeight() { return balanceWeight; }
        public void setBalanceWeight(double balanceWeight) { this.balanceWeight = balanceWeight; }
        public String getSequencingStrategy() { return sequencingStrategy; }
        public void setSequencingStrategy(String sequencingStrategy) { this.sequencingStrategy = sequencingStrategy; }
    }
    
    /**
     * 从AI建议中提取优化参数
     */
    private OptimizationParams extractOptimizationParams(String aiAdvice, List<Integer> oldLoads) {
        OptimizationParams params = new OptimizationParams();
        
        // 默认策略：根据负载情况自动选择
        if (!oldLoads.isEmpty()) {
            int maxLoad = Collections.max(oldLoads);
            int minLoad = Collections.min(oldLoads);
            double loadVariance = (double)(maxLoad - minLoad) / maxLoad;
            
            if (loadVariance > 0.3) {
                // 负载差异大，选择均衡策略
                params.setStrategy("BALANCED");
                params.setBalanceWeight(0.9);
            } else if (loadVariance < 0.1) {
                // 负载已经很均衡，选择效率策略
                params.setStrategy("EFFICIENCY");
                params.setBalanceWeight(0.4);
            } else {
                // 中等差异，混合策略
                params.setStrategy("HYBRID");
                params.setBalanceWeight(0.65);
            }
        }
        
        // 尝试从AI建议中解析策略（简单关键词匹配）
        String adviceLower = aiAdvice.toLowerCase();
        if (adviceLower.contains("balanced") || adviceLower.contains("均衡")) {
            params.setStrategy("BALANCED");
            params.setBalanceWeight(0.85);
        } else if (adviceLower.contains("efficiency") || adviceLower.contains("效率")) {
            params.setStrategy("EFFICIENCY");
            params.setBalanceWeight(0.4);
        } else if (adviceLower.contains("hybrid") || adviceLower.contains("混合")) {
            params.setStrategy("HYBRID");
            params.setBalanceWeight(0.65);
        }
        
        // 尝试解析工序排序策略
        if (adviceLower.contains("spt") || adviceLower.contains("最短处理时间")) {
            params.setSequencingStrategy("SPT");
        } else if (adviceLower.contains("lpt") || adviceLower.contains("最长处理时间")) {
            params.setSequencingStrategy("LPT");
        } else if (adviceLower.contains("edd") || adviceLower.contains("最早交期")) {
            params.setSequencingStrategy("EDD");
        }
        
        return params;
    }
    
    /**
     * 下载优化后的文件
     */
    @GetMapping("/download")
    public ResponseEntity<Resource> downloadFile(@RequestParam String filePath) {
        try {
            File file = new File(filePath);
            if (!file.exists()) {
                return ResponseEntity.notFound().build();
            }
            
            Resource resource = new FileSystemResource(file);
            String fileName = file.getName();
            
            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"")
                    .contentType(MediaType.APPLICATION_JSON)
                    .body(resource);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).build();
        }
    }
}
