<template>
	<el-dialog v-model="currentVisible" :title="currentMode === AddMode.ADD_TASK ? '新增' : '修改'" width="710" center
		align-center @close="handleClose" draggable>
		<el-form :model="ruleForm" :rules="rules" ref="ruleFormRef" label-width="100px">
			<el-form-item label="任务名称:" v-if="currentMode === AddMode.ADD_TASK" prop="taskName">
				<el-input v-model="ruleForm.taskName" placeholder="请输入任务名称" style="width: 90%" />
			</el-form-item>
			<el-form-item label="所属爬虫:" v-if="currentMode === AddMode.ADD_TASK" prop="spiderTypeValue">
				<el-select v-model="ruleForm.spiderTypeValue" placeholder="请选择所属爬虫" style="width: 90%" >
					<el-option v-for="item in spiderTypeOptions" :key="item.value" :label="item.label"
						:value="item.value" :id="item.value" />
				</el-select>
			</el-form-item>
			<el-form-item label="执行频率:" prop="cronExpression">
				<Crontab v-model="ruleForm.cronExpression" style="width: 90%" />
			</el-form-item>
		</el-form>
		<template #footer>
			<div class="dialog-footer">
				<el-button @click="handleClose">取消</el-button>
				<el-button type="primary" @click="handleConfirm">
					确定
				</el-button>
			</div>
		</template>
	</el-dialog>
</template>

<script lang="ts" setup>
import { onMounted, ref } from 'vue'
import { defineProps } from 'vue';
import { watch } from 'vue'
import { addSpiderTask } from '@/api/spiderTask'
import { AddMode } from './enum'
import { Crontab } from '@/components/Crontab/index'
import type { FormInstance, FormRules } from 'element-plus'
import  { ElMessage } from 'element-plus'

interface RuleForm {
	taskName: string
	spiderTypeValue: string
	cronExpression: string
}
const ruleFormRef = ref<FormInstance>()
const ruleForm = ref<RuleForm>({
	taskName: '',
	spiderTypeValue: '',
	cronExpression: '',
})
interface addDialogPropType {
	dialogVisible: boolean,
	mode: AddMode,
	jobId: string,
	cron: string,
	spiderType: string,
	options: string,
}
const props = defineProps<addDialogPropType>()
const rules = ref<FormRules<RuleForm>>({
	taskName: [
		{ required: true, message: '请输入任务名称', trigger: 'blur' },
		{ min: 1, max: 50, message: '任务名称应在1-50个字符之间', trigger: 'blur' },
	],
	spiderTypeValue: [
		{
			required: true,
			message: '请选择所属爬虫',
			trigger: 'change',
		},
	],
	cronExpression: [
		{
			required: true,
			message: '请输入执行频率',
			trigger: 'change',
		},
		{ 
			validator: (rule, value, callback) => {
				// 计算字符串中'*'的数量
				const starCount = (value.match(/\*/g) || []).length;
				if (starCount < 5) {
					callback(new Error('cron表达式最多设置一个间隔'));
				} else {
					callback();
				}
			},
			trigger: 'blur'
		}
	]
})
// 向父组件传递dialog值
const emit = defineEmits(['update:dialogVisible', 'confirm', 'update:mode', 'getTaskList'])
// 组件的状态
const currentVisible = ref(props.dialogVisible)
const currentMode = ref(props.mode)
const spiderTypeOptions = ref([
	{
		value: 'api_spider',
		label: 'api_spider'
	},
	{
		value: 'dsn_now',
		label: 'dsn_now'
	},
	{
		value: 'itu_space_explorer',
		label: 'itu_space_explorer'
	},
])
const taskParams = ref({
	scrapyd_server_id: '1',
	schedule_type: '0',
	project: 'spiders'
})
const cronExpression = ref('')

// 关闭的方法
const handleClose = () => {
	ruleForm.value.taskName = ''
	ruleForm.value.spiderTypeValue
	ruleForm.value.cronExpression = ''
	ruleFormRef.value?.resetFields()
	currentVisible.value = false
}
// 确定的方法
const handleConfirm = async () => {
	console.log(ruleForm.value.cronExpression);
	
	if (!ruleFormRef.value) return
	await ruleFormRef.value.validate(async (valid, fields) => {
		console.log('开始校验');
		//验证表单内容是否通过，通过继续执行
		if (valid) {
			if (currentMode.value === AddMode.ADD_TASK) {
				await addSpiderTask({
					scrapyd_server_id: taskParams.value.scrapyd_server_id,
					schedule_type: taskParams.value.schedule_type,
					project: taskParams.value.project,
					spider: ruleForm.value.spiderTypeValue,
					cron: ruleForm.value.cronExpression,
					options: JSON.stringify({ jobName: ruleForm.value.taskName })
				})
				currentVisible.value = false
				emit('getTaskList')
				ElMessage.success('添加成功')
			} else if (currentMode.value === AddMode.UPDATE_TASK) {
				await addSpiderTask({
					scrapyd_server_id: taskParams.value.scrapyd_server_id,
					schedule_type: taskParams.value.schedule_type,
					project: taskParams.value.project,
					spider: props.spiderType,
					job_id: props.jobId,
					cron: ruleForm.value.cronExpression,
					options: props.options
				})
				currentVisible.value = false
				emit('getTaskList')
				ElMessage.success('修改成功')
			}
		} else {
			console.log('校验不通过');
		}
	})
}

// 监听props变化，同步给组件内部
watch(() => props.dialogVisible,
	(newVal) => {
		currentVisible.value = newVal
	}
)

// 监听组件内部状态变化，同步给父组件，这样才能做到控制对话框组件的显隐
watch(() => currentVisible.value,
	(newVal) => {
		emit('update:dialogVisible', newVal)
	}
)

watch(() => props.mode,
	(newVal) => {
		currentMode.value = newVal
	}
)

watch(() => currentMode.value,
	(newVal) => {
		emit('update:mode', newVal)
	}
)
watch(
	[() => props.dialogVisible, () => props.mode, () => props.cron],
	([newVisible, newMode, newCron]) => {
		if (newVisible && newMode === AddMode.UPDATE_TASK) {
			ruleForm.value.cronExpression = newCron;
		}
		if (!newVisible) {
			// 清空表单
			cronExpression.value = ''
		}
	},
	{ immediate: true }
);
onMounted(() => {

})
</script>

<style>
/* 修改弹出框样式 */
.el-dialog {
	background: transparent;
	background-image: url("@/assets/picture/dialog1.png");
	background-size: 100% 100%;
	background-repeat: no-repeat;
	color: #ffffff;

	.el-dialog__title {
		color: #ffffff;
	}

	.el-input__inner {
		color: #ffffff;
	}
}

/* 修改表单样式 */
.el-form {
	.el-form-item__label {
		color: #ffffff;
	}
}
</style>
