<script lang="ts" setup>
/**
 * @Name: EditEmployeeInfo.vue
 * @Description: 编辑电脑信息
 * @Author: xinyan
 */
import { ref } from 'vue';
import { ElIcon, ElMessage, FormInstance, FormRules, genFileId, UploadInstance, UploadProps, UploadRawFile } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import { useResponse } from '/@/utils/useResponse';
import * as api from '../api';

const visible = defineModel({ default: false });
const { employeeOverview, name } = defineProps<{
	employeeOverview: any;
	name: any;
}>();

const emit = defineEmits(['refresh']);

// 图片处理
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('');

onBeforeMount(() => {
	replaceCol();
});

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

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

const submitForm = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;

	await formEl.validate(async (valid, fields) => {
		if (valid) {
			const dataToUpload = new FormData();

			for (const key in formData) {
				if (key !== 'images' && formData.hasOwnProperty(key)) {
					dataToUpload.append(key, formData[key]);
				}
			}

			if (Array.isArray(formData.images)) {
				formData.images.forEach((image: any) => {
					if (image.raw) {
						dataToUpload.append('images', image.raw);
					}
				});
			}
			try {
				const resp = await useResponse({ id: employeeOverview.id, partial: 1, dataToUpload, }, api.updateEmployeeDetail);
				// 检查上传结果并提示用户
				if (resp.code === 2000) {
					ElMessage.success('修改成功');
					visible.value = false;
					emit('refresh');
				}
			} catch (error) {
				console.error('上传失败:', error);
				ElMessage.error('上传失败，请重试');
			}
		} else {
			console.log('error submit!', fields);
		}
	});
};

const resetForm = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
  visible.value = false;
	formEl.resetFields();
};

function replaceCol() {
	const result = Object.keys(formData).reduce((acc, key) => {
		if (key in employeeOverview) {
			// 如果字段是 images，则转换图片格式
			if (key === 'images' && Array.isArray(employeeOverview[key])) {
				acc[key] = employeeOverview[key].map((img: { image: string }) => ({
					name: '已上传图片',
					url: img.image_url,
				}));
			} else {
				acc[key] = employeeOverview[key];
			}
		}
		return acc;
	}, {} as { [key: string]: any });
	Object.assign(formData, result);
}

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

<template>
	<el-drawer v-model="visible" :title="`人员编辑 - ${name}`" size="30%">
		<el-form ref="ruleFormRef" :model="formData" :rules="rules" class="employee-info-form" label-width="auto">
			<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-item class="button-group">
				<el-button type="primary" @click="submitForm(ruleFormRef)">保存</el-button>
				<el-button @click="resetForm(ruleFormRef)">取消</el-button>
			</el-form-item>
		</el-form>
    <!-- 预览对话框 -->
    <el-dialog v-model="previewVisible" width="30%" height="30%">
      <img :src="previewImage" alt="预览图" style="width: 100%; height: auto;" />
    </el-dialog>
	</el-drawer>
</template>

<style scoped>
.employee-info-form {
	padding: 20px;
}

.button-group {
	margin-top: 20px;
	text-align: center;
}

.employee-info-form :deep(.el-form-item__label) {
	font-size: 14px;
	font-weight: 500;
}
</style>
