<template>
  <el-dialog v-model="props.visible" :title="dialogTitle" width="450" :close-on-click-modal="false"
    :before-close="dialogClose">
          <el-upload
          style="width:400px"
            drag
            ref="upload"
            action="/api/user/import"
            :headers="uploadHeaders"
            :on-error="onError"
            :on-success="onSuccess"
            :before-upload="beforeUpload"
            :show-file-list="false"
            :limit="1"
            v-perm="['sys:user:import']"
          >
          <el-icon class="el-icon--upload" style="color:#165DFF;"><upload-filled /></el-icon>
          <div class="el-upload__text">
            点击或将文件拖拽到这里上传
          </div>
          </el-upload> 
      <div style="margin-top:20px;">
        <span>只能上传 xls、xlsx 文件,</span>
        <el-button type="primary" link @click="handleDownload">下载模板
        </el-button>
      </div>

  </el-dialog>
</template>

<script lang="ts" setup>
  import { getTemplateByCode } from '@/api/system/user';
import { computed,shallowRef,ref,reactive  } from "vue";
import {  UploadInstance } from 'element-plus';
import { FormInstance } from "element-plus";
import { message,loading,closeLoading } from "@/utils/auth";
const formRef = shallowRef<FormInstance>();

import { useUserStore } from '@/store/modules/user';

const props = defineProps({
  visible: {
    type: Boolean,
    required: true,
    default: false
  },
  id: {
    type: Number,
    required: true,
    default: 0
  }
});
const upload = ref<UploadInstance>();
const uploadHeaders = reactive({
    authorization:useUserStore().getToken
  });
const emit = defineEmits(["success", "update:visible"]);

const dialogTitle = computed(() => {
  return '导入用户';
});


const dialogClose = () => {
  emit("update:visible", false);
};

const beforeUpload = (file: UploadFile) => {
  const isLt2M = file.size / 1024 / 1024 < 200;
  if (!isLt2M) {
    message("大小不能超过200MB!", "error");
    return false;
  }
  if (!/\.(xlsx|xls|XLSX|XLS)$/.test(file.name)) {
    message("请上传.xlsx .xls", "error");
    return false;
  }
  loading("上传中");
  return true;
};
const onSuccess = (file: UploadFile) => {
  upload.value!.clearFiles();
  closeLoading();
  if (file.code == 0) {
    message("导入成功");
    emit("update:visible", false);
    emit("success");
  } else {
    message(file.msg ? file.msg : "导入失败", "error");
  }
};
const onError = () => {
  upload.value!.clearFiles();
  closeLoading();
  message("导入失败", "error");
};
const handleDownload = async()=>{
  const res =await getTemplateByCode('user_import')
  window.open(res.filePath)
}


</script>
