<template>
	<el-dialog v-model="state.dialogVisible" width="500px" draggable :title="dialogTitle" @close="close" destroy-on-close>
		<el-form :model="state.ruleForm" ref="ruleFormRef">
			<el-form-item label="" prop="shiftId" :rules="[{ required: true, message: '请选择班次', trigger: 'change' }]">
				<el-select-v2
					v-model="state.ruleForm.shiftId"
					filterable
					:options="numberOptions"
					:props="{
						label: 'name',
						value: 'id',
					}"
					placeholder="请选择班次"
					class="w100"
				/>
			</el-form-item>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="closeDialog" class="default-button">取 消</el-button>
				<el-button type="primary" @click="onSubmit(ruleFormRef)" :loading="loading">确 定</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue';
import { ElMessage, FormInstance } from 'element-plus';
import { throttle } from '@/utils/tools';
import { batchScheduling, deleteScheduling, getSchedulingDetail, getWorkforceClassList, updateScheduling } from '@/api/system/workforce';

// 定义子组件向父组件传值/事件
const emit = defineEmits(['updateList']);

// 定义变量内容
const state = reactive<any>({
	dialogVisible: false,
	ruleForm: {
		shiftId: null,
	},
});
let loading = ref<boolean>(false); // 加载状态
const dialogTitle = ref('选择班次');
// 打开弹窗
const ruleFormRef = ref<RefType>();
const numberOptions = ref<any[]>([]); // 班次列表
const schedulingId = ref(''); // 排班ID
const schedulingDate = ref(''); // 排班日期
const userId = ref(''); // 用户ID
const openDialog = async (row: any) => {
	if (!row) return;
	schedulingId.value = row.row[row.column.property]?.id ?? 'null';
	schedulingDate.value = row.column.property;
	userId.value = row.row?.UserId ?? '';
	try {
		const numberRes = await getWorkforceClassList({ PageSize: 999999, PageIndex: 1 });
		numberOptions.value = numberRes.result?.items ?? [];
		if (schedulingId.value !== 'null') {
			numberOptions.value.push({
				name: '空',
				id: '空',
			});
		}
		dialogTitle.value = `选择 【${row.row?.SchedulingUserName} ${row.column?.property}】排班`;
		if (schedulingId.value) {
			const schedulingRes = await getSchedulingDetail(schedulingId.value);
			state.ruleForm.shiftId = schedulingRes.result?.shiftId;
		}
		state.dialogVisible = true;
	} catch (error) {
		console.log(error);
	}
};
// 关闭弹窗
const closeDialog = () => {
	state.dialogVisible = false;
};
const close = () => {
	ruleFormRef.value?.resetFields();
	ruleFormRef.value?.clearValidate();
};
// 保存
const onSubmit = throttle(async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate((valid: boolean) => {
		if (!valid) return;
		state.loading = true;
		if (schedulingId.value === 'null') {
			// 新增排班
			const request = {
				userIds: [userId.value],
				shiftId: state.ruleForm.shiftId,
				schedulingTime: schedulingDate.value,
			};
			batchScheduling(request)
				.then(() => {
					ElMessage.success('排班成功');
					loading.value = false;
					closeDialog();
					emit('updateList');
				})
				.finally(() => {
					loading.value = false;
					closeDialog();
					emit('updateList');
				});
		} else if (state.ruleForm.shiftId === '空') {
			// 删除排班
			deleteScheduling({ ids: [schedulingId.value] })
				.then(() => {
					ElMessage.success('排班成功');
					closeDialog();
					emit('updateList');
					loading.value = false;
				})
				.catch(() => {
					loading.value = false;
				});
		} else {
			// 修改排班
			const request = {
				shiftId: state.ruleForm.shiftId,
				schedulingTime: schedulingDate.value,
				id: schedulingId.value,
			};
			updateScheduling(request)
				.then(() => {
					ElMessage.success('排班成功');
					closeDialog();
					emit('updateList');
					loading.value = false;
				})
				.catch(() => {
					loading.value = false;
				});
		}
	});
}, 300);
// 暴露变量
defineExpose({
	openDialog,
	closeDialog,
});
</script>
