<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>香菇表型分析系统 V1.0</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: "Times New Roman", Times, serif, "SimSun", "STSong";
            background: #f5f5f5;
            min-height: 100vh;
            padding: 20px;
            color: #333;
        }

        .container {
            max-width: 1400px;
            margin: 0 auto;
            background: white;
            box-shadow: 0 0 20px rgba(0,0,0,0.1);
            border-radius: 2px;
        }

        header {
            text-align: center;
            background: #2c3e50;
            color: white;
            padding: 30px 20px;
            border-bottom: 3px solid #34495e;
        }

        header h1 {
            font-size: 2em;
            margin-bottom: 8px;
            font-weight: 600;
            letter-spacing: 1px;
        }

        header p {
            font-size: 0.95em;
            opacity: 0.9;
            font-family: Arial, sans-serif;
        }

        .main-content {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 0;
        }

        .panel {
            background: white;
            padding: 30px;
            border-right: 1px solid #e0e0e0;
        }

        .panel:last-child {
            border-right: none;
        }

        .panel h2 {
            font-size: 1.3em;
            margin-bottom: 20px;
            color: #2c3e50;
            border-bottom: 2px solid #34495e;
            padding-bottom: 10px;
            font-weight: 600;
        }

        /* 上传区域 */
        .upload-area {
            border: 2px dashed #7f8c8d;
            border-radius: 4px;
            padding: 40px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s;
            background: #fafafa;
        }

        .upload-area:hover {
            border-color: #34495e;
            background: #f0f0f0;
        }

        .upload-area.dragover {
            border-color: #27ae60;
            background: #e8f5e9;
        }

        .upload-icon {
            font-size: 2.5em;
            margin-bottom: 15px;
            color: #7f8c8d;
        }

        .upload-text {
            font-size: 1em;
            color: #555;
            margin-bottom: 8px;
            font-family: Arial, sans-serif;
        }

        .upload-hint {
            font-size: 0.85em;
            color: #888;
            font-family: Arial, sans-serif;
        }

        #fileInput {
            display: none;
        }

        .btn {
            background: #34495e;
            color: white;
            border: none;
            padding: 10px 28px;
            border-radius: 3px;
            font-size: 0.95em;
            cursor: pointer;
            transition: background 0.3s;
            margin-top: 15px;
            font-family: Arial, sans-serif;
            display: block;
            margin-left: auto;
            margin-right: auto;
        }

        .btn:hover {
            background: #2c3e50;
        }

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

        /* 预览区域 */
        .preview-container {
            margin-top: 20px;
            display: none;
        }

        .preview-image {
            width: 100%;
            border-radius: 3px;
            margin-top: 10px;
            border: 1px solid #ddd;
        }

        /* 示例图像 */
        .examples-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
            gap: 10px;
            margin-top: 15px;
        }

        .example-item {
            cursor: pointer;
            border-radius: 3px;
            overflow: hidden;
            transition: all 0.2s;
            border: 2px solid #ddd;
        }

        .example-item:hover {
            border-color: #34495e;
            box-shadow: 0 2px 8px rgba(0,0,0,0.15);
        }

        .example-item img {
            width: 100%;
            height: 80px;
            object-fit: cover;
            display: block;
        }

        /* 结果区域 */
        .results-container {
            display: none;
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 15px;
            margin-bottom: 20px;
        }

        .stat-card {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 3px;
            border-left: 3px solid #34495e;
        }

        .stat-label {
            font-size: 0.85em;
            color: #666;
            margin-bottom: 5px;
            font-family: Arial, sans-serif;
        }

        .stat-value {
            font-size: 1.3em;
            font-weight: 600;
            color: #2c3e50;
            font-family: Arial, sans-serif;
        }

        .mushroom-card {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 3px;
            margin-bottom: 15px;
            border: 1px solid #e0e0e0;
        }

        .mushroom-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 1px solid #ddd;
        }

        .mushroom-id {
            font-size: 1.1em;
            font-weight: 600;
            color: #2c3e50;
            font-family: Arial, sans-serif;
        }

        /* 重点信息区域 */
        .key-results {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 15px;
            margin-bottom: 20px;
            padding: 15px;
            background: white;
            border-radius: 4px;
            border: 2px solid #3498db;
        }

        .key-result-item {
            text-align: center;
        }

        .key-result-label {
            font-size: 0.9em;
            color: #666;
            margin-bottom: 8px;
            font-family: Arial, sans-serif;
            font-weight: 500;
        }

        .key-result-value {
            font-size: 1.8em;
            font-weight: 700;
            color: #2c3e50;
            font-family: Arial, sans-serif;
            line-height: 1.2;
        }

        .key-result-value.diameter {
            color: #e74c3c;
        }

        .key-result-value.pattern {
            color: #27ae60;
        }

        .key-result-unit {
            font-size: 0.6em;
            color: #666;
            font-weight: 400;
        }

        /* 详细信息区域 */
        .mushroom-stats {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 10px;
        }

        .mushroom-stat {
            font-size: 0.9em;
            color: #555;
            font-family: Arial, sans-serif;
            padding: 8px;
            background: white;
            border-radius: 3px;
        }

        .mushroom-stat strong {
            color: #2c3e50;
        }

        .result-image-container {
            margin-top: 20px;
            text-align: center;
        }

        .result-image-container h3 {
            font-size: 1em;
            margin-bottom: 15px;
            color: #2c3e50;
            font-weight: 600;
            font-family: Arial, sans-serif;
        }

        .result-image-container img {
            width: 100%;
            border-radius: 3px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            border: 1px solid #ddd;
        }

        /* 加载动画 */
        .loading {
            display: none;
            text-align: center;
            padding: 40px;
        }

        .spinner {
            border: 3px solid #e0e0e0;
            border-top: 3px solid #34495e;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
            margin: 0 auto 15px;
        }

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

        .loading-text {
            color: #555;
            font-size: 0.95em;
            font-family: Arial, sans-serif;
        }

        /* 错误提示 */
        .error-message {
            background: #fff3cd;
            color: #856404;
            padding: 12px;
            border-radius: 3px;
            margin-top: 15px;
            display: none;
            border: 1px solid #ffeaa7;
            font-size: 0.9em;
            font-family: Arial, sans-serif;
        }

        /* 响应式设计 */
        @media (max-width: 968px) {
            .main-content {
                grid-template-columns: 1fr;
            }

            .panel {
                border-right: none;
                border-bottom: 1px solid #e0e0e0;
            }

            .panel:last-child {
                border-bottom: none;
            }

            .stats-grid {
                grid-template-columns: 1fr;
            }
        }

        /* 图例 */
        .legend {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 3px;
            margin-top: 15px;
            border: 1px solid #e0e0e0;
        }

        .legend-title {
            font-weight: 600;
            margin-bottom: 10px;
            color: #2c3e50;
            font-size: 0.95em;
            font-family: Arial, sans-serif;
        }

        .legend-items {
            display: flex;
            flex-wrap: wrap;
            gap: 12px;
        }

        .legend-item {
            display: flex;
            align-items: center;
            gap: 6px;
            font-size: 0.85em;
            font-family: Arial, sans-serif;
            color: #555;
        }

        .legend-color {
            width: 18px;
            height: 18px;
            border-radius: 2px;
            border: 1px solid rgba(0,0,0,0.1);
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <h1>香菇表型分析系统 V1.0</h1>
            <p>Shiitake Mushroom Phenotypic Analysis System V1.0</p>
        </header>

        <div class="main-content">
            <!-- 左侧：上传面板 -->
            <div class="panel">
                <h2>图像上传</h2>
                <div class="upload-area" id="uploadArea">
                    <div class="upload-icon">📁</div>
                    <div class="upload-text">点击或拖拽图像到此处</div>
                    <div class="upload-hint">支持 JPG、PNG、BMP 格式，最大 16MB</div>
                    <input type="file" id="fileInput" accept="image/*">
                </div>
                <button class="btn" id="uploadBtn" style="display:none;">开始分析</button>

                <div class="preview-container" id="previewContainer">
                    <h3 style="margin-bottom: 10px; color: #2c3e50; font-size: 0.95em;">图像预览</h3>
                    <img id="previewImage" class="preview-image" alt="预览">
                </div>

                <div class="error-message" id="errorMessage"></div>

                <!-- 示例图像 -->
                <div style="margin-top: 30px;">
                    <h3 style="margin-bottom: 15px; color: #2c3e50; font-size: 1em; font-weight: 600;">示例图像</h3>
                    <div class="examples-grid" id="examplesGrid">
                        <div style="grid-column: 1/-1; text-align: center; color: #888; font-size: 0.9em;">
                            加载中...
                        </div>
                    </div>
                </div>
            </div>

            <!-- 右侧：结果面板 -->
            <div class="panel">
                <h2>分析结果</h2>

                <div class="loading" id="loading">
                    <div class="spinner"></div>
                    <div class="loading-text">正在分析图像，请稍候...</div>
                </div>

                <div class="results-container" id="resultsContainer">
                    <div class="stats-grid">
                        <div class="stat-card">
                            <div class="stat-label">AprilTag 标定</div>
                            <div class="stat-value" id="apriltag">-</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-label">像素/毫米比例</div>
                            <div class="stat-value" id="pxPerMm">-</div>
                        </div>
                    </div>

                    <h3 style="margin: 20px 0 15px; color: #2c3e50; font-size: 1em; font-weight: 600;">检测结果</h3>
                    <div id="mushroomsContainer"></div>

                    <div class="result-image-container">
                        <h3>可视化结果</h3>
                        <img id="visImage" alt="分析结果">
                    </div>
                </div>

                <div style="text-align: center; color: #888; padding: 40px; font-family: Arial, sans-serif;" id="placeholder">
                    请上传图像或选择示例图像开始分析
                </div>
            </div>
        </div>
    </div>

    <script>
        let selectedFile = null;
        let lastAction = null;

        // 上传区域交互
        const uploadArea = document.getElementById('uploadArea');
        const fileInput = document.getElementById('fileInput');
        const uploadBtn = document.getElementById('uploadBtn');
        const previewContainer = document.getElementById('previewContainer');
        const previewImage = document.getElementById('previewImage');
        const errorMessage = document.getElementById('errorMessage');

        uploadArea.addEventListener('click', () => fileInput.click());

        uploadArea.addEventListener('dragover', (e) => {
            e.preventDefault();
            uploadArea.classList.add('dragover');
        });

        uploadArea.addEventListener('dragleave', () => {
            uploadArea.classList.remove('dragover');
        });

        uploadArea.addEventListener('drop', (e) => {
            e.preventDefault();
            uploadArea.classList.remove('dragover');
            const files = e.dataTransfer.files;
            if (files.length > 0) {
                handleFileSelect(files[0]);
            }
        });

        fileInput.addEventListener('change', (e) => {
            if (e.target.files.length > 0) {
                handleFileSelect(e.target.files[0]);
            }
        });

        function handleFileSelect(file) {
            selectedFile = file;
            lastAction = 'upload';
            const reader = new FileReader();
            reader.onload = (e) => {
                previewImage.src = e.target.result;
                previewContainer.style.display = 'block';
                uploadBtn.style.display = 'block';
                errorMessage.style.display = 'none';
            };
            reader.readAsDataURL(file);
        }

        uploadBtn.addEventListener('click', () => {
            if (selectedFile) {
                analyzeImage(selectedFile);
            }
        });

        // 分析图像
        async function analyzeImage(file) {
            const formData = new FormData();
            formData.append('file', file);

            showLoading();

            try {
                const response = await fetch('/analyze', {
                    method: 'POST',
                    body: formData
                });

                const data = await response.json();

                if (data.success) {
                    displayResults(data);
                } else {
                    showError(data.error || '分析失败');
                }
            } catch (error) {
                showError('网络错误: ' + error.message);
            } finally {
                hideLoading();
            }
        }

        // 分析示例图像
        async function analyzeExample(imagePath) {
            lastAction = 'example';
            showLoading();

            try {
                const response = await fetch('/analyze_example', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ path: imagePath })
                });

                const data = await response.json();

                if (data.success) {
                    displayResults(data);
                } else {
                    showError(data.error || '分析失败');
                }
            } catch (error) {
                showError('网络错误: ' + error.message);
            } finally {
                hideLoading();
            }
        }

        function safeToFixed(value, digits) {
            const num = Number(value);
            if (Number.isFinite(num)) {
                return num.toFixed(digits);
            }
            return '-';
        }

        // 显示结果
        function displayResults(data) {
            document.getElementById('placeholder').style.display = 'none';
            document.getElementById('resultsContainer').style.display = 'block';

            // 基本信息
            document.getElementById('apriltag').textContent = data.apriltag_detected ? '✓ 已检测' : '✗ 未检测';
            document.getElementById('pxPerMm').textContent = safeToFixed(data.px_per_mm, 4);

            // 左侧预览：上传时保留本地预览；示例图像则用原图
            if (data.orig_image && (lastAction === 'example' || !previewImage.src)) {
                previewImage.src = 'data:image/jpeg;base64,' + data.orig_image;
                previewContainer.style.display = 'block';
            }

            // 香菇列表
            const mushroomsContainer = document.getElementById('mushroomsContainer');
            mushroomsContainer.innerHTML = '';

            const mushrooms = Array.isArray(data.mushrooms) ? data.mushrooms : [];
            if (mushrooms.length === 0) {
                mushroomsContainer.innerHTML = '<div style="color: #888; padding: 10px 0;">未检测到香菇或无有效结果</div>';
            }

            mushrooms.forEach(mushroom => {
                const diameterText = safeToFixed(mushroom.diameter_mm, 1);
                const crackRatioText = safeToFixed(mushroom.crack_ratio_percent, 2);
                const capAreaText = safeToFixed(mushroom.cap_area_mm2, 2);
                const whiteRatioText = safeToFixed(mushroom.white_pattern_ratio, 2);
                const brownRatioText = safeToFixed(mushroom.brown_pattern_ratio, 2);
                const confidenceNum = Number(mushroom.confidence);
                const confidenceText = Number.isFinite(confidenceNum)
                    ? (confidenceNum * 100).toFixed(1)
                    : '-';
                const flatnessText = safeToFixed(mushroom.flatness_score, 3);
                const patternText = mushroom.pattern_type || '未知';

                const card = document.createElement('div');
                card.className = 'mushroom-card';
                card.innerHTML = `
                    <div class="mushroom-header">
                        <div class="mushroom-id">香菇 #${mushroom.id}</div>
                    </div>

                    <!-- 重点信息：直径和花纹类型 -->
                    <div class="key-results">
                        <div class="key-result-item">
                            <div class="key-result-label">菌盖直径</div>
                            <div class="key-result-value diameter">
                                ${diameterText}
                                <span class="key-result-unit">mm</span>
                            </div>
                        </div>
                        <div class="key-result-item">
                            <div class="key-result-label">花纹类型</div>
                            <div class="key-result-value pattern">${patternText}</div>
                        </div>
                    </div>

                    <!-- 详细信息 -->
                    <div class="mushroom-stats">
                        <div class="mushroom-stat">
                            <strong>花纹比例:</strong> ${crackRatioText}%
                        </div>
                        <div class="mushroom-stat">
                            <strong>菌盖面积:</strong> ${capAreaText} mm²
                        </div>
                        <div class="mushroom-stat">
                            <strong>白色花纹:</strong> ${whiteRatioText}%
                        </div>
                        <div class="mushroom-stat">
                            <strong>茶褐色花纹:</strong> ${brownRatioText}%
                        </div>
                        <div class="mushroom-stat">
                            <strong>检测置信度:</strong> ${confidenceText}%
                        </div>
                        ${Number(mushroom.flatness_score) > 0 ? `
                        <div class="mushroom-stat">
                            <strong>平坦度:</strong> ${flatnessText}
                        </div>
                        ` : ''}
                    </div>
                `;
                mushroomsContainer.appendChild(card);
            });

            // 图像
            const visImage = document.getElementById('visImage');
            if (data.vis_image) {
                visImage.src = 'data:image/jpeg;base64,' + data.vis_image;
                visImage.style.display = 'block';
            } else {
                visImage.removeAttribute('src');
                visImage.style.display = 'none';
            }
        }

        // 加载示例图像
        async function loadExamples() {
            try {
                const response = await fetch('/examples');
                const examples = await response.json();

                const grid = document.getElementById('examplesGrid');
                grid.innerHTML = '';

                if (examples.length === 0) {
                    grid.innerHTML = '<div style="grid-column: 1/-1; text-align: center; color: #999;">暂无示例图像</div>';
                    return;
                }

                examples.forEach(example => {
                    const item = document.createElement('div');
                    item.className = 'example-item';
                    item.innerHTML = `<img src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='100' height='80'%3E%3Crect fill='%23ddd' width='100' height='80'/%3E%3Ctext x='50%25' y='50%25' text-anchor='middle' dy='.3em' fill='%23999' font-size='12'%3E${example.name.substring(0, 10)}%3C/text%3E%3C/svg%3E" alt="${example.name}">`;
                    item.title = example.name;
                    item.addEventListener('click', () => analyzeExample(example.path));
                    grid.appendChild(item);
                });
            } catch (error) {
                console.error('加载示例图像失败:', error);
            }
        }

        function showLoading() {
            document.getElementById('loading').style.display = 'block';
            document.getElementById('resultsContainer').style.display = 'none';
            document.getElementById('placeholder').style.display = 'none';
            uploadBtn.disabled = true;
        }

        function hideLoading() {
            document.getElementById('loading').style.display = 'none';
            uploadBtn.disabled = false;
        }

        function showError(message) {
            errorMessage.textContent = message;
            errorMessage.style.display = 'block';
            document.getElementById('resultsContainer').style.display = 'none';
            document.getElementById('placeholder').style.display = 'block';
            setTimeout(() => {
                errorMessage.style.display = 'none';
            }, 5000);
        }

        // 页面加载时获取示例图像
        loadExamples();
    </script>
</body>
</html>
