<!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>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Helvetica Neue', STHeiti, 'Microsoft Yahei', sans-serif;
            background: #f5f5f5;
            color: #333;
            line-height: 1.5;
        }

        .container {
            min-height: 100vh;
            background: #f5f5f5;
        }

        .header {
            background: linear-gradient(135deg, #dbeafe 0%, #bfdbfe 100%);
            color: #1e40af;
            padding: 20px;
            text-align: center;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 16px;
        }

        .header-logo {
            height: 60px;
            width: auto;
            object-fit: contain;
        }

        .header h1 {
            font-size: 24px;
            font-weight: 600;
            margin-bottom: 8px;
        }

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

        .content {
            max-width: 1400px;
            margin: 0 auto;
            padding: 20px;
        }

        .card {
            background: white;
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 16px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.08);
        }

        .card-title {
            font-size: 18px;
            font-weight: 600;
            color: #333;
            margin-bottom: 16px;
            position: relative;
            padding-left: 16px;
        }

        .card-title::before {
            content: '';
            position: absolute;
            left: 0;
            top: 50%;
            transform: translateY(-50%);
            width: 4px;
            height: 18px;
            background: linear-gradient(135deg, #3b82f6 0%, #60a5fa 100%);
            border-radius: 2px;
        }

        .loading {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            padding: 40px 20px;
        }

        .loading-spinner {
            width: 40px;
            height: 40px;
            border: 4px solid #f3f3f3;
            border-top: 4px solid #3b82f6;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-bottom: 16px;
        }

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

        .loading-text {
            color: #666;
            font-size: 14px;
        }

        .error {
            background: linear-gradient(135deg, #fee2e2 0%, #fecaca 100%);
            color: #dc2626;
            padding: 16px;
            border-radius: 8px;
            border-left: 4px solid #dc2626;
            margin-bottom: 16px;
        }

        .patient-info {
            background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
            position: relative;
        }

        .patient-info-content {
            flex: 1;
            padding-right: 120px;
        }

        .patient-status {
            position: absolute;
            top: 20px;
            right: 20px;
        }

        .info-grid {
            display: grid;
            grid-template-columns: 1fr 2fr;
            gap: 16px;
        }

        .info-item {
            display: flex;
            flex-direction: column;
        }

        .info-label {
            font-size: 12px;
            color: #666;
            font-weight: 500;
            margin-bottom: 4px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .info-value {
            font-size: 16px;
            color: #333;
            font-weight: 600;
        }

        /* 中部两栏布局 */
        .middle-section {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 16px;
            margin-bottom: 16px;
            align-items: stretch;
        }

        .image-card-wrapper {
            grid-column: 1;
            display: flex;
        }

        .features-card-wrapper {
            grid-column: 2;
            display: flex;
        }

        .image-card-wrapper .card,
        .features-card-wrapper .card {
            width: 100%;
            display: flex;
            flex-direction: column;
            height: 100%;
        }

        .image-section {
            flex: 1;
            display: flex;
            flex-direction: column;
            min-height: 0;
        }

        .tongue-image-wrapper {
            flex: 1;
            display: flex;
            align-items: center;
            justify-content: center;
            min-height: 0;
        }

        .image-section .tongue-image {
            max-width: 100%;
            max-height: 100%;
            object-fit: contain;
            border-radius: 12px;
            box-shadow: 0 4px 16px rgba(0,0,0,0.1);
        }

        .features-card-wrapper .card {
            min-height: 100%;
        }

        .features-list {
            flex: 1;
        }

        .image-section {
            text-align: center;
        }


        .diagnosis-section {
            background: linear-gradient(135deg, #f0fdf4 0%, #dcfce7 100%);
        }

        .result-text {
            font-size: 14px;
            line-height: 1.6;
            color: #374151;
            white-space: pre-wrap;
            word-break: break-word;
        }

        .features-list {
            display: grid;
            gap: 12px;
            margin-top: 0;
        }

        .feature-item {
            background: #f8fafc;
            padding: 12px;
            border-radius: 8px;
            border-left: 3px solid #3b82f6;
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 12px;
        }

        .feature-content {
            font-size: 14px;
            color: #374151;
            line-height: 1.5;
            flex: 1;
        }

        .feature-confidence {
            font-size: 12px;
            color: #3b82f6;
            padding: 4px 12px;
            background: #eff6ff;
            border: 1px solid #3b82f6;
            border-radius: 50px;
            white-space: nowrap;
            font-weight: 500;
        }

        .status-badge {
            display: inline-flex;
            align-items: center;
            padding: 6px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 500;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .status-completed {
            background: linear-gradient(135deg, #d1fae5 0%, #a7f3d0 100%);
            color: #065f46;
        }

        .status-pending {
            background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);
            color: #92400e;
        }

    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <img src="/pic.png" alt="AI舌诊系统" class="header-logo" />
            <div>
                <h1>陇医小郎中</h1>
                <p>智能舌诊 · 精准分析</p>
            </div>
        </div>

        <div class="content">
            <!-- 加载状态 -->
            <div id="loading" class="loading">
                <div class="loading-spinner"></div>
                <p class="loading-text">正在加载舌诊详情...</p>
            </div>

            <!-- 错误提示 -->
            <div id="error" class="error" style="display: none;"></div>

            <!-- 患者信息和诊断状态（顶部横栏） -->
            <div id="patientInfo" class="card patient-info" style="display: none;">
                <div class="patient-info-content">
                    <h2 class="card-title">患者信息</h2>
                    <div class="info-grid">
                        <div class="info-item">
                            <div class="info-label">患者ID</div>
                            <div class="info-value" id="patientId">--</div>
                        </div>
                        <div class="info-item">
                            <div class="info-label">主诉</div>
                            <div class="info-value" id="patientComplaint">--</div>
                        </div>
                    </div>
                </div>
                <div class="patient-status">
                    <div class="status-badge status-completed" id="statusBadge" style="display: none;">诊断已完成</div>
                </div>
            </div>

            <!-- 中部两栏布局：左边图片，右边关键特征 -->
            <div id="middleSection" class="middle-section" style="display: none;">
                <!-- 左边：舌象图片 -->
                <div class="image-card-wrapper">
                    <div id="imageCard" class="card image-section" style="display: none;">
                        <h2 class="card-title">舌象照片</h2>
                        <div class="tongue-image-wrapper">
                            <img id="tongueImage" src="" alt="舌象照片" class="tongue-image" />
                        </div>
                    </div>
                </div>

                <!-- 右边：关键特征和诊断结论 -->
                <div class="features-card-wrapper">
                    <div id="featuresCard" class="card" style="display: none;">
                        <h2 class="card-title">关键特征</h2>
                        <div id="featuresList" class="features-list"></div>

                        <!-- 诊断结论（底部） -->
                        <div id="diagnosisSectionRight" style="display: none; margin-top: 24px; padding-top: 24px; border-top: 1px solid #e5e7eb;">
                            <h3 style="font-size: 16px; font-weight: 600; color: #333; margin: 0 0 12px 0;">诊断结论</h3>
                            <div class="result-text" id="diagnosisResultRight"></div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 诊断结果（底部横栏） -->
            <div id="diagnosisCard" class="card diagnosis-section" style="display: none;">
                <h2 class="card-title">AI诊断结果</h2>

                <!-- 症候 -->
                <div id="syndromeSection" style="display: none; margin-bottom: 20px;">
                    <h3 style="font-size: 16px; font-weight: 600; color: #333; margin: 0 0 12px 0;">症候</h3>
                    <div class="result-text" id="syndromeText"></div>
                </div>

                <!-- 处方 -->
                <div id="prescriptionSection" style="display: none; margin-bottom: 20px;">
                    <h3 style="font-size: 16px; font-weight: 600; color: #333; margin: 0 0 12px 0;">处方</h3>
                    <div class="result-text" id="prescriptionText"></div>
                </div>

                <!-- 诊断 -->
                <div id="diagnosisSection" style="display: none; margin-bottom: 20px;">
                    <h3 style="font-size: 16px; font-weight: 600; color: #333; margin: 0 0 12px 0;">诊断</h3>
                    <div class="result-text" id="diagnosisText"></div>
                </div>

                <!-- 中医体质分析 -->
                <!-- <div id="constitutionSection" style="display: none; margin-bottom: 20px;">
                    <h3 style="font-size: 16px; font-weight: 600; color: #333; margin: 0 0 12px 0;">中医体质分析</h3>
                    <div class="result-text" id="constitutionAnalysis"></div>
                </div> -->

                <!-- 舌象状态评估 -->
                <div id="assessmentSection" style="display: none; margin-bottom: 20px;">
                    <h3 style="font-size: 16px; font-weight: 600; color: #333; margin: 0 0 12px 0;">舌象状态评估</h3>
                    <div class="result-text" id="tongueAssessment"></div>
                </div>

                <!-- 治疗建议 -->
                <div id="adviceSection" style="display: none; margin-bottom: 20px;">
                    <h3 style="font-size: 16px; font-weight: 600; color: #333; margin: 0 0 12px 0;">治疗建议</h3>
                    <div class="result-text" id="treatmentAdvice"></div>
                </div>

                <!-- 诊断时间（最下面） -->
                <div class="info-item" style="margin-top: 20px; padding-top: 20px; border-top: 1px solid #e5e7eb;">
                    <div class="info-label">诊断时间</div>
                    <div class="info-value" id="diagnosisTime">--</div>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 格式化性别
        function formatGender(gender) {
            if (gender === '1' || gender === 1) return '男';
            if (gender === '2' || gender === 2) return '女';
            return '未知';
        }

        // 格式化时间
        function formatTime(time) {
            if (!time) return '未知';
            try {
                // 处理 LocalDateTime 格式（如：2025-12-24T11:28:25）
                let dateStr = time;
                if (typeof time === 'string') {
                    // 如果是字符串格式，直接使用（兼容 "2025-12-26 11:27:59" -> "2025-12-26T11:27:59"）
                    dateStr = time.replace(' ', 'T');
                } else if (time instanceof Date) {
                    // 如果已经是Date对象，直接使用
                    return time.toLocaleString('zh-CN', {
                        year: 'numeric',
                        month: '2-digit',
                        day: '2-digit',
                        hour: '2-digit',
                        minute: '2-digit',
                        second: '2-digit'
                    });
                }

                const date = new Date(dateStr);
                // 检查日期是否有效
                if (isNaN(date.getTime())) {
                    return '未知';
                }

                return date.toLocaleString('zh-CN', {
                    year: 'numeric',
                    month: '2-digit',
                    day: '2-digit',
                    hour: '2-digit',
                    minute: '2-digit',
                    second: '2-digit'
                });
            } catch (e) {
                console.error('格式化时间失败:', e, time);
                return '未知';
            }
        }

        // 显示加载状态
        function showLoading() {
            document.getElementById('loading').style.display = 'block';
            document.getElementById('error').style.display = 'none';
            document.getElementById('patientInfo').style.display = 'none';
            document.getElementById('middleSection').style.display = 'none';
            document.getElementById('diagnosisCard').style.display = 'none';
        }

        // 显示错误信息
        function showError(message) {
            document.getElementById('loading').style.display = 'none';
            document.getElementById('error').style.display = 'block';
            document.getElementById('error').textContent = message;
        }

        // 显示诊断结果
        function showResults(data) {
            console.log('showResults 被调用，数据:', data);

            try {
                document.getElementById('loading').style.display = 'none';
                document.getElementById('error').style.display = 'none';

                // 显示患者信息
                displayPatientInfo(data);
                displayTongueImage(data);
                displayDiagnosisResults(data);

                console.log('所有数据显示完成');
            } catch (error) {
                console.error('显示结果时出错:', error);
                showError('显示数据时出错: ' + error.message);
            }
        }

        // 显示患者信息
        function displayPatientInfo(data) {
            console.log('displayPatientInfo 被调用，数据:', data);
            const patientInfo = data.patientInfo; // API返回的是 patientInfo，不是 patientCoreInfo
            console.log('patientInfo:', patientInfo);

            if (patientInfo) {
                document.getElementById('patientId').textContent = patientInfo.patientId || '--';
                document.getElementById('patientComplaint').textContent = patientInfo.patientChiefComplaint || '--';

                // 显示诊断状态（右上角）
                const uploadStatus = data.uploadStatus;
                const statusBadge = document.getElementById('statusBadge');
                if (uploadStatus === 2) {
                    statusBadge.textContent = '诊断已完成';
                    statusBadge.className = 'status-badge status-completed';
                    statusBadge.style.display = 'block';
                } else if (uploadStatus === 1) {
                    statusBadge.textContent = '诊断进行中';
                    statusBadge.className = 'status-badge status-pending';
                    statusBadge.style.display = 'block';
                } else {
                    statusBadge.style.display = 'none';
                }

                document.getElementById('patientInfo').style.display = 'block';
                console.log('患者信息显示完成');
            } else {
                console.warn('patientInfo 不存在');
            }
        }

        // 显示舌象图片和关键特征（中部两栏布局）
        function displayTongueImage(data) {
            const tongueImageInfo = data.tongueImage; // API返回的是 tongueImage，不是 tongueImageInfo
            const diagnosisResult = data.diagnosisInfo;

            let hasImage = false;
            let hasRightContent = false;

            // 显示舌象图片（左边）
            if (tongueImageInfo && tongueImageInfo.url) {
                document.getElementById('tongueImage').src = tongueImageInfo.url;
                document.getElementById('imageCard').style.display = 'block';
                hasImage = true;
            }

            // 显示关键特征（右边）
            if (diagnosisResult && diagnosisResult.keyFeatures && diagnosisResult.keyFeatures.length > 0) {
                const featuresList = document.getElementById('featuresList');
                featuresList.innerHTML = '';
                diagnosisResult.keyFeatures.forEach(feature => {
                    const featureDiv = document.createElement('div');
                    featureDiv.className = 'feature-item';
                    featureDiv.innerHTML = `
                        <div class="feature-content">${feature.feature || feature}</div>
                        ${feature.confidence ? `<div class="feature-confidence">可信度: ${(parseFloat(feature.confidence) * 100).toFixed(1)}%</div>` : ''}
                    `;
                    featuresList.appendChild(featureDiv);
                });
                hasRightContent = true;
            }

            // 显示诊断结论（右边底部）
            if (diagnosisResult && diagnosisResult.tongueGeneralDesc) {
                document.getElementById('diagnosisResultRight').textContent = diagnosisResult.tongueGeneralDesc;
                document.getElementById('diagnosisSectionRight').style.display = 'block';
                hasRightContent = true;
            }

            // 如果右边有内容，显示关键特征卡片
            if (hasRightContent) {
                document.getElementById('featuresCard').style.display = 'block';
            }

            // 如果至少有一个内容，显示中部区域
            if (hasImage || hasRightContent) {
                document.getElementById('middleSection').style.display = 'grid';
            }
        }

        // 显示诊断结果（底部横栏）
        function displayDiagnosisResults(data) {
            const diagnosisResult = data.diagnosisInfo; // API返回的是 diagnosisInfo，不是 diagnosisResult

            // 显示诊断时间：优先使用顶层的 inferFinishTime，如果没有则使用 diagnosisInfo.inferTime
            const inferTime = data.inferFinishTime || (diagnosisResult ? diagnosisResult.inferTime : null);
            document.getElementById('diagnosisTime').textContent = formatTime(inferTime);

            let hasContent = false;

            if (diagnosisResult) {
                // 展示：症候 / 处方 / 诊断
                if (diagnosisResult.syndrome) {
                    const el = document.getElementById('syndromeText');
                    const sec = document.getElementById('syndromeSection');
                    if (el && sec) {
                        el.textContent = diagnosisResult.syndrome;
                        sec.style.display = 'block';
                        hasContent = true;
                    }
                }

                if (diagnosisResult.prescription) {
                    const el = document.getElementById('prescriptionText');
                    const sec = document.getElementById('prescriptionSection');
                    if (el && sec) {
                        el.textContent = diagnosisResult.prescription;
                        sec.style.display = 'block';
                        hasContent = true;
                    }
                }

                if (diagnosisResult.diagnosis) {
                    const el = document.getElementById('diagnosisText');
                    const sec = document.getElementById('diagnosisSection');
                    if (el && sec) {
                        el.textContent = diagnosisResult.diagnosis;
                        sec.style.display = 'block';
                        hasContent = true;
                    }
                }

                // 显示治疗建议
                if (diagnosisResult.healthAdvice) {
                    document.getElementById('treatmentAdvice').textContent = diagnosisResult.healthAdvice;
                    document.getElementById('adviceSection').style.display = 'block';
                    hasContent = true;
                }

                // 显示舌象状态评估
                if (diagnosisResult.tongueStateAssessment) {
                    document.getElementById('tongueAssessment').textContent = diagnosisResult.tongueStateAssessment;
                    document.getElementById('assessmentSection').style.display = 'block';
                    hasContent = true;
                }

                // 显示中医体质分析
                if (diagnosisResult.constitutionAnalysis) {
                    const el = document.getElementById('constitutionAnalysis');
                    const sec = document.getElementById('constitutionSection');
                    if (el && sec) {
                        el.textContent = diagnosisResult.constitutionAnalysis;
                        sec.style.display = 'block';
                        hasContent = true;
                    }
                }
            }

            // 如果有任何内容或时间，显示诊断卡片
            if (hasContent || inferTime) {
                document.getElementById('diagnosisCard').style.display = 'block';
            }
        }

        // 获取舌诊详情
        async function loadDiagnosisDetail() {
            // 从URL参数获取数据
            const urlParams = new URLSearchParams(window.location.search);
            const patientId = urlParams.get('patient_id');
            const projectId = urlParams.get('project_id');

            if (!patientId || !projectId) {
                showError('缺少必要的参数：patient_id 和 project_id');
                return;
            }

            try {
                // 构建API请求URL
                const url = `/api/v1/diagnosis/internal/detail?patientId=${encodeURIComponent(patientId)}&projectId=${encodeURIComponent(projectId)}`;

                // 发送请求
                const response = await fetch(url, {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });

                const data = await response.json();

                console.log('API Response:', data); // 调试信息
                console.log('data.code:', data.code); // 调试信息
                console.log('data.data:', data.data); // 调试信息

                // 判断成功：code为0且有data字段
                if (data.code === 0) {
                    if (data.data) {
                        console.log('显示结果数据:', data.data); // 调试信息
                        showResults(data.data);
                    } else {
                        console.log('data.data为空'); // 调试信息
                        showError('未找到舌诊数据');
                    }
                } else {
                    console.log('显示错误:', data.msg); // 调试信息
                    showError(data.msg || '查询失败');
                }

            } catch (error) {
                console.error('加载失败:', error);
                showError('网络错误，请稍后重试');
            }
        }

        // 页面加载完成后自动加载数据
        document.addEventListener('DOMContentLoaded', function() {
            loadDiagnosisDetail();
        });
    </script>
</body>
</html>
