<template>
  <el-dialog v-model="dialogVisible" title="批量添加" :destroy-on-close="true" width="580px" draggable top="1vh">
    <el-form label-width="120px">
      <el-form-item label="模板下载：">
        <el-button type="primary" @click="downloadFile">
          <el-icon color="#fff">
            <Download />
          </el-icon> 模板下载
        </el-button>
      </el-form-item>
      <el-form-item label="文件上传：">
        <el-upload class="upload" drag :action="uploadUrl" :on-success="excelUploadSuccess" :on-error="excelUploadError"  :before-upload="beforeExcelUpload">
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">
            将文件拖到此处，或<em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              请按模板上传文件
            </div>
          </template>
        </el-upload>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref } from "vue";
import type {UploadRawFile } from 'element-plus'

let props = defineProps({
  templateName: {
    type: String,
    default: '',
  },
  uploadUrl: String
})

const dialogVisible = ref(false)

// 下载模板
const downloadFile = () => {
  if (props.templateName === '') {
    return ElMessage({ type: 'error', message: '未配置模板下载路径' })
  }

  let dom = document.createElement("a");
  dom.style.display = 'none'
  dom.target = '_blank'
  dom.href = `./templete/${props.templateName}`
  document.body.appendChild(dom);
  dom.click();
  document.body.removeChild(dom);
}

/**
 * @description 文件上传之前判断
 * @param file 上传的文件
 * */
const beforeExcelUpload = (file: UploadRawFile) => {
  const suffix = file.name.split('.').pop()
  const isExcel = ['xls', 'xlsx'].includes(suffix);
  if (!isExcel)
  ElMessage({type: 'warning',message: '上传文件只能是 xls / xlsx 格式' })

  // const fileSize = file.size
  // if (!fileSize)
  //   setTimeout(() => {
  //     ElNotification({
  //       title: "温馨提示",
  //       message: `上传文件大小不能超过 ${parameter.value.fileSize}MB！`,
  //       type: "warning"
  //     });
  //   }, 0);
  return isExcel;
};

const emit = defineEmits(['success'])
const excelUploadSuccess = (response: any) => {
  emit('success', response)
}

// 上传错误提示
const excelUploadError = () => {
  ElMessage({
    title: "温馨提示",
    message: `批量添加失败，请您重新上传！`,
    type: "error"
  });
};

defineExpose({
  dialogVisible
});
</script>
<style lang="scss" scoped>
.upload {
  width: 80%;
}
</style>
