{% 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-bug 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-success-subtle text-success 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-success 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-primary-subtle text-primary 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-primary 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-danger-subtle text-danger 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-danger 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;

    // 获取 CSRF Token 的辅助函数，确保 POST 请求不被 Django 拦截
    function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    const csrftoken = getCookie('csrftoken');

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

        if (!file) {
            alert('请选择一张图片');
            return;
        }

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

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

        // 尝试获取地理位置，无论成功与否都执行实际的上传
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(
                (position) => {
                    // 获取成功，追加经纬度
                    formData.append('longitude', position.coords.longitude);
                    formData.append('latitude', position.coords.latitude);
                    doFetch(formData, btn, originalText);
                },
                () => {
                    // 用户拒绝或获取失败，直接上传图片
                    console.log("无法获取位置，将仅上传图片");
                    doFetch(formData, btn, originalText);
                },
                { timeout: 3000 } // 设置 3 秒超时，防止卡死
            );
        } else {
            // 浏览器不支持地理位置
            doFetch(formData, btn, originalText);
        }
    }

    // 真正执行网络请求的核心函数
    function doFetch(formData, btn, originalText) {
        fetch('/PAD_predict/upload_pest/', {
            method: 'POST',
            headers: {
                'X-CSRFToken': csrftoken // 带上令牌，防止 403 错误
            },
            body: formData,
        })
        .then(response => response.json())
        .then(data => {
            // 恢复按钮状态
            btn.innerHTML = originalText;
            btn.disabled = false;

            if (data.resultImage) {
                // 1. 渲染检测后的图片
                const resultImage = document.getElementById('resultImage');
                resultImage.src = `data:image/jpeg;base64,${data.resultImage}`;
                resultImage.style.display = 'block';

                // 2. 渲染动态操作按钮 (纠错和百科)
                const resultContainer = resultImage.parentElement;

                // 清理可能存在的旧按钮
                const oldActions = document.getElementById('detect-actions');
                if (oldActions) oldActions.remove();

                // 【核心修复】：确保从 data 里拿到 record_id 和 label，防患于未然
                const recordId = data.record_id || '';
                const detectLabel = data.label || '未知病害';

                // 只有当后端成功返回了 record_id，我们才渲染纠错按钮，避免 400 错误
                let feedbackBtnHtml = '';
                if (recordId) {
                    feedbackBtnHtml = `
                        <button onclick="openFeedback('${recordId}', 'PAD')" class="btn btn-sm btn-outline-warning rounded-pill flex-grow-1">
                            <i class="bi bi-exclamation-triangle"></i> 结果纠错
                        </button>
                    `;
                }

                const actionsHtml = `
                    <div id="detect-actions" class="mt-3 d-flex justify-content-between gap-2">
                        <a href="/encyclopedia/disease/?search=${detectLabel}" target="_blank" class="btn btn-sm btn-outline-primary rounded-pill flex-grow-1">
                            <i class="bi bi-book"></i> 防治百科
                        </a>
                        ${feedbackBtnHtml}
                    </div>
                `;
                resultContainer.insertAdjacentHTML('beforeend', actionsHtml);
            } else {
                alert('系统未返回有效图像数据，请重试');
            }
        })
        .catch(error => {
            console.error('图片上传接口崩溃:', error);
            btn.innerHTML = originalText;
            btn.disabled = false;
            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('/PAD_predict/upload_video_pest/', {
            method: 'POST',
            headers: { 'X-CSRFToken': csrftoken },
            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);
            btn.innerHTML = originalText;
            btn.disabled = false;
            alert('上传失败');
        });
    }

    // ========== 摄像头部分保持不变 ==========
    function startCameraDetection() {
        cameraEventSource = new EventSource('/PAD_predict/camera_detect_pest/');
        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('SSE 流断开:', 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 %}