<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title data-i18n="cron.title">Cron Manager</title>
    <script src="/static/js/i18n.js"></script>
    <style>
        * { box-sizing: border-box; margin: 0; padding: 0; }
        html, body { height: 100%; overflow: hidden; }
        body { font-family: -apple-system, BlinkMacSystemFont, sans-serif; background: #1e1e1e; color: #ccc; }
        
        .toolbar {
            display: flex; align-items: center; gap: 12px; padding: 10px 16px;
            background: #2d2d2d; border-bottom: 1px solid #404040;
        }
        button {
            padding: 6px 14px; border-radius: 6px; border: none;
            background: #0e639c; color: #fff; font-size: 13px; cursor: pointer;
        }
        button:hover { background: #1177bb; }
        button.danger { background: #cf222e; }
        button.danger:hover { background: #da3633; }
        button.secondary { background: #3c3c3c; }
        
        .list { flex: 1; overflow: auto; padding: 12px; }
        .job {
            padding: 12px 16px; background: #2d2d2d; border-radius: 8px; margin-bottom: 8px;
            display: flex; align-items: flex-start; gap: 12px;
        }
        .job.disabled { opacity: 0.5; }
        .job-enable { cursor: pointer; font-size: 18px; }
        .job-info { flex: 1; }
        .job-schedule { 
            font-family: 'Consolas', monospace; font-size: 13px; color: #58a6ff; 
            background: #1e1e1e; padding: 4px 8px; border-radius: 4px; margin-bottom: 4px;
        }
        .job-command { font-size: 12px; color: #ccc; word-break: break-all; }
        .job-actions { display: flex; gap: 8px; }
        .job-actions button { padding: 4px 8px; font-size: 12px; }
        .job-actions .btn-run { background: #238636; }
        .job-actions .btn-run:hover { background: #2ea043; }
        
        .empty { text-align: center; padding: 40px; color: #666; }
        
        .modal {
            position: fixed; inset: 0; background: rgba(0,0,0,0.7); z-index: 1000;
            display: none; align-items: center; justify-content: center;
        }
        .modal.open { display: flex; }
        .modal-content {
            background: #2d2d2d; border-radius: 12px; padding: 20px; width: 400px; max-width: 90%;
        }
        .modal-title { font-size: 16px; margin-bottom: 16px; }
        .form-group { margin-bottom: 12px; }
        .form-group label { display: block; font-size: 12px; color: #888; margin-bottom: 4px; }
        .form-group input, .form-group select {
            width: 100%; padding: 8px 12px; border-radius: 6px; border: 1px solid #404040;
            background: #3c3c3c; color: #ccc; font-size: 14px;
        }
        .form-row { display: flex; gap: 8px; }
        .form-row .form-group { flex: 1; }
        .modal-actions { display: flex; gap: 8px; justify-content: flex-end; margin-top: 16px; }
    </style>
<link rel="stylesheet" href="/static/lib/sweetalert2.min.css">
<script src="/static/lib/sweetalert2.min.js"></script>
<link rel="stylesheet" href="/static/lib/flatpickr/flatpickr.min.css">
<link rel="stylesheet" href="/static/lib/flatpickr/dark.css">
<script src="/static/lib/flatpickr/flatpickr.min.js"></script>
<script src="/static/lib/flatpickr/zh.min.js"></script>
</head>
<body>
    <div id="app">
        <div class="toolbar">
            <span style="font-size:14px;font-weight:500;" data-i18n="cron.heading">Cron Task Manager</span>
            <button onclick="openAddModal()" data-i18n="cron.add_task">+ Add Task</button>
            <button class="secondary" onclick="loadJobs()" data-i18n="common.refresh">Refresh</button>
        </div>
        <div id="list" class="list"></div>
    </div>

    <!-- 添加/编辑弹窗 -->
    <div id="addModal" class="modal">
        <div class="modal-content">
            <div class="modal-title" data-i18n="cron.modal.title">Add Cron Task</div>
            <div class="form-row">
                <div class="form-group">
                    <label data-i18n="cron.modal.minute">Minute</label>
                    <input type="text" id="minute" value="*" placeholder="*">
                </div>
                <div class="form-group">
                    <label data-i18n="cron.modal.hour">Hour</label>
                    <input type="text" id="hour" value="*" placeholder="*">
                </div>
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label data-i18n="cron.modal.day">Day</label>
                    <input type="text" id="day" value="*" placeholder="*">
                </div>
                <div class="form-group">
                    <label data-i18n="cron.modal.month">Month</label>
                    <input type="text" id="month" value="*" placeholder="*">
                </div>
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label data-i18n="cron.modal.weekday">Weekday</label>
                    <input type="text" id="weekday" value="*" placeholder="0-7">
                </div>
                <div class="form-group">
                    <label data-i18n="cron.modal.shortcut">Shortcut</label>
                    <select id="template" onchange="applyTemplate()">
                        <option value="" data-i18n="cron.shortcut.custom">Custom</option>
                        <option value="@reboot" data-i18n="cron.shortcut.reboot">@reboot</option>
                        <option value="@hourly" data-i18n="cron.shortcut.hourly">Hourly</option>
                        <option value="0 3 * * *" data-i18n="cron.shortcut.daily_3am">Daily at 3:00</option>
                        <option value="0 0 * * 0" data-i18n="cron.shortcut.weekly_sunday">Weekly on Sunday</option>
                        <option value="0 0 1 * *" data-i18n="cron.shortcut.monthly_1st">Monthly on 1st</option>
                        <option value="*/5 * * * *" data-i18n="cron.shortcut.every_5min">Every 5 minutes</option>
                    </select>
                </div>
            </div>
            <div class="form-group">
                <label data-i18n="cron.modal.quick_schedule">Quick Schedule (Visual)</label>
                <input type="text" id="quickSchedule" data-i18n-placeholder="cron.modal.quick_schedule_placeholder" placeholder="Click to select time...">
            </div>
            <div class="form-group">
                <label data-i18n="cron.modal.command">Command</label>
                <input type="text" id="command" data-i18n-placeholder="cron.modal.command_placeholder" placeholder="e.g., /home/user/backup.sh">
            </div>
            <div class="modal-actions">
                <button class="secondary" onclick="closeAddModal()" data-i18n="common.cancel">Cancel</button>
                <button onclick="addJob()" data-i18n="common.add">Add</button>
            </div>
        </div>
    </div>

    <script>
    let jobs = [];
    
    function $(id) { return document.getElementById(id); }
    
    function showStatus(msg) { Swal.fire({ icon: 'info', title: I18n.t('common.notice'), text: msg, timer: 2000 }); }
    
    async function loadJobs() {
        try {
            const r = await fetch('/api/cron/list');
            const data = await r.json();
            if (data.success) {
                jobs = (data.data && data.data.jobs) || [];
                render();
            } else {
                Swal.fire(I18n.t('common.error'), data.error || I18n.t('common.load_failed'), 'error');
            }
        } catch (e) {
            Swal.fire(I18n.t('common.error'), e.message, 'error');
        }
    }
    
    function render() {
        const list = $('list');
        if (jobs.length === 0) {
            list.innerHTML = '<div class="empty">' + I18n.t('cron.empty.title') + '<br><br>' + I18n.t('cron.empty.hint') + '</div>';
            return;
        }
        
        list.innerHTML = jobs.map((job, i) => `
            <div class="job ${!job.enabled ? 'disabled' : ''}">
                <div class="job-enable" onclick="toggleJob(${i})">
                    ${job.enabled ? '✅' : '⏸️'}
                </div>
                <div class="job-info">
                    <div class="job-schedule">${job.minute} ${job.hour} ${job.day} ${job.month} ${job.weekday}</div>
                    <div class="job-command">${job.command}</div>
                </div>
                <div class="job-actions">
                    <button class="btn-run" onclick="runJob(${i})">▶ ${I18n.t('cron.job.run')}</button>
                    <button onclick="removeJob(${i})" class="danger">${I18n.t('common.delete')}</button>
                </div>
            </div>
        `).join('');
    }
    
    function openAddModal() {
        $('addModal').classList.add('open');
        $('minute').value = '*';
        $('hour').value = '*';
        $('day').value = '*';
        $('month').value = '*';
        $('weekday').value = '*';
        $('command').value = '';
        $('template').value = '';
    }
    
    function closeAddModal() {
        $('addModal').classList.remove('open');
    }
    
    function applyTemplate() {
        const tmpl = $('template').value;
        if (tmpl.startsWith('@')) {
            $('minute').value = tmpl;
            $('hour').value = '';
            $('day').value = '';
            $('month').value = '';
            $('weekday').value = '';
        } else {
            const parts = tmpl.split(' ');
            if (parts.length >= 5) {
                $('minute').value = parts[0];
                $('hour').value = parts[1];
                $('day').value = parts[2];
                $('month').value = parts[3];
                $('weekday').value = parts[4];
            }
        }
    }
    
    async function addJob() {
        const minute = $('minute').value || '*';
        const hour = $('hour').value || '*';
        const day = $('day').value || '*';
        const month = $('month').value || '*';
        const weekday = $('weekday').value || '*';
        const command = $('command').value.trim();
        
        if (!command) {
            Swal.fire({ icon: 'warning', title: I18n.t('common.notice'), text: I18n.t('cron.validation.command_required') });
            return;
        }
        
        try {
            const r = await fetch('/api/cron/add', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ minute, hour, day, month, weekday, command })
            });
            const data = await r.json();
            if (data.success) {
                closeAddModal();
                loadJobs();
            } else {
                Swal.fire(I18n.t('common.error'), data.error || I18n.t('common.add_failed'), 'error');
            }
        } catch (e) {
            Swal.fire(I18n.t('common.error'), e.message, 'error');
        }
    }
    
    async function removeJob(i) {
        const r = await Swal.fire({ icon: 'warning', title: I18n.t('common.confirm_delete_title'), text: I18n.t('cron.delete.confirm'), showCancelButton: true }); if (!r.isConfirmed) return;
        try {
            const r = await fetch('/api/cron/remove', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ raw: jobs[i].raw })
            });
            const data = await r.json();
            if (data.success) {
                loadJobs();
            } else {
                Swal.fire(I18n.t('common.error'), data.error || I18n.t('common.delete_failed'), 'error');
            }
        } catch (e) {
            Swal.fire(I18n.t('common.error'), e.message, 'error');
        }
    }
    
    async function toggleJob(i) {
        try {
            const r = await fetch('/api/cron/enable', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ raw: jobs[i].raw, enabled: jobs[i].enabled })
            });
            const data = await r.json();
            if (data.success) {
                loadJobs();
            }
        } catch (e) {
            Swal.fire(I18n.t('common.error'), e.message, 'error');
        }
    }
    
    async function runJob(i) {
        const command = jobs[i].command;
        const r = await Swal.fire({ icon: 'warning', title: I18n.t('cron.run.confirm_title'), text: I18n.t('cron.run.confirm_message') + '：' + command + '\n\n' + I18n.t('common.confirm') + '?', showCancelButton: true }); if (!r.isConfirmed) return;
        
        try {
            const r = await fetch('/api/cron/run', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ command })
            });
            const data = await r.json();
            if (data.success) {
                Swal.fire({ icon: 'success', title: I18n.t('cron.run.success'), text: data.stdout || '' });
            } else {
                Swal.fire({ icon: 'error', title: I18n.t('cron.run.failed'), text: data.stderr || data.error || I18n.t('common.unknown') });
            }
        } catch (e) {
            Swal.fire({ icon: 'error', title: I18n.t('cron.run.failed'), text: e.message });
        }
    }
    
    // Flatpickr 初始化
    let quickPicker = null;
    
    function initFlatpickr() {
        if (quickPicker) return;
        
        quickPicker = flatpickr("#quickSchedule", {
            locale: "zh",
            enableTime: true,
            noCalendar: false,
            dateFormat: "Y-m-d H:i",
            minDate: "today",
            defaultDate: new Date(),
            onChange: function(selectedDates, dateStr) {
                if (selectedDates.length > 0) {
                    const date = selectedDates[0];
                    const minute = date.getMinutes();
                    const hour = date.getHours();
                    const day = date.getDate();
                    const month = date.getMonth() + 1;
                    
                    $('minute').value = minute;
                    $('hour').value = hour;
                    $('day').value = day;
                    $('month').value = month;
                    $('weekday').value = '*';
                    
                    // 显示格式化的 cron 表达式
                    console.log(`Cron: ${minute} ${hour} ${day} ${month} *`);
                }
            }
        });
    }
    
    // 重新打开模态框时重新初始化 Flatpickr
    const originalOpenAddModal = openAddModal;
    openAddModal = function() {
        originalOpenAddModal();
        // 延迟初始化，确保 DOM 已渲染
        setTimeout(initFlatpickr, 100);
    }

loadJobs();
    I18n.setLang(I18n.lang);
    </script>
</body>
</html>
