<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>APS排产方案AI诊断系统</title>
    <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 1400px;
            margin: 0 auto;
            background: white;
            border-radius: 15px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.3);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }

        .header h1 {
            font-size: 32px;
            margin-bottom: 10px;
        }

        .header p {
            font-size: 16px;
            opacity: 0.9;
        }

        .content {
            padding: 30px;
        }

        .section {
            margin-bottom: 30px;
            padding: 20px;
            border: 2px solid #e0e0e0;
            border-radius: 10px;
            transition: all 0.3s;
        }

        .section:hover {
            border-color: #667eea;
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.1);
        }

        .section-title {
            font-size: 24px;
            color: #667eea;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 2px solid #667eea;
        }

        .file-list {
            display: grid;
            gap: 10px;
            margin-top: 15px;
        }

        .file-item {
            padding: 15px;
            background: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .file-item:hover {
            background: #e9ecef;
            transform: translateX(5px);
        }

        .file-item.selected {
            background: #667eea;
            color: white;
            border-color: #667eea;
        }

        .btn {
            padding: 12px 30px;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            cursor: pointer;
            transition: all 0.3s;
            font-weight: bold;
            margin: 5px;
        }

        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }

        .btn-success {
            background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
            color: white;
        }

        .btn-success:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(17, 153, 142, 0.4);
        }

        .btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
            transform: none !important;
        }

        .info-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 15px;
            margin-top: 15px;
        }

        .info-card {
            padding: 15px;
            background: #f8f9fa;
            border-radius: 8px;
            border-left: 4px solid #667eea;
        }

        .info-card label {
            font-size: 12px;
            color: #6c757d;
            display: block;
            margin-bottom: 5px;
        }

        .info-card value {
            font-size: 20px;
            font-weight: bold;
            color: #495057;
        }

        .report-container {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 8px;
            margin-top: 15px;
            max-height: 500px;
            overflow-y: auto;
            white-space: pre-wrap;
            line-height: 1.8;
            font-size: 14px;
        }

        /* Markdown 渲染样式 */
        .report-container h1,
        .report-container h2,
        .report-container h3 {
            margin-top: 20px;
            margin-bottom: 10px;
            color: #333;
        }

        .report-container h1 {
            font-size: 24px;
            border-bottom: 2px solid #667eea;
            padding-bottom: 10px;
        }

        .report-container h2 {
            font-size: 20px;
            color: #667eea;
        }

        .report-container h3 {
            font-size: 18px;
        }

        .report-container ul,
        .report-container ol {
            margin-left: 20px;
            margin-bottom: 15px;
        }

        .report-container li {
            margin-bottom: 8px;
        }

        .report-container strong {
            color: #764ba2;
        }

        .report-container code {
            background: #e9ecef;
            padding: 2px 6px;
            border-radius: 4px;
            font-size: 13px;
        }

        .report-container pre {
            background: #2d2d2d;
            color: #f8f8f2;
            padding: 15px;
            border-radius: 8px;
            overflow-x: auto;
            margin: 15px 0;
        }

        .report-container pre code {
            background: none;
            padding: 0;
        }

        .chat-container {
            margin-top: 15px;
        }

        .chat-messages {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 8px;
            min-height: 300px;
            max-height: 500px;
            overflow-y: auto;
            margin-bottom: 15px;
        }

        .message {
            margin-bottom: 15px;
            padding: 12px;
            border-radius: 8px;
            animation: fadeIn 0.3s;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .message.user {
            background: #667eea;
            color: white;
            margin-left: 50px;
        }

        .message.ai {
            background: white;
            border: 1px solid #dee2e6;
            margin-right: 50px;
        }

        .chat-input {
            display: flex;
            gap: 10px;
        }

        .chat-input input {
            flex: 1;
            padding: 12px;
            border: 2px solid #dee2e6;
            border-radius: 8px;
            font-size: 14px;
        }

        .chat-input input:focus {
            outline: none;
            border-color: #667eea;
        }

        .loading {
            text-align: center;
            padding: 20px;
            color: #667eea;
        }

        .spinner {
            border: 3px solid #f3f3f3;
            border-top: 3px solid #667eea;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
            margin: 0 auto 10px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .alert {
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 15px;
        }

        .alert-success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .alert-error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        .upload-area {
            border: 2px dashed #667eea;
            border-radius: 8px;
            padding: 30px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s;
            margin-top: 15px;
        }

        .upload-area:hover {
            background: #f8f9fa;
            border-color: #764ba2;
        }

        .hidden {
            display: none;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🚀 APS排产方案AI诊断系统</h1>
            <p>基于大语言模型的智能排产分析与优化平台</p>
        </div>

        <div class="content">
            <!-- 文件选择区域 -->
            <div class="section" id="fileSection">
                <h2 class="section-title">📂 选择排产方案文件</h2>
                <div id="fileAlert"></div>
                
                <div class="upload-area" onclick="document.getElementById('fileInput').click()">
                    <p>📤 点击上传JSON文件或从下方列表选择</p>
                    <input type="file" id="fileInput" accept=".json" style="display: none;" onchange="handleFileUpload(event)">
                </div>

                <div id="fileListContainer" style="margin-top: 20px;">
                    <h3 style="margin-bottom: 10px;">可用文件列表：</h3>
                    <div id="fileList" class="file-list">
                        <div class="loading">
                            <div class="spinner"></div>
                            <p>加载中...</p>
                        </div>
                    </div>
                </div>

                <div style="margin-top: 20px; text-align: center;">
                    <button class="btn btn-primary" onclick="loadSelectedFile()" id="loadBtn" disabled>
                        加载选中文件
                    </button>
                </div>
            </div>

            <!-- 数据信息区域 -->
            <div class="section hidden" id="infoSection">
                <h2 class="section-title">📊 排产方案基本信息</h2>
                <div id="basicInfo" class="info-grid"></div>
                
                <div style="margin-top: 20px; text-align: center;">
                    <button class="btn btn-success" onclick="startDiagnosis()" id="diagnoseBtn">
                         开始AI诊断
                    </button>
                    <button class="btn btn-primary" onclick="startOptimization()" id="optimizeBtn" style="display: none;">
                        🚀 AI智能优化排产
                    </button>
                </div>
            </div>

            <!-- 诊断报告区域 -->
            <div class="section hidden" id="reportSection">
                <h2 class="section-title">📋 AI诊断报告</h2>
                <div id="reportContent" class="report-container"></div>
                <div style="margin-top: 20px; text-align: center;">
                    <button class="btn btn-success" onclick="downloadOptimizedFile()" id="downloadBtn" style="display: none;">
                        📥 下载优化后的方案
                    </button>
                </div>
            </div>

            <!-- 对话区域 -->
            <div class="section hidden" id="chatSection">
                <h2 class="section-title">💬 与AI助手对话</h2>
                <div class="chat-container">
                    <div id="chatMessages" class="chat-messages"></div>
                    <div class="chat-input">
                        <input type="text" id="questionInput" placeholder="输入您的问题..." 
                               onkeypress="if(event.key==='Enter') askQuestion()">
                        <button class="btn btn-primary" onclick="askQuestion()">发送</button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        let selectedFile = null;
        let currentFilePath = null;
        let optimizedFilePath = null; // 存储优化文件路径

        // 页面加载时获取文件列表
        window.onload = function() {
            loadFileList();
        };

        // 加载文件列表
        async function loadFileList() {
            try {
                const response = await fetch('/api/files');
                const data = await response.json();
                
                if (data.success) {
                    displayFileList(data.files);
                } else {
                    showAlert('fileAlert', 'error', '加载文件列表失败: ' + data.message);
                }
            } catch (error) {
                showAlert('fileAlert', 'error', '网络错误: ' + error.message);
            }
        }

        // 显示文件列表
        function displayFileList(files) {
            const fileListDiv = document.getElementById('fileList');
            
            if (!files || files.length === 0) {
                fileListDiv.innerHTML = '<p style="text-align: center; color: #6c757d;">暂无可用文件，请上传JSON文件</p>';
                return;
            }

            fileListDiv.innerHTML = files.map((file, index) => {
                // 转义文件路径中的特殊字符，防止 JavaScript 语法错误
                const escapedPath = file.path.replace(/\\/g, '\\\\').replace(/'/g, "\\'");
                return `
                <div class="file-item" onclick="selectFile('${escapedPath}', this)" data-path="${file.path}">
                    <div>
                        <strong>${file.name}</strong>
                        <br>
                        <small style="color: #6c757d;">
                            ${(file.size / 1024).toFixed(1)} KB | 
                            ${new Date(file.lastModified).toLocaleString('zh-CN')}
                        </small>
                    </div>
                </div>
            `}).join('');
        }

        // 选择文件
        function selectFile(filePath, element) {
            selectedFile = filePath;
            
            // 移除其他选中状态
            document.querySelectorAll('.file-item').forEach(item => {
                item.classList.remove('selected');
            });
            
            // 添加选中状态
            element.classList.add('selected');
            
            // 启用加载按钮
            document.getElementById('loadBtn').disabled = false;
        }

        // 处理文件上传
        async function handleFileUpload(event) {
            console.log('File upload triggered:', event);
            const file = event.target.files[0];
            console.log('Selected file:', file);
            
            if (!file) {
                console.log('No file selected');
                return;
            }

            showAlert('fileAlert', 'success', '正在上传: ' + file.name);

            const formData = new FormData();
            formData.append('file', file);

            try {
                const response = await fetch('/api/upload', {
                    method: 'POST',
                    body: formData
                });
                
                const data = await response.json();
                
                if (data.success) {
                    showAlert('fileAlert', 'success', '文件上传成功！');
                    loadFileList(); // 刷新文件列表
                } else {
                    showAlert('fileAlert', 'error', '上传失败: ' + data.message);
                }
            } catch (error) {
                console.error('Upload error:', error);
                showAlert('fileAlert', 'error', '上传错误: ' + error.message);
            }
            
            // 清空文件输入，允许重复上传同一文件
            event.target.value = '';
        }

        // 加载选中的文件
        async function loadSelectedFile() {
            if (!selectedFile) {
                alert('请先选择一个文件');
                return;
            }

            currentFilePath = selectedFile;

            try {
                const response = await fetch('/api/load', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ filePath: selectedFile })
                });
                
                const data = await response.json();
                
                if (data.success) {
                    displayBasicInfo(data.basicInfo, data.metrics);
                    document.getElementById('infoSection').classList.remove('hidden');
                    showAlert('fileAlert', 'success', '数据加载成功！');
                    
                    // 滚动到信息区域
                    document.getElementById('infoSection').scrollIntoView({ behavior: 'smooth' });
                } else {
                    showAlert('fileAlert', 'error', '加载失败: ' + data.message);
                }
            } catch (error) {
                showAlert('fileAlert', 'error', '加载错误: ' + error.message);
            }
        }

        // 显示基本信息
        function displayBasicInfo(basicInfo, metrics) {
            const infoDiv = document.getElementById('basicInfo');
            infoDiv.innerHTML = `
                <div class="info-card">
                    <label>生成类型</label>
                    <value>${basicInfo.generateType || 'N/A'}</value>
                </div>
                <div class="info-card">
                    <label>版本号</label>
                    <value>${basicInfo.version || 'N/A'}</value>
                </div>
                <div class="info-card">
                    <label>工序总数</label>
                    <value>${basicInfo.operationCount || 0}</value>
                </div>
                <div class="info-card">
                    <label>唯一订单数</label>
                    <value>${metrics.uniqueOrders || 0}</value>
                </div>
                <div class="info-card">
                    <label>唯一机器数</label>
                    <value>${metrics.uniqueMachines || 0}</value>
                </div>
                <div class="info-card">
                    <label>实际使用机器数</label>
                    <value>${metrics.totalMachinesUsed || 0}</value>
                </div>
                ${metrics.loadBalanceRatio ? `
                <div class="info-card">
                    <label>负载均衡率</label>
                    <value>${(metrics.loadBalanceRatio * 100).toFixed(2)}%</value>
                </div>
                ` : ''}
            `;
        }

        // 开始诊断
        async function startDiagnosis() {
            const diagnoseBtn = document.getElementById('diagnoseBtn');
            diagnoseBtn.disabled = true;
            diagnoseBtn.textContent = '诊断中...';

            try {
                const response = await fetch('/api/diagnose', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });
                
                const data = await response.json();
                
                if (data.success) {
                    displayReport(data.report);
                    document.getElementById('reportSection').classList.remove('hidden');
                    document.getElementById('chatSection').classList.remove('hidden');
                    document.getElementById('optimizeBtn').style.display = 'inline-block';
                    
                    // 滚动到报告区域
                    document.getElementById('reportSection').scrollIntoView({ behavior: 'smooth' });
                } else {
                    alert('诊断失败: ' + data.message);
                }
            } catch (error) {
                alert('诊断错误: ' + error.message);
            } finally {
                diagnoseBtn.disabled = false;
                diagnoseBtn.textContent = ' 开始AI诊断';
            }
        }

        // 显示诊断报告（支持 Markdown）
        function displayReport(report) {
            const reportDiv = document.getElementById('reportContent');
            // 使用 marked.js 渲染 Markdown
            reportDiv.innerHTML = marked.parse(report);
        }

        // 提问
        async function askQuestion() {
            const input = document.getElementById('questionInput');
            const question = input.value.trim();
            
            if (!question) return;

            // 显示用户问题
            addMessage('user', question);
            input.value = '';

            // 显示加载状态
            const loadingId = addMessage('ai', '<div class="spinner"></div><p>AI正在思考...</p>');

            try {
                const response = await fetch('/api/ask', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ question: question })
                });
                
                const data = await response.json();
                
                // 移除加载消息
                document.getElementById(loadingId).remove();
                
                if (data.success) {
                    addMessage('ai', data.answer);
                } else {
                    addMessage('ai', '❌ 回答失败: ' + data.message);
                }
            } catch (error) {
                document.getElementById(loadingId).remove();
                addMessage('ai', '❌ 网络错误: ' + error.message);
            }
        }

        // 添加消息
        function addMessage(type, content) {
            const messagesDiv = document.getElementById('chatMessages');
            const messageId = 'msg-' + Date.now();
            
            const messageDiv = document.createElement('div');
            messageDiv.id = messageId;
            messageDiv.className = `message ${type}`;
            messageDiv.innerHTML = content;
            
            messagesDiv.appendChild(messageDiv);
            messagesDiv.scrollTop = messagesDiv.scrollHeight;
            
            return messageId;
        }

        // 显示提示
        function showAlert(containerId, type, message) {
            const container = document.getElementById(containerId);
            container.innerHTML = `<div class="alert alert-${type}">${message}</div>`;
            
            setTimeout(() => {
                container.innerHTML = '';
            }, 5000);
        }
        
        // 开始优化
        async function startOptimization() {
            const optimizeBtn = document.getElementById('optimizeBtn');
            optimizeBtn.disabled = true;
            optimizeBtn.textContent = '优化中...';

            try {
                const response = await fetch('/api/optimize', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });
                
                const data = await response.json();
                
                if (data.success) {
                    // 存储优化文件路径
                    optimizedFilePath = data.outputFile;
                    
                    // 将优化结果显示在诊断报告区域
                    const reportContent = document.getElementById('reportContent');
                    const optimizationHtml = `
                        <div style="border-top: 3px solid #11998e; padding-top: 20px; margin-top: 30px;">
                            <h1>🚀 AI优化建议</h1>
                            ${marked.parse(data.optimizationAdvice || '优化完成')}
                            <div style="background: #d4edda; padding: 15px; border-radius: 8px; margin-top: 20px; border-left: 4px solid #28a745;">
                                <strong>✅ 优化文件已生成！</strong><br>
                                <small style="color: #155724;">${data.outputFile}</small>
                            </div>
                        </div>
                    `;
                    reportContent.innerHTML += optimizationHtml;
                    
                    // 显示下载按钮
                    document.getElementById('downloadBtn').style.display = 'inline-block';
                    
                    // 滚动到优化结果区域
                    reportContent.scrollIntoView({ behavior: 'smooth' });
                    
                    alert('优化完成！请查看报告底部的优化建议，并下载优化后的方案文件。');
                } else {
                    alert('优化失败: ' + data.message);
                }
            } catch (error) {
                alert('优化错误: ' + error.message);
            } finally {
                optimizeBtn.disabled = false;
                optimizeBtn.textContent = '🚀 AI智能优化排产';
            }
        }
        
        // 下载优化后的文件
        async function downloadOptimizedFile() {
            if (!optimizedFilePath) {
                alert('请先执行优化操作');
                return;
            }
            
            try {
                const response = await fetch('/api/download?filePath=' + encodeURIComponent(optimizedFilePath));
                
                if (response.ok) {
                    const blob = await response.blob();
                    const url = window.URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = optimizedFilePath.split('\\').pop().split('/').pop(); // 提取文件名
                    document.body.appendChild(a);
                    a.click();
                    window.URL.revokeObjectURL(url);
                    document.body.removeChild(a);
                } else {
                    alert('下载失败');
                }
            } catch (error) {
                alert('下载错误: ' + error.message);
            }
        }
    </script>
</body>
</html>
