<template>
  <el-dialog v-model="visible" :title="title" :before-close="fnClose">
    <el-form ref="formRef" :model="form" :rules="rules" :label-width="labelWidth">
      <slot :form="form"></slot>
      <el-form-item label="附件" prop="file">
        <app-upload v-model="form.file" accept=".xls,.xlsx" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button v-if="templateUrl" @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 { ref } from "vue";
import { debounce } from "throttle-debounce";
import { useVModel } from "@vueuse/core";
import { ElDialog, ElForm, ElFormItem, ElButton, ElMessageBox } from "element-plus";
import "element-plus/es/components/dialog/style/css";
import "element-plus/es/components/form/style/css";
import "element-plus/es/components/form-item/style/css";
import "element-plus/es/components/button/style/css";
import AppUpload from "../upload/index.vue";
import useForm from "../../hooks/useForm/index.js";
import { getFileUrl } from "../../utils/index.js";

defineOptions({
  name: "AppImportFile",
});
const props = defineProps({
  labelWidth: { type: String, default: "80px" },
  title: { type: String, default: "导入" },
  templateUrl: { type: String, default: "" },
  customForm: { type: Boolean, default: false },
  form: { type: Object, default: () => ({ file: [] }) },
  rules: {
    type: Object,
    default: () => ({
      file: [{ required: true, message: "附件不能为空", trigger: "change" }],
    }),
  },
});
const emits = defineEmits(["submit", "update:form"]);
const visible = defineModel("visible", { type: Boolean, required: true });
const form = props.customForm
  ? useVModel(props, "form", emits)
  : ref({ file: [] });
const { formRef, validate, reset } = useForm();
const fnExportTemplates = async () => {
  await ElMessageBox.confirm("确定要下载excel模板吗？", { type: "warning" });
  window.open(getFileUrl() + props.templateUrl);
};
const fnClose = () => {
  reset();
  visible.value = false;
};
const fnSubmit = debounce(
  1000,
  async () => {
    await validate();
    emits("submit", form.value);
    reset();
  },
  { atBegin: true }
);
</script>

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