<template>
    <el-card shadow="never" class="list-card">

        <template #header>

            <div class="search" v-show="showSearch">
                <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">

                    <el-form-item prop="jobName">
                        <el-input v-model="queryParams.jobName" placeholder="请输入字典名称" clearable style="width: 240px"
                            @keyup.enter="getList" />
                    </el-form-item>

                    <el-form-item>
                        <el-button type="primary" icon="Search" @click="getList">搜索</el-button>
                        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </template>

        <Table ref="taskTableRef" :tableParams="tableParams" :btnRole="leftBtn" @handleAdd="handleAddTask"
            @handleEdit="handleUpdate" @selectionChange="handleSelectionChange">


        </Table>


        <el-dialog :title="dialogTitle" v-model="dialogVisible" width="30%">
            <el-form :model="form" :rules="formValidate" ref="taskFormRef" label-width="100px" class="demo-ruleForm">
                <el-form-item label="任务执行类" prop="jobName">
                    <el-input v-model="form.jobName" clearable></el-input>
                </el-form-item>
                <el-form-item label="任务组名" prop="jobGroup">
                    <el-input v-model="form.jobGroup" clearable></el-input>
                </el-form-item>
                <el-form-item label="cron表达式" prop="cronExpression">
                    <el-input v-model="form.cronExpression" clearable></el-input>
                    <a target="_blank" href="https://www.matools.com/cron/">
                        <i class="el-icon-info" style="margin:0 3px 3px 0;"></i>在线cron表达式生成
                    </a>
                </el-form-item>
                <el-form-item label="任务描述" prop="jobDescription">
                    <el-input v-model="form.jobDescription" clearable></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="handleSubmit">提交</el-button>
                </span>
            </template>
        </el-dialog>



    </el-card>
</template>
<script setup lang="ts" name="Task">
import { addTask, editTask, deleteTask, pauseTask, resumeTask, triggerTask, taskList } from '@/api/system/task/index';
import { getToday, getYesterday, getCurrentWeek, getMonthLastDay, addDateTime, subDateTime, getDayInfo, getWeekDay, dateFormate } from '@/utils/datetime';
import { tableTypes } from '@/components/Table/types'
import { TaskInfo, TaskInfoQuery } from '@/api/system/task/types';

const querys = reactive({
    showLoading: false,
});

const toggle = reactive({
    active: '1',

});
const leftBtn = ref([
    { type: 'add', hasPermi: `system:task:add` },
    { type: 'edit', hasPermi: `system:task:edit` },
    { type: 'remove', hasPermi: `system:task:remove` },
    { type: 'import', hasPermi: `system:task:import` },
    { type: 'export', hasPermi: `system:task:export` }
])

const detailDialog = reactive<DialogOption>({
    visible: false,
    title: ''
});
const taskTableRef = ref()
const showSearch = ref(true)

const handleSelectionChange = (val) => {
    console.log(val)
}

const tableParams = reactive<tableTypes<TaskInfoQuery, TaskInfo>>({
    tableColumn: [
        { show: true, label: '定时任务', prop: 'jobName', sortable: true },
        { show: true, label: '定时任务组', prop: 'jobGroup', sortable: true },
        { show: true, label: 'cron表达式', prop: 'cronExpression', sortable: true },
        { show: true, label: '任务描述', prop: 'jobDescription', sortable: true },
        { show: true, label: '上次执行时间', prop: 'previousFireTime', sortable: true },
        { show: true, label: '下次执行时间', prop: 'nextFireTime', sortable: true },
        {
            show: true, label: '状态', prop: 'status', sortable: true, render: ({ column }: { column: TaskInfo }) => {

                return [
                    h(ElTag, {}, column.jobStatus == 'NORMAL' ? '执行中' : '已停止'),
                ]
            },
        },

        {
            show: true, label: '操作', width: 300, prop: 'operation', disabledMove: true, render: ({ column }: { column: TaskInfo }) => {
                return [
                    h(ElButton, {
                        link: true, type: 'primary', onClick: () => {
                            resumeTask(column)
                        }
                    }, '恢复执行'),
                    h(ElButton, {
                        link: true, type: 'primary', onClick: () => {
                            triggerTask(column)
                        }
                    }, '立即执行'),
                    h(ElButton, {
                        link: true, type: 'primary', onClick: () => {
                            pauseTask(column)
                        }
                    }, '立即暂停'),
                ]
            }
        },
    ],
    keyId: 'keyId',
    queryParams: {
        jobName: undefined,
    },
    listFn: taskList,
    delFn: deleteTask,
})
const { queryParams } = toRefs(tableParams);

const modalType = ref(0);
const form = reactive<TaskInfo>({
    id: undefined,
    jobName: "",
    cronExpression: "",
    jobGroup: "",
    jobDescription: ""
});

