<template>
	<el-dialog :title="titleMap[mode]" v-model="visible" :width="600" destroy-on-close @closed="$emit('closed')">
		<el-form :model="form" :rules="rules" :disabled="mode==='show'" ref="formRef" label-width="100px">
			<el-form-item label="任务名称" prop="crontab_name">
				<el-input type="text" v-model="form.crontab_name" placeholder="请输入任务名称" clearable></el-input>
			</el-form-item>
			<el-form-item label="调用方法" prop="callback">
				<el-input type="text" v-model="form.callback" placeholder="请输入调用方法" clearable></el-input>
			</el-form-item>
			<el-form-item label="cron表达式" prop="rule">
				<pi-cron v-model="form.rule"></pi-cron>
			</el-form-item>
			<el-form-item label="是否并发" prop="singleton">
				<el-switch v-model="form.singleton" :active-value="1" :inactive-value="0"></el-switch>
			</el-form-item>
			<el-form-item label="是否记录日志" prop="skip_log">
				<el-switch v-model="form.skip_log" :active-value="1" :inactive-value="0"></el-switch>
			</el-form-item>
			<el-form-item label="是否启用" prop="enable">
				<el-switch v-model="form.enable" :active-value="1" :inactive-value="0"></el-switch>
			</el-form-item>
			<el-form-item label="备注" prop="memo">
				<el-input type="textarea" v-model="form.memo" placeholder="请输入备注" clearable></el-input>
			</el-form-item>
		</el-form>
		<template #footer>
			<el-button @click="visible=false" >取 消</el-button>
			<el-button v-if="mode!=='show'" type="primary" :loading="isSaveing" @click="submit()">保 存</el-button>
		</template>
	</el-dialog>
</template>

<script setup>
import {getCurrentInstance, ref} from 'vue'
import api from "@/api/index.js"
import piCron from "@/components/piCron"
import piEditor from "@/components/piEditor"

defineExpose({
	open
})
const emit = defineEmits(['success', 'closed'])
const formRef = ref(null)
const {proxy} = getCurrentInstance()

let mode = ref('add')
let titleMap = ref({
	add: '新增',
	edit: '编辑',
	show: '查看'
})
let visible = ref(false)
let isSaveing = ref(false)
let form = ref({
	crontab_id: null,
	crontab_name: '',
	singleton: 1,
	enable: 1,
	skip_log: 1,
	rule: '',
	callback: ''
})
const rules = ref({
	crontab_name:[
		{required: true, message: '请填写任务名称'}
	],
	rule:[
		{required: true, message: '请填写cron表达式'}
	],
	callback:[
		{required: true, message: '请填写调用方法'}
	]
})

function open(m = 'add', data = null) {
	mode.value = m
	visible.value = true
	Object.assign(form.value, data)
}

async function submit(){
	// 校验登录
	const validate = await formRef.value.validate().catch(() => {});
	if(!validate){ return false }
	isSaveing.value = true;
	const res = form.value.crontab_id? await api.system.crontab.edit(form.value) : await api.system.crontab.add(form.value);
	isSaveing.value = false;
	emit('success')
	visible.value = false;
	proxy.$message.success(res.msg)
}
</script>
