<template>
  <el-dialog v-model="visible" :title="title" :before-close="fnClose">
    <el-form ref="formRef" :model="data.form" :rules="rules" label-width="80px">
      <el-form-item label="附件" prop="file">
        <layout-upload v-model:file-list="data.form.file" accept=".xls" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="fnExportTemplates">导出模板</el-button>
      <el-button type="primary" @click="fnSubmit">确定</el-button>
      <el-button @click="fnClose">取消</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import LayoutUpload from "@/components/upload/index.vue";
import { useVModel } from "@vueuse/core";
import { ElMessageBox } from "element-plus";
import { reactive, ref, watchEffect } from "vue";
import { debounce } from "throttle-debounce";
import useFormValidate from "@/assets/js/useFormValidate.js";

const VITE_TEMPLATE_URL = import.meta.env.VITE_TEMPLATE_URL;
defineOptions({
  name: "LayoutImportFile",
});
const props = defineProps({
  visible: {
    type: Boolean,
    required: true,
    default: false,
  },
  title: {
    type: String,
    default: "导入",
  },
  templateUrl: {
    type: String,
    required: true,
    default: "",
  },
});
const emits = defineEmits(["update:visible", "submit"]);
const visible = useVModel(props, "visible", emits);
const rules = {
  file: [{ required: true, message: "附件不能为空", trigger: "change" }],
};
const formRef = ref(null);
const data = reactive({
  form: {
    file: [],
  },
});
const fnExportTemplates = async () => {
  await ElMessageBox.confirm("确定要下载excel模板吗？", { type: "warning" });
  window.open(VITE_TEMPLATE_URL + props.templateUrl);
};
watchEffect(() => {
  if (!props.visible) {
    formRef.value && formRef.value.resetFields();
  }
});
const fnClose = () => {
  formRef.value.resetFields();
  visible.value = false;
};
const fnSubmit = debounce(
  1000,
  async () => {
    await useFormValidate(formRef, "请上传附件");
    const formData = new FormData();
    formData.append("FFILE", data.form.file[0].raw);
    formData.append("FFILEName", data.form.file[0].name);
    emits("submit", formData);
  },
  { atBegin: true }
);
</script>

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