<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>问题排查助手</title>
    <style>
        :root {
            --primary: #2563eb;
            --primary-hover: #1d4ed8;
            --success: #16a34a;
            --warning: #ca8a04;
            --danger: #dc2626;
            --gray-50: #f9fafb;
            --gray-100: #f3f4f6;
            --gray-200: #e5e7eb;
            --gray-500: #6b7280;
            --gray-700: #374151;
            --gray-900: #111827;
        }

        * { box-sizing: border-box; margin: 0; padding: 0; }

        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Microsoft YaHei", sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 40px 20px;
        }

        .container {
            max-width: 900px;
            margin: 0 auto;
        }

        .card {
            background: white;
            border-radius: 16px;
            box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
            overflow: hidden;
        }

        .card-header {
            background: linear-gradient(135deg, #1e3a8a 0%, #1e40af 100%);
            color: white;
            padding: 24px 32px;
        }

        .card-header h1 {
            font-size: 24px;
            font-weight: 700;
            margin-bottom: 4px;
        }

        .card-header p {
            opacity: 0.8;
            font-size: 14px;
        }

        .card-body {
            padding: 32px;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
        }

        @media (max-width: 600px) {
            .form-row { grid-template-columns: 1fr; }
        }

        .form-label {
            display: block;
            font-size: 14px;
            font-weight: 600;
            color: var(--gray-700);
            margin-bottom: 6px;
        }

        .form-label .required {
            color: var(--danger);
        }

        .form-input, .form-select, .form-textarea {
            width: 100%;
            padding: 12px 14px;
            border: 1px solid var(--gray-200);
            border-radius: 8px;
            font-size: 15px;
            transition: border-color 0.2s, box-shadow 0.2s;
        }

        .form-input:focus, .form-select:focus, .form-textarea:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.1);
        }

        .form-textarea {
            min-height: 120px;
            resize: vertical;
        }

        .form-hint {
            font-size: 12px;
            color: var(--gray-500);
            margin-top: 4px;
        }

        .btn {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            padding: 14px 28px;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.2s;
        }

        .btn-primary {
            background: var(--primary);
            color: white;
        }

        .btn-primary:hover {
            background: var(--primary-hover);
        }

        .btn-primary:disabled {
            opacity: 0.6;
            cursor: not-allowed;
        }

        .btn-secondary {
            background: var(--gray-100);
            color: var(--gray-700);
        }

        .btn-secondary:hover {
            background: var(--gray-200);
        }

        .btn-group {
            display: flex;
            gap: 12px;
            margin-top: 24px;
        }

        .alert {
            padding: 12px 16px;
            border-radius: 8px;
            font-size: 14px;
            margin-bottom: 20px;
        }

        .alert-warning {
            background: #fef3c7;
            border: 1px solid #fcd34d;
            color: #92400e;
        }

        /* 结果区域 */
        .result-section {
            display: none;
            margin-top: 32px;
            padding-top: 32px;
            border-top: 1px solid var(--gray-200);
        }

        .result-section.show {
            display: block;
        }

        .result-header {
            display: flex;
            align-items: center;
            gap: 12px;
            margin-bottom: 20px;
        }

        .result-header h2 {
            font-size: 18px;
            color: var(--gray-900);
        }

        .result-badge {
            background: #dcfce7;
            color: #166534;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 13px;
            font-weight: 600;
        }

        .matched-cases {
            background: var(--gray-50);
            border-radius: 8px;
            padding: 16px;
            margin-bottom: 20px;
        }

        .matched-cases h3 {
            font-size: 14px;
            color: var(--gray-700);
            margin-bottom: 12px;
        }

        .matched-case {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 8px 0;
            border-bottom: 1px solid var(--gray-200);
        }

        .matched-case:last-child {
            border-bottom: none;
        }

        .matched-score {
            background: #dbeafe;
            color: #1e40af;
            padding: 2px 8px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: 600;
        }

        .matched-title {
            flex: 1;
            font-size: 14px;
            color: var(--gray-700);
        }

        .response-content {
            background: var(--gray-50);
            border-radius: 8px;
            padding: 24px;
            line-height: 1.8;
        }

        .response-content h3 {
            color: var(--primary);
            margin-top: 20px;
            margin-bottom: 12px;
            font-size: 16px;
        }

        .response-content h3:first-child {
            margin-top: 0;
        }

        .response-content p, .response-content li {
            color: var(--gray-700);
            font-size: 14px;
        }

        .response-content ul {
            padding-left: 20px;
            margin: 8px 0;
        }

        .response-content code {
            background: #f1f5f9;
            color: #1e40af;
            padding: 2px 8px;
            border-radius: 4px;
            font-size: 13px;
            font-family: "Cascadia Code", "Fira Code", "Consolas", monospace;
            border: 1px solid #e2e8f0;
        }

        .response-content .warning-box {
            background: #fef3c7;
            border-left: 3px solid #f59e0b;
            padding: 12px 16px;
            margin: 16px 0;
            border-radius: 0 8px 8px 0;
        }

        .submit-section {
            margin-top: 24px;
            padding: 16px;
            background: #f0fdf4;
            border-radius: 8px;
            border: 1px solid #86efac;
        }

        .submit-section p {
            color: #166534;
            font-size: 14px;
            margin-bottom: 12px;
        }

        /* 加载状态 */
        .loading {
            display: none;
            align-items: center;
            gap: 12px;
            padding: 40px;
            text-align: center;
        }

        .loading.show {
            display: flex;
            justify-content: center;
        }

        .spinner {
            width: 32px;
            height: 32px;
            border: 3px solid var(--gray-200);
            border-top-color: var(--primary);
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            to { transform: rotate(360deg); }
        }

        .loading-text, #loadingText {
            color: var(--gray-700);
            font-size: 14px;
        }

        /* 模态框 */
        .modal-overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            z-index: 1000;
            justify-content: center;
            align-items: flex-start;
            padding-top: 60px;
            overflow-y: auto;
        }

        .modal-overlay.show {
            display: flex;
        }

        .modal {
            background: white;
            border-radius: 16px;
            box-shadow: 0 25px 50px rgba(0, 0, 0, 0.3);
            width: 600px;
            max-width: 95%;
            overflow: hidden;
        }

        .modal-header {
            background: var(--primary);
            color: white;
            padding: 20px 24px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .modal-header h3 {
            font-size: 18px;
            margin: 0;
        }

        .modal-close {
            background: none;
            border: none;
            color: white;
            font-size: 24px;
            cursor: pointer;
            opacity: 0.8;
        }

        .modal-close:hover {
            opacity: 1;
        }

        .modal-body {
            padding: 24px;
        }

        .modal-body .form-group {
            margin-bottom: 16px;
        }

        .modal-body .form-textarea {
            min-height: 80px;
        }

        .modal-footer {
            padding: 16px 24px;
            border-top: 1px solid var(--gray-200);
            display: flex;
            gap: 12px;
            justify-content: flex-end;
        }

        .success-toast {
            display: none;
            position: fixed;
            top: 20px;
            right: 20px;
            background: var(--success);
            color: white;
            padding: 16px 24px;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
            z-index: 2000;
            font-size: 14px;
            font-weight: 600;
        }

        .success-toast.show {
            display: block;
            animation: slideIn 0.3s ease;
        }

        @keyframes slideIn {
            from { transform: translateX(100px); opacity: 0; }
            to { transform: translateX(0); opacity: 1; }
        }

        /* 页脚 */
        .footer {
            text-align: center;
            padding: 20px;
            color: white;
            opacity: 0.8;
            font-size: 12px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="card">
            <div class="card-header">
                <h1>🔍 问题排查助手</h1>
                <p>基于 357 条历史问题记录 · AI 智能分析 · 安全过滤</p>
            </div>

            <!-- 用户信息栏 -->
            <div class="user-info-bar" style="background: #eff6ff; padding: 12px 32px; border-bottom: 1px solid #dbeafe; display: flex; justify-content: space-between; align-items: center;">
                <div>
                    <span id="userDisplayName" style="font-weight: 600; color: #1e40af;">加载中...</span>
                </div>
                <button class="btn btn-secondary" onclick="logout()" style="padding: 8px 16px; font-size: 14px;">
                    🚪 退出
                </button>
            </div>

            <div class="card-body">
                <div class="alert alert-warning">
                    ⚠️ 排查步骤均为只读操作，不会修改系统。如需执行重启/删除等危险操作，请联系研发组。
                </div>

                <form id="troubleshootForm">
                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label">
                                项目名称 <span class="required">*</span>
                            </label>
                            <input type="text"
                                   id="projectName"
                                   class="form-input"
                                   placeholder="输入项目名称，如：厦门银行"
                                   list="projectList"
                                   autocomplete="off">
                            <datalist id="projectList"></datalist>
                            <p class="form-hint">可手动输入或从列表选择</p>
                        </div>

                        <div class="form-group">
                            <label class="form-label">
                                系统类型 <span class="required">*</span>
                            </label>
                            <select id="systemType" class="form-select">
                                <option value="">请选择...</option>
                                <option value="标准版预定2.0">标准版预定2.0</option>
                                <option value="标准版运维集控系统">标准版运维集控系统</option>
                                <option value="新统一平台">新统一平台</option>
                                <option value="统一平台">统一平台</option>
                            </select>
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="form-label">APK 产品</label>
                        <input type="text"
                               id="apkProduct"
                               class="form-input"
                               placeholder="如：门口屏5.0、无纸化、桌牌（可选）">
                        <p class="form-hint">仅涉及 APK 产品时填写</p>
                    </div>

                    <div class="form-group">
                        <label class="form-label">模型选择</label>
                        <select id="modelSelect" class="form-select">
                            <option value="glm-4-flash">快速模式（5-10秒，简单问题）</option>
                            <option value="glm-5.1" selected>标准模式（20-50秒，推荐）</option>
                            <option value="glm-4-plus">深度模式（30-60秒，复杂问题）</option>
                        </select>
                        <p class="form-hint">快速模式适合简单问题，深度模式适合复杂问题</p>
                    </div>

                    <div class="form-group">
                        <label class="form-label">
                            问题描述 <span class="required">*</span>
                        </label>
                        <textarea id="query"
                                  class="form-textarea"
                                  placeholder="请详细描述遇到的问题，例如：&#10;门口屏绑定失败，提示 MQTT 连接错误...&#10;&#10;包含以下信息有助于更精准分析：&#10;- 报错信息或截图内容&#10;- 问题发生时间&#10;- 近期是否有变更"></textarea>
                    </div>

                    <div class="btn-group">
                        <button type="submit" class="btn btn-primary" id="submitBtn">
                            🔬 帮我排查
                        </button>
                        <button type="button" class="btn btn-secondary" onclick="clearForm()">
                            🔄 清空
                        </button>
                    </div>
                </form>

                <!-- 加载状态 -->
                <div class="loading" id="loading">
                    <div class="spinner"></div>
                    <span id="loadingText">正在分析问题...</span>
                </div>

                <!-- 结果区域 -->
                <div class="result-section" id="resultSection">
                    <div class="result-header">
                        <h2>✅ 排查诊断结果</h2>
                        <span class="result-badge" id="resultTime"></span>
                    </div>

                    <!-- 匹配案例 -->
                    <div class="matched-cases" id="matchedCases">
                        <h3>📋 匹配到的历史案例</h3>
                        <!-- 动态填充 -->
                    </div>

                    <!-- AI 响应 -->
                    <div class="response-content" id="responseContent">
                        <!-- 动态填充 -->
                    </div>

                    <!-- 导出和提交按钮区域 -->
                    <div style="margin-top: 24px; display: flex; gap: 12px; justify-content: flex-end;">
                        <button class="btn btn-secondary" onclick="exportReport()" id="exportBtn" style="display:none;">
                            📄 导出 Word 文档
                        </button>
                    </div>

                    <!-- 提交入库 -->
                    <div class="submit-section" id="submitSection" style="display:none;">
                        <p>✅ 问题已解决？点击提交记录入库，帮助其他同事快速排查同类问题。</p>
                        <button class="btn btn-primary" onclick="submitRecord()">
                            📝 提交记录入库
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <div class="footer">
            问题排查助手 · 基于 Claude AI · 安全过滤保障
            <button class="btn btn-secondary" onclick="showCacheModal()" style="margin-left: 20px; padding: 8px 16px; font-size: 13px;">
                📊 缓存管理
            </button>
        </div>
    </div>

    <script>
        // ============================================================
        // 数据
        // ============================================================
        let projectList = [];
        let lastMatchedCases = [];  // 保存最近一次匹配的案例，用于导出

        // ============================================================
        // 模型选择 localStorage 持久化
        // ============================================================
        const MODEL_STORAGE_KEY = 'troubleshoot_model';

        // 恢复模型选择
        function restoreModelSelection() {
            const savedModel = localStorage.getItem(MODEL_STORAGE_KEY);
            const modelSelect = document.getElementById('modelSelect');

            if (savedModel) {
                // 恢复上次的选择
                modelSelect.value = savedModel;
            } else {
                // 默认选择标准模式
                modelSelect.value = 'glm-5.1';
            }
        }

        // 监听模型选择变化
        function initModelSelection() {
            const modelSelect = document.getElementById('modelSelect');
            modelSelect.addEventListener('change', function() {
                const selectedModel = this.value;
                localStorage.setItem(MODEL_STORAGE_KEY, selectedModel);
                console.log('模型选择已保存:', selectedModel);
            });
        }

        // 加载项目列表
        async function loadProjects() {
            try {
                const resp = await fetch('/api/projects');
                const data = await resp.json();
                if (data.success) {
                    projectList = data.projects;
                    const datalist = document.getElementById('projectList');
                    datalist.innerHTML = projectList.map(p => `<option value="${p}">`).join('');
                }
            } catch (e) {
                console.error('加载项目列表失败:', e);
            }
        }

        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', () => {
            loadUserInfo();           // 加载用户信息
            restoreModelSelection();  // 恢复模型选择
            initModelSelection();     // 初始化监听
            loadProjects();
        });

        // ============================================================
        // 用户信息加载与退出
        // ============================================================

        async function loadUserInfo() {
            try {
                const resp = await fetch('/api/user/info', { credentials: 'include' });
                const data = await resp.json();

                if (data.success) {
                    const user = data.user;
                    const roleText = user.role === 'admin' ? '管理员' : '用户';
                    const displayName = `${user.username}（${roleText}）`;
                    document.getElementById('userDisplayName').textContent = displayName;

                    // 根据角色显示/隐藏缓存管理按钮
                    if (user.role !== 'admin') {
                        const cacheBtn = document.querySelector('button[onclick="showCacheModal()"]');
                        if (cacheBtn) {
                            cacheBtn.style.display = 'none';
                        }
                    }
                } else {
                    // 未登录，跳转登录页
                    window.location.href = '/login';
                }
            } catch (e) {
                console.error('获取用户信息失败:', e);
                // 跳转登录页
                window.location.href = '/login';
            }
        }

        async function logout() {
            if (!confirm('确定要退出登录吗？')) {
                return;
            }

            try {
                const resp = await fetch('/logout', { method: 'POST', credentials: 'include' });
                window.location.href = '/login';
            } catch (e) {
                alert('退出失败');
            }
        }

        // ============================================================
        // 表单提交 — 流式返回（SSE）
        // ============================================================
        document.getElementById('troubleshootForm').addEventListener('submit', async (e) => {
            e.preventDefault();

            const projectName = document.getElementById('projectName').value.trim();
            const systemType = document.getElementById('systemType').value;
            const apkProduct = document.getElementById('apkProduct').value.trim();
            const query = document.getElementById('query').value.trim();
            const model = document.getElementById('modelSelect').value;

            // 验证
            if (!projectName) {
                alert('请输入项目名称');
                return;
            }
            if (!systemType) {
                alert('请选择系统类型');
                return;
            }
            if (!query) {
                alert('请输入问题描述');
                return;
            }

            // 显示加载状态
            showLoading('正在连接服务...');
            document.getElementById('resultSection').classList.remove('show');
            document.getElementById('submitBtn').disabled = true;

            // 使用 SSE 流式返回
            startStreamAnalyze(projectName, systemType, apkProduct, query, model);
        });

        // ============================================================
        // SSE 流式返回
        // ============================================================
        function startStreamAnalyze(projectName, systemType, apkProduct, query) {
            // 构建 URL
            const params = new URLSearchParams({
                project_name: projectName,
                system_type: systemType,
                apk_product: apkProduct || '',
                query: query
            });

            const url = `/api/analyze/stream?${params.toString()}`;
            const source = new EventSource(url);

            // 结果容器
            let fullContent = '';
            let matchedCasesShown = false;

            // 监听消息
            source.onmessage = function(event) {
                const data = JSON.parse(event.data);

                switch (data.type) {
                    case 'start':
                        updateLoadingText(data.message || '正在分析...');
                        break;

                    case 'matched_cases':
                        // 显示匹配案例
                        if (!matchedCasesShown && data.cases && data.cases.length > 0) {
                            lastMatchedCases = data.cases;  // 保存匹配案例，用于导出
                            showMatchedCases(data.cases, '<1s');
                            matchedCasesShown = true;
                        }
                        updateLoadingText('正在生成排查步骤...');
                        break;

                    case 'chunk':
                        // 追加内容
                        fullContent += data.content;
                        updateResponseContent(fullContent);
                        break;

                    case 'done':
                        source.close();
                        hideLoading();
                        document.getElementById('resultTime').textContent = `AI 分析 ${data.api_time}s`;
                        document.getElementById('submitSection').style.display = 'block';
                        document.getElementById('exportBtn').style.display = 'inline-flex';  // 显示导出按钮
                        document.getElementById('submitBtn').disabled = false;
                        break;

                    case 'error':
                        source.close();
                        hideLoading();
                        alert('分析失败：' + data.message);
                        document.getElementById('submitBtn').disabled = false;
                        break;
                }
            };

            // 监听错误
            source.onerror = function(event) {
                // 只在连接尚未收到任何数据时报错
                if (fullContent === '' && !matchedCasesShown) {
                    source.close();
                    hideLoading();
                    console.error('SSE 连接错误');
                    // 降级：尝试普通请求
                    fallbackToNormalRequest(projectName, systemType, apkProduct, query);
                }
            };
        }

        // 降级：普通请求
        async function fallbackToNormalRequest(projectName, systemType, apkProduct, query) {
            try {
                updateLoadingText('正在尝试普通模式...');

                // 搜索
                const searchResp = await fetch('/api/search', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ project_name: projectName, query: query }),
                });
                const searchData = await searchResp.json();

                if (searchData.success) {
                    showMatchedCases(searchData.matched_cases, searchData.search_time);
                }

                // 分析
                const analyzeResp = await fetch('/api/analyze', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        project_name: projectName,
                        system_type: systemType,
                        apk_product: apkProduct,
                        query: query,
                        matched_cases: searchData.matched_cases || [],
                    }),
                });
                const analyzeData = await analyzeResp.json();

                if (analyzeData.success) {
                    showAIResponse(analyzeData);
                } else {
                    alert('分析失败：' + analyzeData.error);
                }
            } catch (e) {
                alert('服务异常，请稍后重试');
            } finally {
                hideLoading();
                document.getElementById('submitBtn').disabled = false;
            }
        }

        // 更新响应内容（追加显示）
        function updateResponseContent(content) {
            const container = document.getElementById('responseContent');

            // 确保 resultSection 可见
            document.getElementById('resultSection').classList.add('show');

            // 渲染 Markdown
            container.innerHTML = renderMarkdown(content);

            // 滚动到底部
            container.scrollTop = container.scrollHeight;
        }

        // ============================================================
        // 加载状态控制（P2 优化：分阶段进度提示）
        // ============================================================
        function showLoading(text) {
            document.getElementById('loading').classList.add('show');
            document.getElementById('loadingText').textContent = text;
        }

        function updateLoadingText(text) {
            document.getElementById('loadingText').textContent = text;
        }

        function hideLoading() {
            document.getElementById('loading').classList.remove('show');
        }

        // ============================================================
        // 渲染匹配案例（阶段一立即显示）
        // ============================================================
        function showMatchedCases(matchedCases, searchTime) {
            const section = document.getElementById('resultSection');
            section.classList.add('show');

            // 显示匹配案例卡片
            const casesHtml = matchedCases.map(c => `
                <div class="matched-case">
                    <span class="matched-score">${Math.round(c.score * 100)}%</span>
                    <span class="matched-title">${c.project ? '[' + c.project + '] ' : ''}${c.title}</span>
                </div>
            `).join('');

            document.getElementById('matchedCases').innerHTML = `
                <h3>📋 匹配到的历史案例（搜索耗时 ${searchTime}s）</h3>
                ${casesHtml}
            `;

            // 清空 AI 响应区域，等待分析
            document.getElementById('responseContent').innerHTML = `
                <div style="text-align: center; padding: 20px; color: #6b7280;">
                    <div class="spinner" style="margin: 0 auto 12px;"></div>
                    <p>正在等待 AI 分析结果...</p>
                </div>
            `;

            // 更新耗时徽章
            document.getElementById('resultTime').textContent = `搜索 ${searchTime}s | AI 分析中...`;
        }

        // ============================================================
        // 渲染 AI 分析结果（阶段二追加显示）
        // ============================================================
        function showAIResponse(data) {
            // 更新耗时
            document.getElementById('resultTime').textContent = `AI 分析 ${data.api_time}s`;

            // 渲染 AI 响应
            const responseHtml = renderMarkdown(data.response);
            document.getElementById('responseContent').innerHTML = responseHtml;

            // 显示提交按钮
            document.getElementById('submitSection').style.display = 'block';
        }

        // ============================================================
        // 简单 Markdown 渲染
        // ============================================================
        function renderMarkdown(text) {
            if (!text) return '';

            // 标题
            text = text.replace(/^### (.+)$/gm, '<h3>$1</h3>');
            text = text.replace(/^## (.+)$/gm, '<h3>$1</h3>');

            // 加粗
            text = text.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>');

            // 代码块
            text = text.replace(/`([^`]+)`/g, '<code>$1</code>');

            // 列表
            text = text.replace(/^- (.+)$/gm, '<li>$1</li>');
            text = text.replace(/^(\d+)\. (.+)$/gm, '<li>$2</li>');

            // 警告
            text = text.replace(/⚠️/g, '⚠️ ');

            // 段落
            text = text.replace(/\n\n/g, '</p><p>');
            text = '<p>' + text + '</p>';

            return text;
        }

        // ============================================================
        // 清空表单
        // ============================================================
        function clearForm() {
            document.getElementById('projectName').value = '';
            document.getElementById('systemType').value = '';
            document.getElementById('apkProduct').value = '';
            document.getElementById('query').value = '';
            document.getElementById('resultSection').classList.remove('show');
        }

        // ============================================================
        // 提交记录入库
        // ============================================================
        let lastTroubleshootData = null;

        function submitRecord() {
            // 收集表单数据
            const projectName = document.getElementById('projectName').value.trim();
            const systemType = document.getElementById('systemType').value;
            const apkProduct = document.getElementById('apkProduct').value.trim();
            const query = document.getElementById('query').value.trim();

            // 预填数据
            document.getElementById('modalProjectName').value = projectName;
            document.getElementById('modalPhenomenon').value = query;

            // 自动填充排查步骤（从响应中提取）
            const responseEl = document.getElementById('responseContent');
            const stepsText = responseEl ? responseEl.innerText.replace(/⚠️ 注意事项[\s\S]*/, '').trim() : '';

            document.getElementById('modalTroubleshootSteps').value = stepsText;
            document.getElementById('modalRootCause').value = '';
            document.getElementById('modalSolution').value = '';
            document.getElementById('modalRecorder').value = '';

            // 显示模态框
            document.getElementById('submitModal').classList.add('show');
        }

        function closeSubmitModal() {
            document.getElementById('submitModal').classList.remove('show');
        }

        async function confirmSubmit() {
            const data = {
                project_name: document.getElementById('modalProjectName').value.trim(),
                phenomenon: document.getElementById('modalPhenomenon').value.trim(),
                system_type: document.getElementById('systemType').value,
                apk_product: document.getElementById('apkProduct').value.trim(),
                troubleshoot_steps: document.getElementById('modalTroubleshootSteps').value.trim(),
                root_cause: document.getElementById('modalRootCause').value.trim(),
                solution: document.getElementById('modalSolution').value.trim(),
                recorder: document.getElementById('modalRecorder').value.trim(),
            };

            // 必填校验
            if (!data.project_name) { alert('请输入项目名称'); return; }
            if (!data.phenomenon) { alert('请输入问题现象'); return; }
            if (!data.recorder) { alert('请输入记录人'); return; }

            try {
                const resp = await fetch('/api/submit', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(data),
                });
                const result = await resp.json();
                if (result.success) {
                    closeSubmitModal();
                    showToast('提交成功！问题已入库');
                } else {
                    alert('提交失败：' + result.error);
                }
            } catch (e) {
                console.error(e);
                alert('提交异常，请稍后重试');
            }
        }

        function showToast(message) {
            const toast = document.getElementById('successToast');
            toast.textContent = message;
            toast.classList.add('show');
            setTimeout(() => {
                toast.classList.remove('show');
            }, 3000);
        }

        // ============================================================
        // 缓存管理
        // ============================================================

        async function showCacheModal() {
            document.getElementById('cacheModal').classList.add('show');

            // 获取缓存统计
            try {
                const resp = await fetch('/api/cache/stats');
                const data = await resp.json();

                if (data.success) {
                    document.getElementById('cacheTotalFiles').textContent = data.stats.total_files || 0;
                    document.getElementById('cacheTotalSize').textContent = (data.stats.total_size_mb || 0) + ' MB';
                    document.getElementById('cacheOldest').textContent = data.stats.oldest || '-';
                    document.getElementById('cacheNewest').textContent = data.stats.newest || '-';
                } else {
                    console.error('获取缓存统计失败:', data.error);
                }
            } catch (e) {
                console.error('获取缓存统计失败:', e);
                alert('获取缓存统计失败，请检查服务是否正常');
            }
        }

        function closeCacheModal() {
            document.getElementById('cacheModal').classList.remove('show');
        }

        async function clearCache() {
            const confirmed = confirm('确定要清空所有缓存吗？这将删除所有已缓存的排查结果。');

            if (!confirmed) {
                return;
            }

            try {
                const resp = await fetch('/api/cache/clear', { method: 'POST' });
                const data = await resp.json();

                if (data.success) {
                    alert(data.message);
                    showCacheModal(); // 刷新统计信息
                } else {
                    alert('清空缓存失败：' + data.error);
                }
            } catch (e) {
                alert('清空缓存异常：' + e.message);
            }
        }

        // ============================================================
        // 导出功能
        // ============================================================

        async function exportReport() {
            // 收集数据
            const projectName = document.getElementById('projectName').value.trim();
            const systemType = document.getElementById('systemType').value;
            const apkProduct = document.getElementById('apkProduct').value.trim();
            const query = document.getElementById('query').value.trim();

            // 获取 AI 响应内容（从结果区域提取）
            const responseEl = document.getElementById('responseContent');
            const response = responseEl ? responseEl.innerText : '';

            // 获取匹配案例
            const matchedCases = lastMatchedCases || [];

            // 显示加载提示
            const exportBtn = document.getElementById('exportBtn');
            const originalText = exportBtn.innerHTML;
            exportBtn.innerHTML = '⏳ 导出中...';
            exportBtn.disabled = true;

            try {
                const resp = await fetch('/api/export', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        project_name: projectName,
                        system_type: systemType,
                        apk_product: apkProduct,
                        query: query,
                        matched_cases: matchedCases,
                        response: response,
                    }),
                });

                if (resp.ok) {
                    // 触发下载
                    const blob = await resp.blob();
                    const url = window.URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);
                    a.download = `排查报告_${projectName}_${timestamp}.docx`;
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                    window.URL.revokeObjectURL(url);

                    showToast('导出成功！');
                } else {
                    const errorData = await resp.json();
                    alert('导出失败：' + (errorData.error || '未知错误'));
                }
            } catch (e) {
                alert('导出异常：' + e.message);
            } finally {
                // 恢复按钮状态
                exportBtn.innerHTML = originalText;
                exportBtn.disabled = false;
            }
        }
    </script>

    <!-- 提交入库模态框 -->
    <div class="modal-overlay" id="submitModal">
        <div class="modal">
            <div class="modal-header">
                <h3>提交问题记录</h3>
                <button class="modal-close" onclick="closeSubmitModal()">✕</button>
            </div>
            <div class="modal-body">
                <div class="form-group">
                    <label class="form-label">项目名称 <span style="color:var(--danger)">*</span></label>
                    <input type="text" id="modalProjectName" class="form-input" placeholder="项目名称">
                </div>
                <div class="form-group">
                    <label class="form-label">问题现象 <span style="color:var(--danger)">*</span></label>
                    <textarea id="modalPhenomenon" class="form-textarea" placeholder="描述遇到的问题"></textarea>
                </div>
                <div class="form-group">
                    <label class="form-label">排查过程</label>
                    <textarea id="modalTroubleshootSteps" class="form-textarea" placeholder="排查步骤（自动填充，可编辑）"></textarea>
                </div>
                <div class="form-group">
                    <label class="form-label">实际根因</label>
                    <textarea id="modalRootCause" class="form-textarea" placeholder="请填写排查确认的根因"></textarea>
                </div>
                <div class="form-group">
                    <label class="form-label">解决方案</label>
                    <textarea id="modalSolution" class="form-textarea" placeholder="请填写解决方案"></textarea>
                </div>
                <div class="form-group">
                    <label class="form-label">记录人 <span style="color:var(--danger)">*</span></label>
                    <input type="text" id="modalRecorder" class="form-input" placeholder="请填写您的姓名">
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn btn-secondary" onclick="closeSubmitModal()">取消</button>
                <button class="btn btn-primary" onclick="confirmSubmit()">确认提交</button>
            </div>
        </div>
    </div>

    <!-- 缓存管理模态框 -->
    <div class="modal-overlay" id="cacheModal">
        <div class="modal">
            <div class="modal-header">
                <h3>📊 缓存管理</h3>
                <button class="modal-close" onclick="closeCacheModal()">✕</button>
            </div>
            <div class="modal-body">
                <div id="cacheStats" style="line-height: 2;">
                    <p><strong>缓存文件总数：</strong><span id="cacheTotalFiles">加载中...</span></p>
                    <p><strong>缓存总大小：</strong><span id="cacheTotalSize">加载中...</span></p>
                    <p><strong>最早缓存时间：</strong><span id="cacheOldest">加载中...</span></p>
                    <p><strong>最新缓存时间：</strong><span id="cacheNewest">加载中...</span></p>
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn btn-secondary" onclick="closeCacheModal()">关闭</button>
                <button class="btn btn-primary" onclick="clearCache()" style="background: var(--danger);">
                    🗑️ 清除所有缓存
                </button>
            </div>
        </div>
    </div>

    <!-- 成功提示 -->
    <div class="success-toast" id="successToast"></div>

</body>
</html>