<!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: #1e293b;
            color: #e2e8f0;
            padding: 2px 8px;
            border-radius: 4px;
            font-size: 13px;
            font-family: "Cascadia Code", "Fira Code", monospace;
        }

        .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 {
            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="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">
                            问题描述 <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 class="loading-text">正在分析问题...</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 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 · 安全过滤保障
        </div>
    </div>

    <script>
        // ============================================================
        // 数据
        // ============================================================
        let projectList = [];

        // 加载项目列表
        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', () => {
            loadProjects();
        });

        // ============================================================
        // 表单提交 — 渐进式两阶段请求（P0 优化）
        // ============================================================
        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();

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

            // 显示加载状态（阶段一）
            showLoading('🔍 正在搜索历史案例...');
            document.getElementById('resultSection').classList.remove('show');
            document.getElementById('submitBtn').disabled = true;

            try {
                // ===== 阶段一：搜索匹配案例 =====
                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) {
                    alert('搜索失败：' + searchData.error);
                    return;
                }

                // 立即显示匹配案例（<3s）
                showMatchedCases(searchData.matched_cases, searchData.search_time);

                // ===== 阶段二：AI 深度分析 =====
                updateLoadingText(`📋 找到 ${searchData.matched_count} 个相似案例，正在进行 AI 深度分析...`);

                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) {
                console.error(e);
                alert('服务异常，请稍后重试');
            } finally {
                hideLoading();
                document.getElementById('submitBtn').disabled = false;
            }
        });

        // ============================================================
        // 加载状态控制（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);
        }
    </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="success-toast" id="successToast"></div>

</body>
</html>