<template>
	<el-dialog v-model="state.dialogVisible" width="500px" draggable title="选择用户" @close="close" destroy-on-close>
		<el-form :model="state.ruleForm" label-width="90px" ref="ruleFormRef">
			<el-form-item label="用户姓名" prop="employee" :rules="[{ required: true, message: '请选择用户', trigger: 'change' }]">
				<el-select
					v-model="state.ruleForm.employee"
					filterable
					remote
					class="w100"
					reserve-keyword
					placeholder="填写用户姓名查询"
					remote-show-suffix
					:remote-method="remoteMethod"
					:loading="loading"
					value-key="id"
					multiple
				>
					<el-option v-for="item in userList" :key="item.id" :label="item.userName" :value="item" />
				</el-select>
			</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 { queryUser } from '@/api/system/workflow';
import { removeDuplicate } from '@/utils/arrayOperation';
import { addWorkforce } from '@/api/system/workforce';

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

// 定义变量内容
const state = reactive<any>({
	dialogVisible: false,
	ruleForm: {
		employee: [], // 当前用户
	},
});
let loading = ref<boolean>(false); // 加载状态
// 打开弹窗
const ruleFormRef = ref<RefType>();
const openDialog = async () => {
	try {
		state.dialogVisible = true;
	} catch (error) {
		console.log(error);
	}
};
// 关闭弹窗
const closeDialog = () => {
	state.dialogVisible = false;
};
const close = () => {
	ruleFormRef.value?.resetFields();
	ruleFormRef.value?.clearValidate();
};
// 远程搜索用户名称
// 指定用户列表
const userList = ref<EmptyArrayType>([]);
const remoteMethod = (query: string) => {
	if (query !== '') {
		loading.value = true;
		queryUser({ name: query }).then((res: any) => {
			loading.value = false;
			const newUsers = res.result.map((item: any) => {
				return {
					...item,
					userName: !item.name.includes('-') ? item.name + '-' + item.organization?.name : item.name,
				};
			});
			userList.value = removeDuplicate([...newUsers, ...userList.value], 'id');
		});
	}
};
// 新增
const onSubmit = throttle(async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate((valid: boolean) => {
		if (!valid) return;
		loading.value = true;
    const request = state.ruleForm.employee.map((item: any) => {
      return {
        userId: item.id,
        userName: item.name,
      };
    });
		addWorkforce(request)
			.then(() => {
				emit('updateList');
				ElMessage.success('添加成功');
				loading.value = false;
				closeDialog();
			})
			.finally(() => {
				loading.value = false;
			});
	});
}, 300);
// 暴露变量
defineExpose({
	openDialog,
	closeDialog,
});
</script>
