{% extends 'base.html' %}
{% load static %}

{% block title %}品相智能检测 - 茄子在线检测系统{% endblock %}

{% block content %}
<div class="row justify-content-center">
    <div class="col-lg-12">
        <div class="text-center mb-5 fade-in-up">
            <h2 class="fw-bold" style="color: #6f42c1;">
                <i class="bi bi-stars me-2"></i>茄子品相智能检测
            </h2>
            <p class="text-muted">基于计算机视觉的形状与色泽分级系统</p>
        </div>

        <div class="row g-4 mb-5">

            <div class="col-lg-4 col-md-12 fade-in-up" style="animation-delay: 0.1s;">
                <div class="card h-100 shadow-hover border-0 function-card">
                    <div class="card-body text-center p-4">
                        <div class="icon-circle bg-primary-subtle text-primary mb-3">
                            <i class="bi bi-image"></i>
                        </div>
                        <h4 class="fw-bold mb-3">图片检测</h4>
                        <p class="text-muted small mb-3">上传单张茄子图片进行品相评分</p>

                        <div class="mb-3">
                            <input type="file" id="imageInput" accept="image/*" class="form-control mb-3">
                            <button onclick="uploadImage()" class="btn btn-primary w-100 rounded-pill">
                                <i class="bi bi-upload me-2"></i>上传并检测
                            </button>
                        </div>

                        <div class="result-container mt-3">
                            <img id="resultImage" src="" alt="检测结果" class="img-fluid rounded shadow-sm" style="display: none; width: 100%; object-fit: contain;">
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-lg-4 col-md-12 fade-in-up" style="animation-delay: 0.2s;">
                <div class="card h-100 shadow-hover border-0 function-card">
                    <div class="card-body text-center p-4">
                        <div class="icon-circle bg-info-subtle text-info mb-3">
                            <i class="bi bi-camera-video"></i>
                        </div>
                        <h4 class="fw-bold mb-3">视频检测</h4>
                        <p class="text-muted small mb-3">上传视频流进行连续品相分析</p>

                        <div class="mb-3">
                            <input type="file" id="videoInput" accept="video/*" class="form-control mb-3">
                            <button onclick="uploadVideo()" class="btn btn-info text-white w-100 rounded-pill">
                                <i class="bi bi-play-circle me-2"></i>上传并分析
                            </button>
                        </div>

                        <div class="result-container mt-3">
                            <video id="resultVideo" controls class="img-fluid rounded shadow-sm" style="display: none; width: 100%;">
                                您的浏览器不支持视频播放。
                            </video>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-lg-4 col-md-12 fade-in-up" style="animation-delay: 0.3s;">
                <div class="card h-100 shadow-hover border-0 function-card">
                    <div class="card-body text-center p-4">
                        <div class="icon-circle bg-success-subtle text-success mb-3">
                            <i class="bi bi-webcam"></i>
                        </div>
                        <h4 class="fw-bold mb-3">实时监控</h4>
                        <p class="text-muted small mb-3">调用本地摄像头进行实时分级</p>

                        <div class="mb-3 mt-4">
                            <button id="startCameraDetection" onclick="startCameraDetection()" class="btn btn-outline-success w-100 rounded-pill mb-2">
                                <i class="bi bi-record-circle me-2"></i>开始检测
                            </button>
                            <button id="stopCameraDetection" onclick="stopCameraDetection()" style="display: none;" class="btn btn-danger w-100 rounded-pill beat-animation">
                                <i class="bi bi-stop-circle me-2"></i>停止检测
                            </button>
                        </div>

                        <div class="result-container mt-3">
                            <img id="cameraResultImage" src="" alt="检测结果" class="img-fluid rounded shadow-sm" style="display: none; width: 100%;">
                        </div>
                    </div>
                </div>
            </div>

        </div>
    </div>
</div>

<style>
    /* 动画效果 */
    .fade-in-up {
        animation: fadeInUp 0.6s ease-out forwards;
        opacity: 0;
        transform: translateY(20px);
    }
    @keyframes fadeInUp {
        to { opacity: 1; transform: translateY(0); }
    }

    /* 卡片悬浮特效 */
    .shadow-hover {
        transition: transform 0.3s ease, box-shadow 0.3s ease;
    }
    .shadow-hover:hover {
        transform: translateY(-5px);
        box-shadow: 0 10px 20px rgba(0,0,0,0.1) !important;
    }

    /* 图标圆圈 */
    .icon-circle {
        width: 60px;
        height: 60px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 1.8rem;
        margin: 0 auto;
    }

    /* 停止按钮心跳动画 */
    .beat-animation {
        animation: beat 1.5s infinite;
    }
    @keyframes beat {
        0% { transform: scale(1); }
        50% { transform: scale(1.05); }
        100% { transform: scale(1); }
    }

    /* 结果容器最小高度，防止抖动 */
    .result-container {
        min-height: 20px;
    }
