<template>
  <basicModal
    @register="modalRegister"
    ref="modalRef"
    class="basicModal basicFormModal"
    @on-ok="handleSubmit"
    @on-close="handleClose"
  >
    <template #default>
      <n-form
        class="ls-form"
        ref="formRef"
        :model="formData"
        label-placement="left"
        label-width="85px"
      >
        <n-form-item
          label="模板名称"
          path="name"
          :rule="{ required: true, message: '请输入模板名称', trigger: 'blur' }"
        >
          <n-input
            :maxlength="50"
            placeholder="请输入模板名称"
            clearable
            v-model:value="formData.name"
          />
        </n-form-item>
        <n-form-item
          label="模板code"
          path="code"
          :rule="{ required: true, message: '请输入模板code', trigger: 'blur' }"
        >
          <n-input
            v-if="!formData.id"
            :maxlength="100"
            placeholder="请输入模板code"
            clearable
            v-model:value="formData.code"
          />
          <span v-else>{{ formData.code }}</span>
        </n-form-item>
        <n-form-item
          label="模板文件"
          path="filePath"
          :rule="{ key: 'filePath', required: true, message: '请上传模板文件', trigger: 'blur' }"
        >
          <UploadFile
            @upload="fileUpload"
            file-type=".xlsx.xls.doc.docx"
            name="file"
            :fileLists="
              formData.filePath ? [{ name: formData.fileName, url: formData.filePath }] : []
            "
          />
        </n-form-item>
      </n-form>
    </template>
  </basicModal>
</template>
<script lang="ts" setup>
  import {
    fileTemplateAdd,
    fileTemplateUpdate,
    getFileTemplateDetail,
  } from '@/api/file/fileTemplate';
  import { onMounted, reactive, ref } from 'vue';
  import { useMessage } from 'naive-ui';
  import { useModal } from '@/components/Modal';
  import UploadFile from '@/components/Upload/file.vue';

  const emit = defineEmits(['success', 'update:visible']);
  const formRef = ref();

  /**
   * 定义表单参数
   */
  const message = useMessage();
  const formData = reactive({
    id: '',
    name: '',
    code: '',
    filePath: '',
    fileName: '',
  });

  /**
   * 定义接收的参数
   */
  const props = defineProps({
    visible: {
      type: Boolean,
      required: true,
      default: false,
    },
    fileId: {
      type: Number,
      required: true,
      default: 0,
    },
  });

  /**
   * 定义模态
   */
  const [modalRegister, { openModal, setSubLoading }] = useModal({
    title: props.fileId ? '编辑文件模板' : '添加文件模板',
    subBtuText: '确定',
    width: 600,
  });

  /**
   *上传文件
   * @param filePath 文件路径
   * @param fileName 文件名称
   */
  const fileUpload = async (filePath: any, fileName: any) => {
    formData.filePath = filePath;
    formData.fileName = fileName;
    formRef.value?.validate(
      (errors) => {},
      (rule) => {
        return rule?.key === 'filePath';
      },
    );
    return;
  };

  /**
   * 执行提交
   */
  const handleSubmit = async () => {
    formRef.value
      .validate()
      .then(async () => {
        props.fileId ? await fileTemplateUpdate(formData) : await fileTemplateAdd(formData);
        message.success('操作成功');
        setSubLoading(false);
        emit('update:visible', false);
        emit('success');
      })
      .catch((error) => {
        setSubLoading(false);
      });
  };

  /**
   * 关闭窗体
   */
  const handleClose = () => {
    emit('update:visible', false);
  };

  /**
   * 设置表单数据
   */
  const setFormData = async () => {
    const data = await getFileTemplateDetail(props.fileId);
    for (const key in formData) {
      if (data[key] != null && data[key] != undefined) {
        //@ts-ignore
        formData[key] = data[key];
      }
    }
  };

  /**
   * 钩子函数
   */
  onMounted(() => {
    if (props.fileId) {
      setFormData();
    }
  });

  /**
   * 定义函数
   */
  defineExpose({
    openModal,
  });
</script>
