<template>
  <el-dialog
    v-model="dialog.visible"
    :title="dialog.title"
    width="500px"
    @close="closeDialog"
  >
    <el-form :model="importData" label-width="100px">
      <el-form-item label="Excel文件">
        <el-upload
          ref="uploadRef"
          action=""
          drag
          accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
          :limit="1"
          :auto-upload="false"
          :file-list="importData.fileList"
          :on-change="handleFileChange"
          :on-exceed="handleFileExceed"
        >
          <el-icon class="el-icon--upload">
            <i-ep-upload-filled />
          </el-icon>
          <div class="el-upload__text">
            将文件拖到此处，或
            <em>点击上传</em>
          </div>
          <template #tip>
            <div style="color: red">文件类型: xls/xlsx</div>
          </template>
        </el-upload>
      </el-form-item>
    </el-form>
    <!-- 弹窗底部操作按钮 -->
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { UploadInstance, genFileId } from "element-plus";
import request from "@/utils/request";

// 弹窗对象
const dialog = reactive({
  visible: false,
  type: "obj-import",
  width: 800,
  title: "",
});

const uploadUrl = ref("");
const uploadRef = ref<UploadInstance>(); // 上传组件
// 导入数据
const importData = reactive({
  file: undefined,
  fileList: [],
});

const uploadEmits = defineEmits(["finished"]);

/**
 * 传入url和title
 */
const show = (url: string, title: string) => {
  dialog.title = title;
  dialog.visible = true;
  uploadUrl.value = url;
  if (dialog.type === "obj-import") {
    // 导入弹窗
    dialog.title = "数据导入";
    dialog.width = 600;
  }
};
const closeDialog = () => {
  dialog.visible = false;
  if (dialog.type === "obj-import") {
    importData.file = undefined;
    importData.fileList = [];
  }
};

/** 弹窗提交 */
const handleSubmit = async () => {
  let data: any = await request({
    url: uploadUrl.value,
    method: "post",
    data: importData,
    headers: {
      "Content-Type": "multipart/form-data",
    },
  });
  ElMessage({
    message: data.msg,
    type: "success",
  });
  dialog.visible = false;
  uploadUrl.value = "";
  uploadEmits("finished");
};

/** Excel文件 Change */
const handleFileChange = (file: any) => {
  importData.file = file.raw;
};
/** Excel文件 Exceed  */
const handleFileExceed = (files) => {
  uploadRef.value!.clearFiles();
  const file = files[0];
  file.uid = genFileId();
  uploadRef.value!.handleStart(file);
  importData.file = file;
};

defineExpose({ show });
</script>

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