</style>

<script>
    let cameraEventSource = null;

    function uploadImage() {
        const fileInput = document.getElementById('imageInput');
        const file = fileInput.files[0];

        // 获取地理位置
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition((position) => {
                const formData = new FormData();
                formData.append('image', file);
                formData.append('longitude', position.coords.longitude);
                formData.append('latitude', position.coords.latitude);

                // 执行 fetch 请求 (逻辑不变，只需多传两个参数)
                executeUpload(formData);
            }, () => {
                // 如果获取失败，发送空位置
                const formData = new FormData();
                formData.append('image', file);
                executeUpload(formData);
            });
        }

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

            const btn = event.target.closest('button');
            const originalText = btn.innerHTML;
            btn.innerHTML = '<span class="spinner-border spinner-border-sm"></span> 检测中...';
            btn.disabled = true;

            fetch('/predict/upload/', {
                method: 'POST',
                body: formData,
            })
            .then(response => response.json())
            .then(data => {
                btn.innerHTML = originalText;
                btn.disabled = false;

                if (data.resultImage) {
                    const resultImage = document.getElementById('resultImage');
                    resultImage.src = `data:image/jpeg;base64,${data.resultImage}`;
                    resultImage.style.display = 'block';

                    // --- 新增：通用联动按钮组 ---
                    const resultContainer = document.querySelector('.result-container');
                    const oldActions = document.getElementById('detect-actions');
                    if (oldActions) oldActions.remove();

                    const actionsHtml = `
                        <div id="detect-actions" class="mt-3 d-flex justify-content-between gap-2">
                            <a href="/encyclopedia/shape/?search=${data.label || ''}" target="_blank" class="btn btn-sm btn-outline-primary rounded-pill flex-grow-1">
                                <i class="bi bi-book"></i> 品相百科
                            </a>
                            <button onclick="openFeedback('${data.record_id}', 'SHAPE')" class="btn btn-sm btn-outline-warning rounded-pill flex-grow-1">
                                <i class="bi bi-exclamation-triangle"></i> 结果纠错
                            </button>
                        </div>
                    `;
                    resultContainer.insertAdjacentHTML('beforeend', actionsHtml);
                } else {
                    alert('检测失败');
                }
            })
            .catch(error => {
                console.error('Error uploading image:', error);
                btn.innerHTML = originalText;
                btn.disabled = false;
                alert('上传失败');
            });
        } else {
            alert('请选择一张图片');
        }
    }

    function uploadVideo() {
        const fileInput = document.getElementById('videoInput');
        const file = fileInput.files[0];
        if (!file) {
            alert('请选择一个视频文件');
            return;
        }

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

        // 简单的加载提示
        const btn = event.target.closest('button');
        const originalText = btn.innerHTML;
        btn.innerHTML = '<span class="spinner-border spinner-border-sm"></span> 上传中...';
        btn.disabled = true;

        fetch('/predict/upload_video/', {
            method: 'POST',
            body: formData,
        })
        .then(response => response.blob())
        .then(blob => {
            btn.innerHTML = originalText;
            btn.disabled = false;

            const url = URL.createObjectURL(blob);
            const resultVideo = document.getElementById('resultVideo');
            resultVideo.src = url;
            resultVideo.style.display = 'block';
            resultVideo.play();
        })
        .catch(error => {
            console.error('Error uploading video:', error);
            btn.innerHTML = originalText;
            btn.disabled = false;
            alert('上传失败');
        });
    }

    function startCameraDetection() {
        cameraEventSource = new EventSource('/predict/camera_detect/');
        cameraEventSource.onmessage = function (event) {
            const data = JSON.parse(event.data);
            if (data.frame) {
                const cameraResultImage = document.getElementById('cameraResultImage');
                cameraResultImage.src = `data:image/jpeg;base64,${data.frame}`;
                cameraResultImage.style.display = 'block';
            }
        };
        cameraEventSource.onerror = function (error) {
            console.error('EventSource failed:', error);
            cameraEventSource.close();
        };

        document.getElementById('startCameraDetection').style.display = 'none';
        document.getElementById('stopCameraDetection').style.display = 'inline-block';
    }

    function stopCameraDetection() {
        if (cameraEventSource) {
            cameraEventSource.close();
            cameraEventSource = null;
        }
        document.getElementById('cameraResultImage').style.display = 'none';
        document.getElementById('startCameraDetection').style.display = 'inline-block';
        document.getElementById('stopCameraDetection').style.display = 'none';
    }
</script>
{% endblock %}