<script lang="ts" setup>
/**
 * @Name: CreateEmployee.vue
 * @Description:
 * @Author: xinyan
 */
import { ElMessage, FormInstance, FormRules } from 'element-plus';
import { useResponse } from '/@/utils/useResponse';
import * as api from '../api';
import { ref } from 'vue';

const showDialog = defineModel({ default: false });
const emit = defineEmits(['refresh']);

const createLoading = ref(false);

// 图片处理
const upload = ref<UploadInstance>();

// 表单数据
interface RuleForm {
	name: string;
	department: string;
	phone: string;
	email: string;
	// user: string;
	// macaddress: string;
	// ipaddress: string;
	images: UploadFile[];
}

const ruleFormRef = ref<FormInstance>();
const formData = reactive<RuleForm>({
	name: '',
	department: '',
	phone: '',
	email: '',
	images: [],
});

const rules = reactive<FormRules<RuleForm>>({
	name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
	department: [{ required: true, message: '请输入部门', trigger: 'blur' }],
	phone: [
		// { required: true, message: '请输入电话号码', trigger: 'blur' },
		// { pattern: /^[0-9]{11}$/, message: '请输入正确的手机号码', trigger: 'blur' },
	],
	email: [
		// { required: true, message: '请输入邮箱', trigger: 'blur' },
		// { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' },
	],
});

const previewVisible = ref(false); // 控制预览对话框的显示
const previewImage = ref('');

const handlePreview = (file) => {
  previewImage.value = file.url || URL.createObjectURL(file.raw); // 获取图片 URL
  previewVisible.value = true; // 显示对话框
};

// 超过图片限制时触发的回调
const handleExceed: UploadProps['onExceed'] = (files) => {
	upload.value!.clearFiles();
	const file = files[0] as UploadRawFile;
	file.uid = genFileId();
	upload.value!.handleStart(file);
};

const submitForm = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate((valid, fields) => {
		if (valid) {
			handleSave();
			showDialog.value = false;
			emit('refresh');
			ElMessage.success('添加成功');
		} else {
			ElMessage.error('添加失败,请检查表单');
		}
	});
};

// 保存操作
async function handleSave() {
	const bodyData = new FormData();
	const fieldsToAppend = ['name', 'department', 'phone', 'email'];
	fieldsToAppend.forEach((field) => {
		bodyData.append(field, formData[field as keyof RuleForm]);
	});

	if (formData.images.length > 0 && formData.images[0].raw) {
		bodyData.append('images', formData.images[0].raw); // 使用 'images' 作为字段名，将 File 对象添加到 FormData 中
	}
	await useResponse(bodyData, api.createEmployee);
	// if (resp.code === 2000) {
	//   ElMessage.success('添加成功');
	// }
}

// 取消操作
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  formData.images = [];
  showDialog.value = false;
};

onMounted(() => {});
</script>

<template>
	<el-dialog v-model="showDialog" :close-on-click-modal="false" title="新增电脑信息" width="35%">
		<el-form ref="ruleFormRef" :model="formData" :rules="rules" class="employee-info-form" label-width="auto" status-icon>
			<el-form-item label="姓名：" prop="name">
				<el-input v-model="formData.name" placeholder="请输入姓名" />
			</el-form-item>
			<el-form-item label="部门：" prop="department">
				<el-input v-model="formData.department" placeholder="请输入部门" />
			</el-form-item>
			<el-form-item label="电话号码：" prop="phone">
				<el-input v-model="formData.phone" placeholder="请输入电话号码" />
			</el-form-item>
			<el-form-item label="邮箱：" prop="email">
				<el-input v-model="formData.email" placeholder="请输入邮箱" />
			</el-form-item>
			<!-- 人员图片上传 -->
			<el-form-item :key="images" label="人员图片：">
				<el-upload
					ref="upload"
					v-model:file-list="formData.images"
					:auto-upload="false"
					:limit="1"
					:on-exceed="handleExceed"
					action="#"
					list-type="picture-card"
          accept="image/*"
          :on-preview="handlePreview"
				>
					<el-icon>
						<Plus />
					</el-icon>
				</el-upload>
			</el-form-item>
		</el-form>
		<template #footer>
			<div class="dialog-footer">
				<el-button :loading="createLoading" type="primary" @click="submitForm(ruleFormRef)">保存</el-button>
				<el-button @click="resetForm(ruleFormRef)">取消</el-button>
			</div>
		</template>
	</el-dialog>
  <!-- 预览对话框 -->
  <el-dialog v-model="previewVisible" width="30%" height="30%">
    <img :src="previewImage" alt="预览图" style="width: 100%; height: auto;" />
  </el-dialog>
</template>

<style scoped>
.dialog-footer {
	margin-bottom: 10px;
	text-align: center;
}
</style>
