<!-- 
 * @Description: 表单
 * @Author: syy 
 * @Date: 2023-12-15 15:45:59
-->
<template>
  <div>
    <form-container v-model="visible" :title="`${sysUserProps.opt}人员`" form-size="800px" @close="onClose">
      <el-form
        ref="sysUserFormRef"
        :rules="rules"
        :disabled="sysUserProps.disabled"
        :model="sysUserProps.record"
        :hide-required-asterisk="sysUserProps.disabled"
        label-width="auto"
        label-suffix=" :"
      >
        <el-tabs v-model="activeName">
          <Basic v-model="sysUserProps.record"></Basic>
        </el-tabs>
      </el-form>
      <template #footer>
        <el-button @click="onClose"> 取消 </el-button>
        <el-button v-show="!sysUserProps.disabled" type="primary" @click="handleSubmit"> 确定 </el-button>
      </template>
    </form-container>
  </div>
</template>

<script setup lang="ts" name="SysUserKeyPersonnelForm">
import { SysUserPersonnel, userManageKeyPersonApi } from "@/api";
import { FormOptEnum } from "@/enums";
import { required } from "@/utils/formRules";
import { FormInstance } from "element-plus";
import Basic from "./form_basic.vue";

const visible = ref(false); //是否显示表单
const activeName = ref("basic");
// 表单参数
const sysUserProps = reactive<FormProps.Base<SysUserPersonnel.SysUserPerInfo>>({
  opt: FormOptEnum.ADD,
  record: {},
  disabled: false
});

// 表单验证规则
const rules = reactive({
  name: [required("请输入姓名")],
  gender: [required("请选择性别")],
  faces: [required("请上传人脸图片")],
  phone: [required("请输入手机号")]
});

/**
 * 打开表单
 * @param props 表单参数
 */
function onOpen(props: FormProps.Base<SysUserPersonnel.SysUserPerInfo>) {
  Object.assign(sysUserProps, props); //合并参数
  if (props.opt == FormOptEnum.ADD) {
    //如果是新增,设置默认值
    // sysUserProps.record.sortCode = 99;
  }
  visible.value = true; //显示表单
  if (props.record.personId) {
    //如果传了id，就去请求api获取record
    userManageKeyPersonApi.detail({ id: props.record.personId }).then((res: any) => {
      sysUserProps.record = res.data;
    });
  }
}

// 提交数据（新增/编辑）
const sysUserFormRef = ref<FormInstance>();
/** 提交表单 */
async function handleSubmit() {
  sysUserFormRef.value?.validate(async valid => {
    if (!valid) return; //表单验证失败
    //提交表单
    if (sysUserProps.record.faces.length === 0) {
      return ElMessage.error("请上传人脸图片");
    }
    if (sysUserProps.record.personId) {
      await userManageKeyPersonApi
        .update(sysUserProps.record)
        .then(() => {
          sysUserProps.successful!(); //调用父组件的successful方法
        })
        .finally(() => {
          onClose();
        });
    } else {
      await userManageKeyPersonApi
        .add(sysUserProps.record)
        .then(() => {
          sysUserProps.successful!(); //调用父组件的successful方法
        })
        .finally(() => {
          onClose();
        });
    }
  });
}

/** 关闭表单*/
function onClose() {
  visible.value = false;
  activeName.value = "basic";
}

// 暴露给父组件的方法
defineExpose({
  onOpen
});
</script>

<style lang="scss" scoped></style>
