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

{% block title %}服务端日志 - AgomTradePro{% endblock %}

{% block extra_css %}
<link rel="stylesheet" href="{% static 'css/admin-shell.css' %}">
<style>
    .server-log-toolbar {
        display: flex;
        gap: 10px;
        align-items: center;
        flex-wrap: wrap;
    }

    .server-log-checkbox {
        display: inline-flex;
        align-items: center;
        gap: 6px;
        color: var(--color-text-secondary);
        font-size: 14px;
    }

    .server-log-surface {
        padding: 18px;
    }

    .server-log-box {
        background: #10151c;
        color: #d5dee7;
        padding: 14px;
        border-radius: 14px;
        height: 70vh;
        overflow: auto;
        font-family: Consolas, Menlo, Monaco, monospace;
        font-size: 12px;
        line-height: 1.5;
        white-space: pre-wrap;
        border: 1px solid #2a3645;
    }

    .server-log-status {
        margin-top: 12px;
        color: var(--color-text-secondary);
        font-size: 13px;
    }

    @media (max-width: 900px) {
        .server-log-toolbar .btn {
            width: 100%;
            text-align: center;
        }
    }
</style>
{% endblock %}

{% block content %}
<div class="admin-shell admin-shell--wide">
    <div class="admin-shell__hero">
        <div class="admin-shell__lead">
            <h1 class="admin-shell__title">服务端实时日志</h1>
            <p class="admin-shell__subtitle">面向管理员的值守页。当前只展示本进程缓存日志，默认每 2 秒轮询一次，适合查看最近运行状态与异常。</p>
        </div>
        <div class="admin-shell__actions">
            <a href="{% url 'admin-console' %}" class="btn btn-secondary admin-shell__action-link">返回管理控制台</a>
            <a href="{% url 'admin-server-logs-export' %}" class="btn btn-primary admin-shell__action-link">导出 TXT</a>
        </div>
    </div>

    <div class="admin-shell__banner">
        <strong>入口说明：</strong>
        当前页属于管理控制台中的运维值守入口；
        配置修改请回设置中心；
        底层模型检查仍使用 Django Admin。
    </div>

    <div class="admin-shell__surface server-log-surface">
        <div class="server-log-toolbar">
            <button id="toggle-btn" type="button" class="btn btn-secondary">暂停刷新</button>
            <button id="clear-btn" type="button" class="btn btn-secondary">清空当前视图</button>
            <label class="server-log-checkbox"><input id="autoscroll" type="checkbox" checked> 自动滚动到底部</label>
        </div>
        <div id="log-box" class="server-log-box" style="margin-top: 14px;"></div>
        <p id="status" class="server-log-status">连接中...</p>
    </div>
</div>

<script>
(() => {
    const box = document.getElementById('log-box');
    const status = document.getElementById('status');
    const toggleBtn = document.getElementById('toggle-btn');
    const clearBtn = document.getElementById('clear-btn');
    const autoScroll = document.getElementById('autoscroll');
    let running = true;
    let since = 0;

    function appendLines(entries) {
        if (!entries || entries.length === 0) return;
        const lines = entries.map(e => `${e.ts} [${e.level}] ${e.logger} | ${e.message}`);
        box.textContent += (box.textContent ? '\n' : '') + lines.join('\n');
        if (autoScroll.checked) {
            box.scrollTop = box.scrollHeight;
        }
    }

    async function poll() {
        if (!running) return;
        try {
            const resp = await fetch(`/admin/server-logs/stream/?since=${since}&limit=400`, {
                headers: { 'X-Requested-With': 'XMLHttpRequest' }
            });
            if (!resp.ok) {
                throw new Error(`HTTP ${resp.status}`);
            }
            const data = await resp.json();
            appendLines(data.entries);
            since = data.last_id || since;
            status.textContent = `已连接，游标: ${since}，最近更新: ${new Date().toLocaleTimeString()}`;
        } catch (err) {
            status.textContent = `连接异常: ${err.message}`;
        }
    }

    toggleBtn.addEventListener('click', () => {
        running = !running;
        toggleBtn.textContent = running ? '暂停刷新' : '继续刷新';
        status.textContent = running ? '已恢复刷新' : '已暂停刷新';
    });

    clearBtn.addEventListener('click', () => {
        box.textContent = '';
    });

    poll();
    setInterval(poll, 2000);
})();
</script>
{% endblock %}
