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

{% block extra_css %}
<style>
    .container { max-width: 960px; }

    /* 访客模式提示条 */
    .guest-banner {
        display: flex;
        align-items: center;
        justify-content: space-between;
        background: #fef3c7;
        border: 1px solid #f59e0b;
        border-radius: 8px;
        padding: 10px 16px;
        margin-bottom: 16px;
        font-size: 14px;
        color: #92400e;
        flex-wrap: wrap;
        gap: 10px;
    }
    .guest-banner span { display: flex; align-items: center; gap: 6px; }
    .btn-login-link {
        background: #2563eb;
        color: #fff;
        padding: 6px 14px;
        border-radius: 6px;
        text-decoration: none;
        font-size: 13px;
        font-weight: 600;
        white-space: nowrap;
    }
    .btn-login-link:hover { background: #1d4ed8; }

    /* 报告头 */
    .report-head { display: flex; align-items: center; justify-content: space-between; margin-bottom: 18px; flex-wrap: wrap; gap: 12px; }
    .report-meta h2 { font-size: 20px; color: var(--gray-900); margin-bottom: 4px; }
    .report-meta .sub { font-size: 13px; color: var(--gray-500); }
    .export-wrap { position: relative; }
    .btn-export { background: var(--primary); color: #fff; border: none; padding: 9px 18px; border-radius: 8px; font-size: 14px; font-weight: 600; cursor: pointer; }
    .export-menu { display: none; position: absolute; right: 0; top: 44px; background: #fff; border: 1px solid var(--gray-200); border-radius: 8px; box-shadow: 0 4px 16px rgba(0,0,0,.12); overflow: hidden; z-index: 10; }
    .export-menu.show { display: block; }
    .export-menu a { display: block; padding: 10px 20px; font-size: 14px; color: var(--gray-700); text-decoration: none; }
    .export-menu a:hover { background: var(--gray-50); }

    /* 汇总卡片 */
    .summary-cards { display: grid; grid-template-columns: repeat(4,1fr); gap: 12px; margin-bottom: 24px; }
    .sum-card { background: #fff; border-radius: 12px; padding: 18px; text-align: center; border: 1px solid var(--gray-200); }
    .sum-card .num { font-size: 28px; font-weight: 700; }
    .sum-card .label { font-size: 13px; color: var(--gray-500); margin-top: 4px; }
    .sum-total .num { color: var(--gray-900); }
    .sum-ok .num { color: var(--green); }
    .sum-warn .num { color: var(--yellow); }
    .sum-crit .num { color: var(--red); }

    /* 异常项 */
    .section-title { font-size: 16px; font-weight: 700; color: var(--gray-900); margin: 24px 0 12px; display: flex; align-items: center; gap: 8px; }
    .abnormal-box { background: #fff; border-radius: 12px; border: 1px solid var(--gray-200); overflow: hidden; }
    .abnormal-row { display: grid; grid-template-columns: 24px 2fr 1fr 1fr 1fr auto; gap: 12px; align-items: center; padding: 12px 18px; border-bottom: 1px solid var(--gray-100); font-size: 14px; }
    .abnormal-row:last-child { border-bottom: none; }
    .ab-icon { text-align: center; }
    .ab-crit { color: var(--red); } .ab-warn { color: var(--yellow); }
    .ab-name { font-weight: 600; color: var(--gray-900); }
    .ab-module { font-size: 12px; color: var(--gray-500); }
    .ab-value { font-weight: 600; }
    .ab-threshold { font-size: 13px; color: var(--gray-500); }
    .btn-fix { background: #fef3c7; color: #92400e; border: none; padding: 5px 12px; border-radius: 6px; font-size: 12px; font-weight: 600; cursor: pointer; }

    /* 分模块折叠 */
    .module-block { background: #fff; border-radius: 12px; border: 1px solid var(--gray-200); margin-bottom: 12px; overflow: hidden; }
    .module-header { display: flex; align-items: center; gap: 10px; padding: 14px 18px; cursor: pointer; user-select: none; }
    .module-header:hover { background: var(--gray-50); }
    .module-toggle { font-size: 12px; color: var(--gray-500); transition: transform .2s; flex-shrink: 0; }
    .module-block.open .module-toggle { transform: rotate(90deg); }
    .module-title { font-weight: 700; color: var(--gray-900); flex: 1; }
    .module-mini { display: flex; gap: 8px; font-size: 13px; }
    .module-body { max-height: 0; overflow: hidden; transition: max-height .35s ease; }
    .module-block.open .module-body { max-height: 5000px; }

    /* 检测项行 */
    .item-row { display: grid; grid-template-columns: 2fr 1.5fr 1fr 1fr; gap: 12px; padding: 10px 18px; border-top: 1px solid var(--gray-100); font-size: 14px; }
    .item-name { color: var(--gray-700); }
    .item-value { color: var(--gray-900); font-weight: 600; word-break: break-all; }
    .item-threshold { color: var(--gray-500); font-size: 13px; }
    .item-status { font-weight: 600; }
    .stt-正常 { color: var(--green); } .stt-警告 { color: var(--yellow); } .stt-严重 { color: var(--red); }

    /* 进程列表特殊样式 */
    .process-row { border-top: 1px solid var(--gray-100); padding: 10px 18px; }
    .process-summary { font-weight: 600; color: var(--gray-900); margin-bottom: 8px; display: flex; align-items: center; gap: 8px; }
    .process-toggle-btn { background: var(--gray-100); border: 1px solid var(--gray-200); padding: 3px 10px; border-radius: 6px; font-size: 12px; cursor: pointer; color: var(--gray-700); }
    .process-toggle-btn:hover { background: var(--gray-200); }
    .process-table-wrap { display: none; margin-top: 8px; overflow-x: auto; }
    .process-table-wrap.show { display: block; }
    .process-table { width: 100%; border-collapse: collapse; font-size: 13px; }
    .process-table th { background: var(--gray-50); padding: 8px 10px; text-align: left; font-weight: 600; color: var(--gray-700); border-bottom: 2px solid var(--gray-200); }
    .process-table td { padding: 6px 10px; border-bottom: 1px solid var(--gray-100); color: var(--gray-900); }
    .process-table tr:hover td { background: var(--gray-50); }
    .process-table .cmd-cell { font-family: monospace; font-size: 12px; max-width: 300px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }

    /* 长值展开 */
    .long-value { cursor: pointer; color: var(--primary); }
    .long-value .truncated { display: inline; }
    .long-value .full { display: none; }
    .long-value.expanded .truncated { display: none; }
    .long-value.expanded .full { display: inline; white-space: pre-wrap; word-break: break-all; }

    @media screen and (max-width: 768px) {
        .container { padding: 0; }
        .report-head { flex-direction: column; align-items: flex-start; gap: 10px; }
        .report-meta h2 { font-size: 16px; }
        .export-wrap { width: 100%; }
        .btn-export { width: 100%; }
        .export-menu { position: fixed; left: 12px; right: 12px; top: auto; bottom: 12px; border-radius: 12px; }
        .summary-cards { grid-template-columns: repeat(2, 1fr); gap: 8px; }
        .sum-card { padding: 12px; }
        .sum-card .num { font-size: 22px; }
        .abnormal-row { grid-template-columns: 20px 1fr auto; gap: 6px; padding: 10px 12px; font-size: 13px; }
        .abnormal-row .ab-threshold, .abnormal-row .ab-module, .abnormal-row .btn-fix { display: none; }
        .ab-name { font-size: 13px; }
        .module-header { padding: 12px 14px; }
        .module-title { font-size: 14px; word-break: break-word; }
        .module-mini { font-size: 12px; }
        .item-row { grid-template-columns: 1fr auto; gap: 4px; padding: 8px 14px; font-size: 13px; }
        .item-threshold { display: none; }
        .item-status { white-space: nowrap; }
        .process-table { font-size: 11px; }
        .process-table th, .process-table td { padding: 4px 6px; }
        .process-table .cmd-cell { max-width: 120px; }
        .guest-banner { flex-direction: column; text-align: center; gap: 8px; padding: 12px; }
    }
    @media screen and (max-width: 480px) {
        .report-meta h2 { font-size: 14px; }
        .report-meta .sub { font-size: 12px; }
        .summary-cards { gap: 6px; }
        .sum-card { padding: 10px; }
        .sum-card .num { font-size: 18px; }
        .sum-card .label { font-size: 11px; }
        .abnormal-row { padding: 8px 10px; font-size: 12px; gap: 4px; }
        .module-header { padding: 10px 12px; }
        .module-title { font-size: 13px; }
        .item-row { padding: 7px 12px; font-size: 12px; }
        .item-value { word-break: break-word; font-size: 12px; }
        .process-table { font-size: 10px; }
        .process-table .cmd-cell { max-width: 90px; }
        .guest-banner { padding: 10px; font-size: 13px; }
        .btn-login-link { padding: 5px 10px; font-size: 12px; }
    }
</style>
{% endblock %}

{% block content %}
<div class="container">
    {% if token_auth %}
    <div class="guest-banner">
        <span>👤 访客模式 — 仅可查看本报告</span>
        <a href="/login?next={{ request.url | urlencode }}" class="btn-login-link">🔑 登录查看更多功能</a>
    </div>
    {% endif %}

    <div class="report-head">
        <div class="report-meta">
            <h2>{{ '🖥️' if report.target_type == 'local' else '🌐' }} {{ report.target_name }}</h2>
            <div class="sub">
                {{ '⚡ 快速巡检' if report.suite == 'quick' else '🔍 全量巡检' }} ·
                {{ (report.started_at or '').replace('T', ' ') }} ~ {{ (report.finished_at or '')[11:19] }}
            </div>
        </div>
        <div class="export-wrap">
            {% if not token_auth %}
            <button class="btn-compare" onclick="openCompareModal()" style="background: #10b981; color: #fff; border: none; padding: 9px 18px; border-radius: 8px; font-size: 14px; font-weight: 600; cursor: pointer; margin-right: 8px;">📊 对比历史报告</button>
            {% endif %}
            <button class="btn-export" onclick="toggleExport()">⬇ 导出 ▾</button>
            <div class="export-menu" id="export-menu">
                <a href="/api/service-monitor/reports/{{ report.id }}/export?format=md{% if token_auth %}&token={{ access_token }}{% endif %}">导出 Markdown</a>
                <a href="/api/service-monitor/reports/{{ report.id }}/export?format=json{% if token_auth %}&token={{ access_token }}{% endif %}">导出 JSON</a>
                <a href="/api/service-monitor/reports/{{ report.id }}/export?format=excel{% if token_auth %}&token={{ access_token }}{% endif %}">导出 Excel</a>
                <a href="/api/service-monitor/reports/{{ report.id }}/export?format=pdf{% if token_auth %}&token={{ access_token }}{% endif %}">导出 PDF</a>
            </div>
        </div>
    </div>

    <!-- 汇总卡片 -->
    {% set s = report.summary or {} %}
    <div class="summary-cards">
        <div class="sum-card sum-total"><div class="num">{{ s.total or 0 }}</div><div class="label">总检测项</div></div>
        <div class="sum-card sum-ok"><div class="num">{{ s['正常'] or 0 }}</div><div class="label">正常</div></div>
        <div class="sum-card sum-warn"><div class="num">{{ s['警告'] or 0 }}</div><div class="label">警告</div></div>
        <div class="sum-card sum-crit"><div class="num">{{ s['严重'] or 0 }}</div><div class="label">严重</div></div>
    </div>

    <!-- 异常项置顶 -->
    {% set ns = namespace(abnormal=[]) %}
    {% for m in report.modules %}
        {% for it in m['items'] %}
            {% if it.status in ['警告', '严重'] %}
                {% set _ = ns.abnormal.append((m.name, it)) %}
            {% endif %}
        {% endfor %}
    {% endfor %}

    {% if ns.abnormal %}
    <div class="section-title">⚠️ 异常项（{{ ns.abnormal | length }}）</div>
    <div class="abnormal-box">
        {% for mod_name, it in ns.abnormal %}
        <div class="abnormal-row">
            <span class="ab-icon {{ 'ab-crit' if it.status == '严重' else 'ab-warn' }}">{{ '✗' if it.status == '严重' else '⚠' }}</span>
            <span><span class="ab-name">{{ it.name }}</span><br><span class="ab-module">{{ mod_name }}</span></span>
            <span class="ab-value {{ 'ab-crit' if it.status == '严重' else 'ab-warn' }}">{{ it.value }}</span>
            <span class="ab-threshold">{{ it.threshold or '-' }}</span>
            <span class="item-status stt-{{ it.status }}">{{ it.status }}</span>
            {% if is_admin and not token_auth %}
            <button class="btn-fix" onclick="tryFix('{{ it.key }}')">修复</button>
            {% else %}
            <span></span>
            {% endif %}
        </div>
        {% endfor %}
    </div>
    {% else %}
    <div class="section-title">✅ 全部正常</div>
    {% endif %}

    <!-- 分模块折叠明细 -->
    <div class="section-title">📋 检测明细（点击展开）</div>
    {% for m in report.modules %}
    {% set ms = m.summary or {} %}
    {% set has_abnormal = (ms.get('警告', 0) or ms.get('严重', 0)) %}
    <div class="module-block{{ ' open' if has_abnormal else '' }}" data-module="{{ m.id }}">
        <div class="module-header" onclick="toggleModule(this)">
            <span class="module-toggle">▶</span>
            <span class="module-title">{{ m.name }}</span>
            <span class="module-mini">
                {% if ms.get('正常') %}<span class="stt-正常">✓{{ ms['正常'] }}</span>{% endif %}
                {% if ms.get('警告') %}<span class="stt-警告">⚠{{ ms['警告'] }}</span>{% endif %}
                {% if ms.get('严重') %}<span class="stt-严重">✗{{ ms['严重'] }}</span>{% endif %}
            </span>
        </div>
        <div class="module-body">
            {% for it in m['items'] %}
                {# 判断是否为进程列表项 #}
                {% if it.key.endswith('_PROCESS_LIST') or it.key.endswith('_PROCESSES_DETAIL') %}
            <div class="process-row">
                <div class="process-summary">
                    <span>{{ it.name }}</span>
                    <button class="process-toggle-btn" onclick="toggleProcessTable(this)">展开详情</button>
                </div>
                <div class="process-table-wrap">
                    <table class="process-table">
                        <thead><tr><th>用户</th><th>PID</th><th>CPU%</th><th>内存%</th><th>命令</th></tr></thead>
                        <tbody>
                            {% for line in it.value.split('|') %}
                            {% set parts = line.strip().split() %}
                            {% if parts|length >= 5 %}
                            <tr>
                                <td>{{ parts[0] }}</td>
                                <td>{{ parts[1] }}</td>
                                <td>{{ parts[2] }}</td>
                                <td>{{ parts[3] }}</td>
                                <td class="cmd-cell" title="{{ ' '.join(parts[4:]) }}">{{ ' '.join(parts[4:]) }}</td>
                            </tr>
                            {% endif %}
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
            </div>
                {% else %}
            <div class="item-row">
                <span class="item-name">{{ it.name }}</span>
                {% if it.value|length > 80 %}
                <span class="item-value long-value" onclick="this.classList.toggle('expanded')">
                    <span class="truncated">{{ it.value[:80] }}…</span>
                    <span class="full">{{ it.value }}</span>
                </span>
                {% else %}
                <span class="item-value">{{ it.value }}</span>
                {% endif %}
                <span class="item-threshold">{{ it.threshold or '-' }}</span>
                <span class="item-status stt-{{ it.status }}">{{ it.status }}</span>
            </div>
                {% endif %}
            {% endfor %}
        </div>
    </div>
    {% endfor %}
</div>

<!-- 对比报告选择弹窗 -->
{% if not token_auth %}
<div id="compare-modal" class="modal" style="display:none;">
    <div class="modal-overlay" onclick="closeCompareModal()"></div>
    <div class="modal-content">
        <div class="modal-header">
            <h3>选择对比报告</h3>
            <button class="modal-close" onclick="closeCompareModal()">×</button>
        </div>
        <div class="modal-body">
            <div id="compare-loading" style="text-align:center;padding:20px;color:var(--gray-500);">加载中...</div>
            <div id="compare-list" style="display:none;"></div>
        </div>
    </div>
</div>
<style>
.modal { position: fixed; top: 0; left: 0; right: 0; bottom: 0; z-index: 1000; }
.modal-overlay { position: absolute; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.5); }
.modal-content { position: relative; max-width: 500px; margin: 80px auto; background: #fff; border-radius: 12px; box-shadow: 0 8px 32px rgba(0,0,0,0.2); max-height: 70vh; display: flex; flex-direction: column; }
.modal-header { display: flex; align-items: center; justify-content: space-between; padding: 16px 20px; border-bottom: 1px solid var(--gray-200); }
.modal-header h3 { margin: 0; font-size: 18px; color: var(--gray-900); }
.modal-close { background: none; border: none; font-size: 24px; color: var(--gray-500); cursor: pointer; padding: 0; line-height: 1; }
.modal-close:hover { color: var(--gray-900); }
.modal-body { padding: 16px 20px; overflow-y: auto; }
.compare-item { display: flex; align-items: center; padding: 12px 16px; border: 1px solid var(--gray-200); border-radius: 8px; margin-bottom: 8px; cursor: pointer; transition: all .15s; }
.compare-item:hover { border-color: var(--primary); background: var(--gray-50); }
.compare-item.selected { border-color: var(--primary); background: #eff6ff; }
.compare-item input { margin-right: 12px; }
.compare-item .info { flex: 1; }
.compare-item .info .date { font-size: 14px; font-weight: 600; color: var(--gray-900); }
.compare-item .info .summary { font-size: 12px; color: var(--gray-500); margin-top: 2px; }
.modal-footer { padding: 12px 20px; border-top: 1px solid var(--gray-200); display: flex; justify-content: flex-end; gap: 8px; }
@media screen and (max-width: 768px) {
    .modal-content { margin: 20px; max-height: 80vh; }
    .btn-compare { display: none; }
}
</style>
{% endif %}
{% endblock %}

{% block extra_js %}
<script>
    function toggleExport() { document.getElementById('export-menu').classList.toggle('show'); }
    document.addEventListener('click', (e) => {
        if (!e.target.closest('.export-wrap')) document.getElementById('export-menu').classList.remove('show');
    });

    function toggleModule(header) {
        const block = header.parentElement;
        block.classList.toggle('open');
    }

    function toggleProcessTable(btn) {
        const wrap = btn.closest('.process-row').querySelector('.process-table-wrap');
        wrap.classList.toggle('show');
        btn.textContent = wrap.classList.contains('show') ? '收起详情' : '展开详情';
    }

    async function tryFix(key) {
        const r = await fetch('/api/service-monitor/fix', {method:'POST', headers:{'Content-Type':'application/json'}, credentials:'include', body: JSON.stringify({key})});
        const d = await r.json();
        alert(d.message || '修复能力开发中');
    }

    // 对比报告功能
    let compareReports = [];
    let selectedCompareId = null;

    async function openCompareModal() {
        document.getElementById('compare-modal').style.display = 'block';
        document.getElementById('compare-loading').style.display = 'block';
        document.getElementById('compare-list').style.display = 'none';
        selectedCompareId = null;

        try {
            const targetId = '{{ report.target_id }}';
            const r = await fetch(`/api/service-monitor/reports?target_id=${targetId}&limit=20`, {credentials:'include'});
            const d = await r.json();
            if (d.success) {
                compareReports = d.reports.filter(rp => rp.id !== '{{ report.id }}');
                renderCompareList();
            }
        } catch (e) {
            document.getElementById('compare-loading').textContent = '加载失败';
        }
    }

    function renderCompareList() {
        const list = document.getElementById('compare-list');
        const loading = document.getElementById('compare-loading');

        if (compareReports.length === 0) {
            list.innerHTML = '<div style="text-align:center;padding:20px;color:var(--gray-500);">暂无其他历史报告</div>';
        } else {
            list.innerHTML = compareReports.map(rp => {
                const s = rp.summary || {};
                const date = (rp.finished_at || rp.started_at || '').replace('T', ' ');
                const summary = `正常 ${s['正常']||0} / 警告 ${s['警告']||0} / 严重 ${s['严重']||0}`;
                return `<div class="compare-item" onclick="selectCompare('${rp.id}', this)">
                    <input type="radio" name="compare-select" value="${rp.id}" ${selectedCompareId===rp.id?'checked':''}>
                    <div class="info">
                        <div class="date">${date}</div>
                        <div class="summary">${summary}</div>
                    </div>
                </div>`;
            }).join('') + `<div class="modal-footer"><button class="btn-action btn-primary" onclick="doCompare()" ${!selectedCompareId?'disabled style="opacity:0.5"':''}>开始对比</button></div>`;
        }

        loading.style.display = 'none';
        list.style.display = 'block';
    }

    function selectCompare(id, el) {
        selectedCompareId = id;
        document.querySelectorAll('.compare-item').forEach(item => item.classList.remove('selected'));
        el.classList.add('selected');
        el.querySelector('input').checked = true;
        const btn = document.querySelector('.modal-footer .btn-primary');
        if (btn) { btn.disabled = false; btn.style.opacity = '1'; }
    }

    function doCompare() {
        if (!selectedCompareId) return;
        window.location.href = `/service-monitor/compare/{{ report.id }}/${selectedCompareId}`;
    }

    function closeCompareModal() {
        document.getElementById('compare-modal').style.display = 'none';
    }
</script>
{% endblock %}