const formValidate = {
    jobGroup: [
        { required: true, message: "任务组名不能为空", trigger: "blur" }
    ],
    jobName: [
        { required: true, message: "任务名不能为空", trigger: "blur" }
    ],
    cronExpression: [
        { required: true, message: "cron表达式不能为空", trigger: "blur" }
    ],
    jobDescription: [
        { required: true, message: "任务描述不能为空", trigger: "blur" }
    ]
};


const dialogVisible = ref(false);
const editDisabled = ref(false);
const dialogTitle = ref('');


const formRef = ref(null);

onMounted(() => {
    getList();
});
const queryFormRef = ref()
/** 重置按钮操作 */
const resetQuery = () => {
    queryFormRef.value?.resetFields();
    getList();
}

const handleChangeType = (value) => {
    toggle.active = value;
};

const reset = () => {
    Object.assign(form, {
        jobName: "",
        cronExpression: "",
        jobGroup: "",
        jobDescription: ""
    });
};

const handleAddTask = () => {
    dialogTitle.value = '添加任务';
    modalType.value = 0;
    reset();
    dialogVisible.value = true;
};

const handleUpdate = (row) => {
    dialogTitle.value = '编辑任务';
    modalType.value = 1;
    Object.assign(form, JSON.parse(JSON.stringify(row)));
    dialogVisible.value = true;
};
const taskFormRef = ref()

const handleSubmit = async () => {
    if (!taskFormRef.value) return;

    await taskFormRef.value.validate(async (valid) => {
        if (valid) {
            if (modalType.value === 0) {
                try {
                    const res = await addTask(form);
                    if (res.success && res.code == 200) {
                        ElMessage.success('添加成功');
                        getList();
                        dialogVisible.value = false;
                    } else {
                        ElMessage.error(res.msg);
                    }
                } catch (err) {
                    console.error(err);
                }
            } else {
                try {
                    const res = await editTask(form);
                    if (res.success && res.code == 200) {
                        ElMessage.success('编辑成功');
                        getList();
                        dialogVisible.value = false;
                    } else {
                        ElMessage.error(res.msg);
                    }
                } catch (err) {
                    console.error(err);
                }
            }
        }
    });
};


const getList = async () => {
    taskTableRef.value.getData()
};

const pause = (row) => {
    ElMessageBox.confirm(`确定要暂停任务${row.jobName}?`, "确认暂停", {
        confirmButtonText: "提交",
        cancelButtonText: "取消",
        type: "warning",
        center: true
    }).then(async () => {
        try {
            const params = {
                jobName: row.jobName,
                jobGroup: row.jobGroup,
            };
            const res = await pauseTask(params);
            if (res.success && res.code == 200) {
                ElMessage.success('暂停成功');
                getList();
            } else {
                ElMessage.error(res.msg);
            }
        } catch (err) {
            console.error(err);
        }
    }).catch(() => { });
};

const trigger = (row) => {
    ElMessageBox.confirm(`确定要立即执行${row.jobName}?`, "确认执行", {
        confirmButtonText: "提交",
        cancelButtonText: "取消",
        type: "warning",
        center: true
    }).then(async () => {
        try {
            const params = {
                jobName: row.jobName,
                jobGroup: row.jobGroup,
            };
            const res = await triggerTask(params);
            if (res.success && res.code == 200) {
                ElMessage.success('执行成功');
            } else {
                ElMessage.error(res.msg);
            }
        } catch (err) {
            console.error(err);
        }
    }).catch(() => { });
};

const resume = (row) => {
    ElMessageBox.confirm(`确定要重启任务${row.jobName}?`, "确认重启", {
        confirmButtonText: "提交",
        cancelButtonText: "取消",
        type: "warning",
        center: true
    }).then(async () => {
        try {
            const params = {
                jobName: row.jobName,
                jobGroup: row.jobGroup,
            };
            const res = await resumeTask(params);
            if (res.success && res.code == 200) {
                ElMessage.success('重启成功');
                getList();
            } else {
                ElMessage.error(res.msg);
            }
        } catch (err) {
            console.error(err);
        }
    }).catch(() => { });
};

const remove = (row) => {
    // ElMessageBox.confirm(`确定要删除任务${row.jobName}?`, "确认删除", {
    //     confirmButtonText: "提交",
    //     cancelButtonText: "取消",
    //     type: "warning",
    //     center: true
    // }).then(async () => {
    //     try {
    //         const params = {
    //             jobName: row.jobName,
    //             jobGroup: row.jobGroup,
    //         };
    //         const res = await deleteTask(params);
    //         if (res.success && res.code == 200) {
    //             ElMessage.success('删除成功');
    //             getList();
    //         } else {
    //             ElMessage.error(res.msg);
    //         }
    //     } catch (err) {
    //         console.error(err);
    //     }
    // }).catch(() => { });
};
</script>
<style type="text/css" scoped></style>
