<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';

const showDialog = defineModel({ default: 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' }],
  email: [{ required: true, message: '请输入所属商铺', trigger: 'blur' }],
});

// 超过图片限制时触发的回调
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();
      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]);
  });

  // 处理图片文件，将每个图片文件对象添加到 FormData 中
  const imageFile = formData.images[0]?.raw; // 获取 raw 属性中的 File 对象
  if (imageFile instanceof File) {
    bodyData.append('images', imageFile); // 使用 'images' 作为字段名，将 File 对象添加到 FormData 中
  }
  await useResponse(bodyData, api.createEmployee);
}

// 取消操作
const handleCancel = () => {
  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"
        >
          <el-icon>
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm(ruleFormRef)">保存</el-button>
        <el-button @click="handleCancel">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

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