{% extends "service_monitor/base.html" %}
{% block title %}巡检报告{% endblock %}

{% block extra_css %}
<style>
    /* 筛选栏 */
    .filter-bar {
        display: flex;
        align-items: center;
        gap: 12px;
        margin-bottom: 16px;
    }
    .filter-bar select {
        padding: 8px 12px;
        border: 1px solid var(--gray-200);
        border-radius: 8px;
        font-size: 14px;
        color: var(--gray-700);
        background: #fff;
    }
    .filter-bar select:focus {
        outline: none;
        border-color: var(--primary);
    }
    .report-count {
        font-size: 13px;
        color: var(--gray-500);
        margin-left: auto;
    }

    /* 报告列表 */
    .report-list {
        background: #fff;
        border-radius: 12px;
        box-shadow: 0 2px 8px rgba(0,0,0,.06);
        border: 1px solid var(--gray-200);
        overflow: hidden;
    }
    .report-row {
        display: grid;
        grid-template-columns: 40px 2fr 1fr 2fr 2fr 1fr;
        gap: 12px;
        align-items: center;
        padding: 14px 18px;
        border-bottom: 1px solid var(--gray-100);
        text-decoration: none;
    }
    .report-row:last-child { border-bottom: none; }
    .report-row:hover { background: var(--gray-50); }
    .report-row.is-link { cursor: pointer; }
    .report-checkbox {
        display: flex;
        align-items: center;
        justify-content: center;
    }
    .report-checkbox input {
        width: 16px;
        height: 16px;
        cursor: pointer;
        accent-color: var(--primary);
    }
    .report-target { font-weight: 600; color: var(--gray-900); }
    .report-suite { font-size: 13px; color: var(--gray-500); }
    .report-summary { display: flex; gap: 10px; font-size: 13px; }
    .sm-ok { color: var(--green); } .sm-warn { color: var(--yellow); } .sm-crit { color: var(--red); }
    .report-time { font-size: 13px; color: var(--gray-500); }
    .btn-view {
        background: var(--gray-100);
        color: var(--gray-700);
        padding: 6px 14px;
        border-radius: 6px;
        font-size: 13px;
        font-weight: 600;
        text-decoration: none;
        text-align: center;
    }
    .btn-view:hover { background: var(--gray-200); }

    /* 批量操作栏 */
    .batch-bar {
        display: none;
        align-items: center;
        gap: 16px;
        padding: 12px 18px;
        background: #fff;
        border-radius: 12px;
        box-shadow: 0 2px 8px rgba(0,0,0,.06);
        border: 1px solid var(--gray-200);
        margin-bottom: 12px;
    }
    .batch-bar.show { display: flex; }
    .batch-count { font-size: 14px; color: var(--gray-700); font-weight: 600; }
    .btn-batch-del {
        background: #fee2e2;
        color: var(--red);
        border: none;
        padding: 8px 16px;
        border-radius: 8px;
        font-size: 13px;
        font-weight: 600;
        cursor: pointer;
        margin-left: auto;
    }
    .btn-batch-del:hover { background: #fecaca; }

    @media screen and (max-width: 768px) {
        .filter-bar { flex-direction: column; align-items: stretch; gap: 8px; }
        .filter-bar select { width: 100%; padding: 8px 10px; font-size: 13px; }
        .report-count { margin-left: 0; text-align: right; font-size: 12px; }
        .report-row {
            grid-template-columns: 28px 1fr auto;
            gap: 8px; padding: 12px 14px;
            border-bottom: 2px solid var(--gray-200);
        }
        .report-summary, .report-time, .btn-view { display: none; }
        .report-target { font-size: 14px; }
        .report-suite { font-size: 12px; }
        .batch-bar { flex-wrap: wrap; gap: 10px; padding: 10px 14px; }
        .btn-batch-del { margin-left: 0; }
        .section-head { margin-bottom: 12px; }
    }
    @media screen and (max-width: 480px) {
        .filter-bar select { padding: 7px 8px; font-size: 12px; }
        .report-row { padding: 10px 12px; gap: 6px; }
        .report-checkbox input { width: 14px; height: 14px; }
        .report-target { font-size: 13px; }
        .report-suite { font-size: 11px; }
        .batch-bar { padding: 10px 12px; gap: 8px; }
        .batch-count { font-size: 13px; }
        .btn-batch-del { padding: 6px 12px; font-size: 12px; }
        .section-title { font-size: 15px; }
    }
</style>
{% endblock %}

{% block content %}
<div class="section-head">
    <div class="section-title">📋 巡检报告</div>
</div>

<div class="filter-bar">
    <select id="filter-target" onchange="filterByTarget()">
        <option value="">全部目标</option>
        {% for t in targets %}
        <option value="{{ t.id }}" {{ 'selected' if request.args.get('target_id') == t.id }}>{{ t.name }}</option>
        {% endfor %}
    </select>
    <span class="report-count">共 {{ reports | length }} 条报告</span>
</div>

{% if is_admin and reports %}
<!-- 批量操作栏 -->
<div class="batch-bar" id="batch-bar">
    <input type="checkbox" id="select-all" onchange="toggleSelectAll(this)" style="width:16px;height:16px;accent-color:var(--primary);">
    <span class="batch-count" id="batch-count">已选 0 条</span>
    <button class="btn-batch-del" onclick="batchDelete()">🗑 批量删除</button>
</div>
{% endif %}

{% if reports %}
<div class="report-list">
    {% for r in reports %}
    <div class="report-row">
        {% if is_admin %}
        <div class="report-checkbox">
            <input type="checkbox" class="report-check" value="{{ r.id }}" onchange="updateBatchCount()">
        </div>
        {% endif %}
        <a href="/service-monitor/report/{{ r.id }}" class="report-target is-link" style="text-decoration:none;color:inherit;">{{ r.target_name }}</a>
        <span class="report-suite">{{ '快速' if r.suite == 'quick' else '全量' }}</span>
        <span class="report-summary">
            <span class="sm-ok">✓{{ r.summary.正常 if r.summary else 0 }}</span>
            <span class="sm-warn">⚠{{ r.summary.警告 if r.summary else 0 }}</span>
            <span class="sm-crit">✗{{ r.summary.严重 if r.summary else 0 }}</span>
        </span>
        <span class="report-time">{{ (r.started_at or '')[5:16].replace('T', ' ') }}</span>
        <a href="/service-monitor/report/{{ r.id }}" class="btn-view">查看</a>
    </div>
    {% endfor %}
</div>
{% else %}
<div class="empty">📭 暂无巡检报告，点击目标卡片开始巡检</div>
{% endif %}
{% endblock %}

{% block extra_js %}
<script>
    function filterByTarget() {
        const targetId = document.getElementById('filter-target').value;
        const url = targetId
            ? '/service-monitor/reports?target_id=' + encodeURIComponent(targetId)
            : '/service-monitor/reports';
        window.location.href = url;
    }

    function toggleSelectAll(el) {
        document.querySelectorAll('.report-check').forEach(cb => cb.checked = el.checked);
        updateBatchCount();
    }

    function updateBatchCount() {
        const checks = document.querySelectorAll('.report-check:checked');
        const count = checks.length;
        document.getElementById('batch-count').textContent = `已选 ${count} 条`;
        // 全选框状态同步
        const all = document.querySelectorAll('.report-check');
        document.getElementById('select-all').checked = all.length > 0 && count === all.length;
    }

    // 任意 checkbox 变化时显示批量操作栏
    document.addEventListener('change', function(e) {
        if (e.target.classList.contains('report-check')) {
            const bar = document.getElementById('batch-bar');
            const hasChecked = document.querySelectorAll('.report-check:checked').length > 0;
            bar.classList.toggle('show', true);  // 管理员始终显示批量栏
        }
    });

    // 初始化：管理员且有报告时显示批量栏
    (function() {
        const bar = document.getElementById('batch-bar');
        if (bar && {{ 'true' if is_admin and reports else 'false' }}) {
            bar.classList.add('show');
        }
    })();

    async function batchDelete() {
        const ids = Array.from(document.querySelectorAll('.report-check:checked')).map(cb => cb.value);
        if (ids.length === 0) {
            alert('请先选择要删除的报告');
            return;
        }
        if (!confirm(`确定删除选中的 ${ids.length} 份报告？此操作不可恢复。`)) return;

        try {
            const r = await fetch('/api/service-monitor/reports/batch', {
                method: 'DELETE',
                headers: { 'Content-Type': 'application/json' },
                credentials: 'include',
                body: JSON.stringify({ ids: ids }),
            });
            const d = await r.json();
            if (d.success) {
                alert(`成功删除 ${d.deleted} 份报告`);
                location.reload();
            } else {
                alert(d.error?.message || '删除失败');
            }
        } catch (e) {
            alert('请求失败');
        }
    }
</script>
{% endblock %}
