<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>定时任务管理</title>
    <link rel="stylesheet" th:href="@{/layui/css/layui.css}">
    <link rel="stylesheet" th:href="@{/css/common.css}">
    <script th:src="@{/layui/jquery-3.4.1.min.js}"></script>
    <script th:src="@{/layui/layui.js}"></script>
    <script th:src="@{/js/common.js}"></script>
    <script th:src="@{/js/rules.js}"></script>

    <style>
        body {
            background: #f2f2f2
        }

        #boxDiv {
            background: #ffffff
        }

        #titleDiv {
            overflow: visible;
        }

        .content {
            padding: 0 8px;
        }
    </style>
</head>
<body class="layui-layout-body">
<div id="boxDiv" style="left:8px;right: 8px;bottom:8px;top:8px;position:absolute;">
    <div class="toolbar" id="titleDiv">
        <div class="layui-inline">
            <span>任务名称：</span>
            <input type="text" id="searchName" placeholder="任务名称关键字" autocomplete="off" class="layui-input formWidth"/>
        </div>

        <div class="layui-inline">
            <span>任务类型：</span>
            <select id="searchType" class="layui-input formWidth">
                <option value="">全部</option>
                <option value="1">对账任务</option>
                <option value="2">数据同步</option>
                <option value="3">其他任务</option>
            </select>
        </div>

        <div class="layui-inline">
            <button class="layui-btn layui-btn-sm layui-btn-normal" data-type="search" id="search">
                <i class="layui-icon">&#xe615;</i>查询
            </button>
            <button class="layui-btn layui-btn-sm layui-btn-normal" data-type="add" id="add">
                <i class="layui-icon">&#xe654;</i>添加
            </button>
            <button class="layui-btn layui-btn-sm layui-btn-warm" onclick="refreshJobList()">
                <i class="layui-icon layui-icon-refresh"></i>刷新任务状态
            </button>
        </div>
    </div>

    <table id="mainTable" lay-filter="quartzTable"></table>

    <!-- 表格操作栏 -->
    <script type="text/html" id="barDemo">
        <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
        {{# if(d.status === '0'){ }}
        <a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="start">启动</a>
        {{# } else { }}
        <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="pause">暂停</a>
        {{# } }}
        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
    </script>

    <!-- 状态列模板 -->
    <script type="text/html" id="statusTpl">
        {{# if(d.status === '0'){ }}
        <span style="color: #FF5722;">已暂停</span>
        {{# } else { }}
        <span style="color: #5FB878;">运行中</span>
        {{# } }}
    </script>

    <!-- 新增/编辑任务弹窗 -->
    <div id="addQuartz" style="display:none;">
        <form class="layui-form" style="margin-top:20px; padding-right: 20px;" lay-filter="quartzForm">
            <input type="hidden" id="configId" name="configId"/>

            <div class="layui-form-item">
                <label class="layui-form-label">任务名称:</label>
                <div class="layui-input-block">
                    <input type="text" id="quartzName" name="quartzName" required lay-verify="required"
                           autocomplete="off" placeholder="请输入任务名称" class="layui-input">
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">任务类型:</label>
                <div class="layui-input-block">
                    <select id="jobType" name="jobType" lay-verify="required">
                        <option value="">请选择任务类型</option>
                        <option value="1">对账任务</option>
                        <option value="2">数据同步</option>
                        <option value="3">其他任务</option>
                    </select>
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">任务类:</label>
                <div class="layui-input-block">
                    <input type="text" id="quartz_class" name="quartz_class" required lay-verify="required"
                           autocomplete="off" placeholder="例如: com.saye.hospitalgd.scheduler.job.XXXJob"
                           class="layui-input">
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">执行时间:</label>
                <div class="layui-input-block">
                    <input type="radio" name="timeType" value="cron" title="Cron表达式" checked>
                    <input type="radio" name="timeType" value="simple" title="简单配置">
                </div>
            </div>

            <div class="layui-form-item" id="cronDiv">
                <label class="layui-form-label">Cron表达式:</label>
                <div class="layui-input-block">
                    <input type="text" id="cronExpression" name="cronExpression"
                           autocomplete="off" placeholder="例如: 0 0 2 * * ? (每天凌晨2点执行)"
                           class="layui-input">
                    <div class="layui-form-mid layui-word-aux">
                        <a href="javascript:void(0);" onclick="showCronHelp()">Cron表达式帮助</a>
                    </div>
                </div>
            </div>

            <div class="layui-form-item layui-hide" id="simpleDiv">
                <label class="layui-form-label">执行频率:</label>
                <div class="layui-input-inline" style="width: 80px;">
                    <input type="number" id="intervalValue" name="intervalValue" value="1"
                           autocomplete="off" class="layui-input">
                </div>
                <div class="layui-input-inline" style="width: 120px;">
                    <select id="intervalUnit" name="intervalUnit">
                        <option value="hour">小时</option>
                        <option value="day" selected>天</option>
                        <option value="week">周</option>
                    </select>
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">备注:</label>
                <div class="layui-input-block">
                    <textarea id="remark" name="remark" placeholder="请输入任务备注说明"
                              class="layui-textarea"></textarea>
                </div>
            </div>
        </form>
    </div>

    <!-- Cron帮助弹窗 -->
    <div id="cronHelp" style="display:none; padding: 20px;">
        <div style="line-height: 1.8;">
            <p><strong>Cron表达式格式：</strong>秒 分 时 日 月 周 [年]</p>
            <p><strong>常用示例：</strong></p>
            <ul style="list-style: disc; padding-left: 30px;">
                <li><code>0 0 2 * * ?</code> - 每天凌晨2点执行</li>
                <li><code>0 0 0/1 * * ?</code> - 每小时执行一次</li>
                <li><code>0 0 12 * * ?</code> - 每天中午12点执行</li>
                <li><code>0 0 1 1 * ?</code> - 每月1号凌晨1点执行</li>
                <li><code>0 0 23 ? * MON-FRI</code> - 周一到周五晚上11点执行</li>
                <li><code>0 0/30 * * * ?</code> - 每30分钟执行一次</li>
            </ul>
            <p><strong>特殊字符说明：</strong></p>
            <ul style="list-style: disc; padding-left: 30px;">
                <li><code>*</code> - 任意值</li>
                <li><code>?</code> - 不指定值（用于日和周）</li>
                <li><code>-</code> - 范围（例如：10-12）</li>
                <li><code>,</code> - 多个值（例如：MON,WED,FRI）</li>
                <li><code>/</code> - 递增（例如：0/15表示从0开始每15单位）</li>
            </ul>
        </div>
    </div>

</div>
</body>
<script>
    let element, table, laydate, layer, form;
    let isEditMode = false;

    layui.use(['element', 'table', 'laydate', 'layer', 'form'], function () {
        element = layui.element;
        table = layui.table;
        laydate = layui.laydate;
        layer = layui.layer;
        form = layui.form;

        //表格加载
        table.render({
            elem: '#mainTable',
            height: 'full-' + 58,
            url: '/quartzConfig/findQuartzConfig',
            title: '定时任务表',
            page: true,//开启分页
            limit: 20,
            limits: [20, 30, 50],
            defaultToolbar: [],
            id: 'quartzTable',
            cols: [
                [
                    {type: 'numbers', title: '序号', width: 60},
                    {field: 'quartzName', title: '任务名称', width: 200},
                    {field: 'quartzClass', title: '任务类', minWidth: 300},
                    {field: 'quartzType', title: '任务类型', width: 100, templet: function (d) {
                        if (d.quartzType === '1') return '对账任务';
                        if (d.quartzType === '2') return '数据同步';
                        if (d.quartzType === '3') return '其他任务';
                        return d.quartzType || '-';
                    }},
                    {field: 'expression', title: 'Cron表达式', width: 150},
                    {field: 'status', title: '状态', width: 100, align: 'center', templet: '#statusTpl'},
                    {field: 'createTime', title: '创建时间', width: 160},
                    {fixed: 'right', title: '操作', align: 'center', width: 200, toolbar: '#barDemo'}
                ]
            ]
        });

        // 查询
        $("#search").on('click', function () {
            search();
        });

        // 新增
        $("#add").on('click', function () {
            isEditMode = false;
            form.val('quartzForm', {
                configId: '',
                quartzName: '',
                jobType: '',
                quartz_class: '',
                cronExpression: '0 0 2 * * ?',
                intervalValue: '1',
                intervalUnit: 'day',
                remark: ''
            });

            layer.open({
                type: 1,
                title: "新增定时任务",
                shade: 0.3,
                area: ['600px', '90%'],
                offset: 'auto',
                content: $("#addQuartz"),
                btn: ['保存', '取消'],
                btnAlign: 'c',
                success: function () {
                    form.render();
                },
                yes: function (index, layero) {
                    saveQuartz(index);
                },
                btn2: function () {
                }
            });
        });

        // 表格操作事件
        table.on('tool(quartzTable)', function (obj) {
            let data = obj.data;

            if (obj.event === 'edit') {
                editQuartz(data);
            } else if (obj.event === 'start') {
                changeStatus(data.configId, '1');
            } else if (obj.event === 'pause') {
                changeStatus(data.configId, '0');
            } else if (obj.event === 'del') {
                deleteQuartz(data.configId);
            }
        });

        // 监听时间类型切换
        form.on('radio(timeType)', function (data) {
            if (data.value === 'cron') {
                $('#cronDiv').removeClass('layui-hide');
                $('#simpleDiv').addClass('layui-hide');
            } else {
                $('#cronDiv').addClass('layui-hide');
                $('#simpleDiv').removeClass('layui-hide');
            }
        });

        // 初始查询
        search();
    });

    // 查询
    function search() {
        let quartzName = $("#searchName").val();
        let quartzType = $("#searchType").val();

        table.reload('quartzTable', {
            method: 'get',
            url: '/quartzConfig/findQuartzConfig',
            where: {
                quartz_name: quartzName,
                quartz_type: quartzType
            },
            page: {
                curr: 1
            }
        });
    }

    // 编辑任务
    function editQuartz(data) {
        isEditMode = true;
        
        form.val('quartzForm', {
            configId: data.configId,
            quartzName: data.quartzName,
            jobType: data.quartzType,
            quartz_class: data.quartzClass,
            cronExpression: data.expression,
            remark: data.remark
        });

        layer.open({
            type: 1,
            title: "编辑定时任务",
            shade: 0.3,
            area: ['600px', '90%'],
            offset: 'auto',
            content: $("#addQuartz"),
            btn: ['保存', '取消'],
            btnAlign: 'c',
            success: function () {
                form.render();
            },
            yes: function (index, layero) {
                saveQuartz(index);
            },
            btn2: function () {
            }
        });
    }

    // 保存任务
    function saveQuartz(index) {
        let quartzName = $("#quartzName").val();
        let jobType = $("#jobType").val();
        let quartzClass = $("#quartz_class").val();
        let remark = $("#remark").val();
        let configId = $("#configId").val();

        if (!quartzName) {
            layer.msg('请输入任务名称', {icon: 2});
            return;
        }
        if (!jobType) {
            layer.msg('请选择任务类型', {icon: 2});
            return;
        }
        if (!quartzClass) {
            layer.msg('请输入任务类', {icon: 2});
            return;
        }

        // 获取cron表达式
        let timeType = $("input[name='timeType']:checked").val();
        let cronExpression = '';
        
        if (timeType === 'cron') {
            cronExpression = $("#cronExpression").val();
            if (!cronExpression) {
                layer.msg('请输入Cron表达式', {icon: 2});
                return;
            }
        } else {
            // 简单配置转换为cron表达式
            let intervalValue = $("#intervalValue").val();
            let intervalUnit = $("#intervalUnit").val();
            
            if (intervalUnit === 'hour') {
                cronExpression = '0 0 0/' + intervalValue + ' * * ?';
            } else if (intervalUnit === 'day') {
                cronExpression = '0 0 2 */' + intervalValue + ' * ?';
            } else if (intervalUnit === 'week') {
                cronExpression = '0 0 2 ? * MON/' + intervalValue;
            }
        }

        let url = isEditMode ? '/quartzConfig/modifyQuartz' : '/quartzConfig/addNewQuartz';
        let param = {
            quartzName: quartzName,
            jobType: jobType,
            quartz_class: quartzClass,
            remark: remark,
            dataStr: cronExpression,  // 直接传递完整的cron表达式
            time: '0'  // 传递time参数供后端使用
        };

        if (isEditMode) {
            param.configId = configId;
        }

        let load = layer.load();
        AjaxPostJson(url, param, function (data) {
            layer.close(load);
            if (data.errCode === "0") {
                layer.msg('保存成功', {icon: 1, time: 1000}, function () {
                    layer.close(index);
                    search();
                });
            } else {
                layer.alert(data.errMsg || '保存失败', {icon: 2});
            }
        });
    }

    // 修改状态
    function changeStatus(configId, status) {
        let statusText = status === '1' ? '启动' : '暂停';
        
        layer.confirm('确定要' + statusText + '该任务吗？', {title: statusText + '任务'}, function (index) {
            let url = '/quartzConfig/changestatus';
            let param = {
                configId: configId,
                status: status
            };

            let load = layer.load();
            AjaxPostJson(url, param, function (data) {
                layer.close(load);
                layer.close(index);
                
                if (data.errCode === "0") {
                    layer.msg(statusText + '成功', {icon: 1, time: 1000}, function () {
                        search();
                    });
                } else {
                    layer.alert(data.errMsg || statusText + '失败', {icon: 2});
                }
            });
        });
    }

    // 删除任务
    function deleteQuartz(configId) {
        layer.confirm('确定删除该定时任务吗？删除后将无法恢复！', {title: '删除任务'}, function (index) {
            let url = '/quartzConfig/deleteQuartz';
            let param = {
                configId: configId
            };

            let load = layer.load();
            AjaxPostJson(url, param, function (data) {
                layer.close(load);
                layer.close(index);
                
                if (data.errCode === "0") {
                    layer.msg('删除成功', {icon: 1, time: 1000}, function () {
                        search();
                    });
                } else {
                    layer.alert(data.errMsg || '删除失败', {icon: 2});
                }
            });
        });
    }

    // 刷新任务列表
    function refreshJobList() {
        let load = layer.load(1, {shade: [0.3, '#000']});
        
        $.ajax({
            url: '/quartzConfig/get_all_jobs',
            type: 'POST',
            dataType: 'json',
            success: function (data) {
                layer.close(load);
                if (data.quartzJobsVOList) {
                    layer.msg('刷新成功，当前运行中的任务数：' + data.quartzJobsVOList.length, {icon: 1});
                    search();
                } else {
                    layer.msg('刷新成功', {icon: 1});
                    search();
                }
            },
            error: function () {
                layer.close(load);
                layer.alert('刷新失败，请检查网络连接！', {icon: 2});
            }
        });
    }

    // 显示Cron帮助
    function showCronHelp() {
        layer.open({
            type: 1,
            title: 'Cron表达式帮助',
            shade: 0.3,
            area: ['600px', '500px'],
            content: $("#cronHelp")
        });
    }
</script>
</html>

