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

{% block title %}紫睛灵 - 自演进控制中心{% endblock %}

{% block content %}
<div class="container-fluid py-4">

    <div class="d-flex justify-content-between align-items-center mb-4 fade-in-up">
        <div>
            <h3 class="fw-bold mb-0" style="color: #6f42c1;">
                <i class="bi bi-cpu me-2"></i>自演进控制中心
            </h3>
            <span class="text-muted">驱动底层轻量化架构的本地适应性演进</span>
        </div>
    </div>

    <div class="card border-0 shadow-lg rounded-4 overflow-hidden mb-4 fade-in-up">
        <div class="card-body p-4 p-md-5">
            <div class="d-flex justify-content-between align-items-end mb-3">
                <div>
                    <h4 class="fw-bold mb-1">经验池重构进度</h4>
                    <span class="text-muted small">当收集满 {{ threshold }} 张样本时，将触发底层轻量化模型 GPU 级防遗忘微调。</span>
                </div>
                <div class="text-end">

                    <h4 class="fw-bold mb-0 {% if is_evolving %}text-warning{% else %}text-primary{% endif %}">
                        {% if is_evolving %}
                            <i class="fas fa-spinner fa-spin"></i> 模型微调中...
                        {% else %}
                            <span>{{ current_samples }}</span> <span class="fs-5 text-muted">/ {{ threshold }}</span>
                        {% endif %}
                    </h4>
                </div>
            </div>
            <div class="progress" style="height: 25px; border-radius: 20px;">

                <div class="progress-bar progress-bar-striped progress-bar-animated {% if is_evolving %}bg-warning{% elif progress_percent >= 100 %}bg-success{% else %}bg-primary{% endif %}"
                    role="progressbar" style="width: {{ progress_percent }}%;">
                    {% if not is_evolving %}{{ progress_percent }}%{% endif %}
                </div>
            </div>
        </div>
    </div>

    <div class="card border-0 shadow-sm rounded-4 fade-in-up">
        <div class="card-header bg-white border-bottom-0 pt-4 pb-0 ps-4">
            <h5 class="fw-bold"><i class="bi bi-list-check me-2"></i>待校准检测记录</h5>
        </div>
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-hover align-middle mb-0">
                    <thead class="bg-light">
                        <tr>
                            <th scope="col" class="ps-4">检测时间</th>
                            <th scope="col">缩略图</th>
                            <th scope="col">系统判定</th>
                            <th scope="col">人工校准</th>
                            <th scope="col" class="text-end pe-4">操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for record in records %}
                        <tr>
                            <td class="ps-4 text-muted small">{{ record.created_at|date:"Y-m-d H:i" }}</td>
                            <td>
                                <img src="/media/{{ record.result_path }}" class="rounded shadow-sm" style="width: 55px; height: 55px; object-fit: cover;">
                            </td>
                            <td>
                                <span class="badge bg-light text-dark border">{{ record.description|default:"未识别"|slice:":12" }}</span>
                            </td>
                            <td style="width: 260px;">

                                <select class="form-select form-select-sm shadow-sm" id="correct_label_{{ record.id }}">
                                    <option value="" selected>✅ 确认无误 (无需修改)</option>
                                    <option value="健康">健康</option>
                                    <option value="茄子褐纹病">茄子褐纹病</option>
                                    <option value="茄子绵疫病">茄子绵疫病</option>
                                </select>
                            </td>
                            <td class="text-end pe-4">

                                <button type="button"
                                        class="btn btn-sm btn-danger rounded-pill px-3 shadow-hover"
                                        id="btn-{{ record.id }}"
                                        onclick="submitFeedback_V2(this, '{{ record.id }}', '{{ record.pk }}')">
                                    <i class="bi bi-cloud-arrow-up me-1"></i>
                                    提交演进
                                </button>
                            </td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

{% csrf_token %}

<script>
    // 名字改了，防止浏览器调用缓存里的旧函数
    function submitFeedback_V2(btn, rid, rpk) {
        // 1. 自动选择有效的 ID (哪个有值用哪个)
        const finalId = rid || rpk || btn.getAttribute('data-record-id');
        const sourceType = 'PAD_SYSTEM';

        console.log("【最终调试】检测到 ID:", finalId);

        if (!finalId || finalId === "" || finalId === "None") {
            alert('致命错误：页面上没抓到 ID！请检查按钮文字里有没有数字。');
            return;
        }

        const selectElem = document.getElementById('correct_label_' + finalId);
        const correctLabel = selectElem ? selectElem.value : "";
        const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value;

        const formData = new FormData();
        formData.append('record_id', finalId);
        formData.append('source_type', sourceType); // 👈 如果日志里还显示空，说明 JS 还是旧的
        formData.append('is_correct', correctLabel === "" ? 'true' : 'false');
        formData.append('correct_label', correctLabel);

        btn.disabled = true;
        btn.innerHTML = '正在进化...';

        fetch('/feedback/submit/', {
            method: 'POST',
            headers: { 'X-CSRFToken': csrftoken },
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if(data.status === 'success') {
                alert('演进样本提交成功！');
                location.href = '/evolution_dashboard/'; // 强行刷新页面
            } else {
                alert('服务器拒绝: ' + data.message);
                btn.disabled = false;
                btn.innerHTML = '重试';
            }
        })
        .catch(err => alert('网络故障，请检查 Django 控制台'));
    }
    document.addEventListener("DOMContentLoaded", function() {
        // 只有在当前处于训练状态时，才开启高频轮询
        const isCurrentlyEvolving = {{ is_evolving|yesno:"true,false" }};

        if (isCurrentlyEvolving) {
            console.log("检测到模型正在微调，启动后台状态监听...");
            const checkInterval = setInterval(() => {
                fetch("/api/evolution/status/")
                    .then(response => response.json())
                    .then(data => {
                        // 如果后端发现训练结束了 (锁被释放了)
                        if (data.is_evolving === false) {
                            console.log("微调完成，正在刷新重置页面...");
                            clearInterval(checkInterval);
                            // 强制刷新页面，此时进度条会自动变回 0/5000
                            window.location.reload();
                        }
                    })
                    .catch(err => console.error("查询微调状态失败:", err));
            }, 3000); // 每 3 秒拉取一次状态
        }
    });
</script>
{% endblock %}