{% extends "service_monitor/base.html" %}
{% block title %}定时任务{% endblock %}

{% block extra_css %}
<style>
    /* 表格 */
    .table { background: #fff; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,.06); border: 1px solid var(--gray-200); overflow: hidden; }
    .table-head, .table-row { display: grid; grid-template-columns: 2fr 1.2fr 1fr 1fr 1fr 1.2fr 1.5fr; gap: 12px; padding: 12px 18px; align-items: center; }
    .table-head { background: var(--gray-50); font-size: 13px; color: var(--gray-500); font-weight: 600; border-bottom: 1px solid var(--gray-200); }
    .table-row { border-bottom: 1px solid var(--gray-100); font-size: 14px; }
    .table-row:last-child { border-bottom: none; }
    .name { font-weight: 600; color: var(--gray-900); }
    .cron { font-family: monospace; font-size: 13px; color: var(--gray-700); }
    .status-badge { font-size: 12px; padding: 3px 10px; border-radius: 6px; font-weight: 600; }
    .badge-enabled { background: #dcfce7; color: #15803d; }
    .badge-disabled { background: var(--gray-100); color: var(--gray-500); }
    .actions { display: flex; gap: 8px; }
    .btn-sm { padding: 5px 12px; border-radius: 6px; font-size: 12px; font-weight: 600; cursor: pointer; border: none; text-decoration: none; display: inline-block; }
    .btn-toggle { background: #fef3c7; color: #92400e; }
    .btn-edit { background: var(--gray-100); color: var(--gray-700); }
    .btn-del { background: #fee2e2; color: var(--red); }

    /* 弹窗 */
    .modal-mask { display: none; position: fixed; inset: 0; background: rgba(0,0,0,.4); z-index: 200; align-items: center; justify-content: center; padding: 20px; }
    .modal-mask.show { display: flex; }
    .modal { background: #fff; border-radius: 14px; padding: 28px; width: 100%; max-width: 480px; max-height: 90vh; overflow-y: auto; }
    .modal h3 { font-size: 18px; color: var(--gray-900); margin-bottom: 18px; }
    .form-group { margin-bottom: 14px; }
    .form-group label { display: block; font-size: 13px; color: var(--gray-700); margin-bottom: 5px; font-weight: 600; }
    .form-group input, .form-group select { width: 100%; padding: 9px 12px; border: 1px solid var(--gray-200); border-radius: 8px; font-size: 14px; }
    .form-group input:focus, .form-group select:focus { outline: none; border-color: var(--primary); }
    .form-hint { font-size: 12px; color: var(--gray-500); margin-top: 4px; }
    .cron-presets { display: flex; gap: 8px; flex-wrap: wrap; margin-top: 8px; }
    .cron-preset { background: var(--gray-100); border: 1px solid var(--gray-200); padding: 5px 12px; border-radius: 6px; font-size: 12px; cursor: pointer; color: var(--gray-700); }
    .cron-preset:hover { background: var(--gray-200); }
    .modal-actions { display: flex; gap: 10px; justify-content: flex-end; margin-top: 20px; }
    .btn-cancel { background: var(--gray-100); color: var(--gray-700); border: none; padding: 9px 18px; border-radius: 8px; cursor: pointer; font-size: 14px; font-weight: 600; }
    .btn-save { background: var(--primary); color: #fff; border: none; padding: 9px 18px; border-radius: 8px; cursor: pointer; font-size: 14px; font-weight: 600; }
    .btn-save:disabled { opacity: .6; cursor: not-allowed; }

    @media screen and (max-width: 1024px) {
        .table-head, .table-row { grid-template-columns: 1fr 1fr 1fr 1fr; }
        .table-head span:nth-child(5), .table-head span:nth-child(6), .table-row span:nth-child(5), .table-row span:nth-child(6) { display: none; }
    }
    @media screen and (max-width: 768px) {
        .table-head { display: none; }
        .table-row { grid-template-columns: 1fr 1fr; gap: 6px; padding: 14px; }
    }
</style>
{% endblock %}

{% block content %}
<div class="section-head">
    <div class="section-title">⏰ 定时任务</div>
    {% if is_admin %}
    <button class="btn-add" onclick="openCreate()">+ 新增定时任务</button>
    {% endif %}
</div>

{% if schedules %}
<div class="table">
    <div class="table-head">
        <span>任务名称</span>
        <span>目标</span>
        <span>套件</span>
        <span>Cron</span>
        <span>状态</span>
        <span>下次执行</span>
        <span>操作</span>
    </div>
    {% for s in schedules %}
    <div class="table-row">
        <span class="name">{{ s.name }}</span>
        <span>{{ s.target_name or s.target_id }}</span>
        <span>{{ '快速' if s.suite == 'quick' else '全量' }}</span>
        <span class="cron">{{ s.cron }}</span>
        <span><span class="status-badge {{ 'badge-enabled' if s.enabled else 'badge-disabled' }}">{{ '启用' if s.enabled else '禁用' }}</span></span>
        <span>{{ s.next_run_at or '-' }}</span>
        <div class="actions">
            {% if is_admin %}
            <button class="btn-sm btn-toggle" onclick="toggleSchedule('{{ s.id }}')">{{ '禁用' if s.enabled else '启用' }}</button>
            <button class="btn-sm btn-edit" onclick="openEdit('{{ s.id }}')">编辑</button>
            <button class="btn-sm btn-del" onclick="deleteSchedule('{{ s.id }}')">删除</button>
            {% else %}
            <span class="btn-sm" style="opacity:.5; cursor:default;">查看</span>
            {% endif %}
        </div>
    </div>
    {% endfor %}
</div>
{% else %}
<div class="empty">📭 暂无定时任务，点击"新增定时任务"创建</div>
{% endif %}

<!-- 新增/编辑弹窗 -->
<div class="modal-mask" id="modal">
    <div class="modal">
        <h3 id="modal-title">新增定时任务</h3>
        <div class="form-group">
            <label>任务名称</label>
            <input type="text" id="f-name" placeholder="如：每日全量巡检">
        </div>
        <div class="form-group">
            <label>监测目标</label>
            <select id="f-target">
                {% for t in targets %}
                <option value="{{ t.id }}">{{ t.name }}</option>
                {% endfor %}
            </select>
        </div>
        <div class="form-group">
            <label>巡检套件</label>
            <select id="f-suite">
                <option value="quick">快速巡检</option>
                <option value="full">全量巡检</option>
            </select>
        </div>
        <div class="form-group">
            <label>Cron 表达式</label>
            <input type="text" id="f-cron" placeholder="0 8 * * *">
            <div class="form-hint">格式：分 时 日 月 周（如 0 8 * * * 表示每天 8:00）</div>
            <div class="cron-presets">
                <span class="cron-preset" onclick="setCron('0 8 * * *')">每天 08:00</span>
                <span class="cron-preset" onclick="setCron('0 */6 * * *')">每 6 小时</span>
                <span class="cron-preset" onclick="setCron('0 8 * * 1')">每周一 08:00</span>
                <span class="cron-preset" onclick="setCron('0 12,18 * * *')">每天 12:00、18:00</span>
            </div>
        </div>
        <div class="modal-actions">
            <button class="btn-cancel" onclick="closeModal()">取消</button>
            <button class="btn-save" id="btn-save" onclick="saveSchedule()">保存</button>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
const TARGETS = {{ targets | tojson | safe }};
let editingId = null;

function openCreate() {
    editingId = null;
    document.getElementById('modal-title').textContent = '新增定时任务';
    document.getElementById('f-name').value = '';
    document.getElementById('f-target').selectedIndex = 0;
    document.getElementById('f-suite').value = 'quick';
    document.getElementById('f-cron').value = '0 8 * * *';
    document.getElementById('modal').classList.add('show');
}

function openEdit(id) {
    editingId = id;
    document.getElementById('modal-title').textContent = '编辑定时任务';
    // TODO: 填充现有数据
    const row = event.target.closest('.table-row');
    const name = row.querySelector('.name').textContent;
    document.getElementById('f-name').value = name;
    document.getElementById('modal').classList.add('show');
}

function closeModal() {
    document.getElementById('modal').classList.remove('show');
}

function setCron(expr) {
    document.getElementById('f-cron').value = expr;
}

async function saveSchedule() {
    const data = {
        name: document.getElementById('f-name').value.trim(),
        target_id: document.getElementById('f-target').value,
        suite: document.getElementById('f-suite').value,
        cron: document.getElementById('f-cron').value.trim(),
    };

    if (!data.name) {
        alert('请输入任务名称');
        return;
    }
    if (!data.cron) {
        alert('请输入 Cron 表达式');
        return;
    }

    const url = editingId
        ? '/api/service-monitor/schedules/' + editingId
        : '/api/service-monitor/schedules';
    const method = editingId ? 'PUT' : 'POST';

    try {
        const r = await fetch(url, {
            method: method,
            headers: {'Content-Type': 'application/json'},
            credentials: 'include',
            body: JSON.stringify(data),
        });
        const d = await r.json();
        if (d.success) {
            closeModal();
            location.reload();
        } else {
            alert(d.error?.message || '保存失败');
        }
    } catch (e) {
        alert('请求失败');
    }
}

async function toggleSchedule(id) {
    try {
        const r = await fetch('/api/service-monitor/schedules/' + id + '/toggle', {
            method: 'POST',
            credentials: 'include',
        });
        const d = await r.json();
        if (d.success) {
            location.reload();
        } else {
            alert('操作失败');
        }
    } catch (e) {
        alert('请求失败');
    }
}

async function deleteSchedule(id) {
    if (!confirm('确定删除该定时任务？')) return;
    try {
        const r = await fetch('/api/service-monitor/schedules/' + id, {
            method: 'DELETE',
            credentials: 'include',
        });
        const d = await r.json();
        if (d.success) {
            location.reload();
        } else {
            alert('删除失败');
        }
    } catch (e) {
        alert('请求失败');
    }
}
</script>
{% endblock %}