<template>
  <el-dialog title="批量创建" v-model="dialogVisible" width="500px" destroy-on-close :close-on-click-modal="false">
    <el-upload :headers="HEADERS" :on-success="handleSuccess" :on-error="handleError" :before-upload="beforeUpload" class="upload-demo" drag :action="ACTION">
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text"><em>点击</em>或将文件拖拽到这里上传</div>
      <template #tip>
        <div class="tip-text">
          <div class="el-upload__tip">只能上传excel文件，且不超过500KB</div>
          <div class="down el-upload__tip" @click="dowdDemo">下载导入模板</div>
        </div>
      </template>
    </el-upload>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogVisible = false"> 确定 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { ElMessage } from "element-plus";
import { useCommonStore } from "@/store/common";
import { exportDemoAccount } from "@/api/index";
interface Tdata {
  code: number;
  data: {
    errMsg: string;
    errorCount: number;
  };
  msg: string;
}

const comm = useCommonStore();
const ACTION = import.meta.env.VITE_APP_URL + "/v1/api/upload/account";
const HEADERS = {
  "Access-Token": comm.user.token,
};
const dialogVisible = ref(false);
defineExpose({ dialogVisible });
const emit = defineEmits(["success"]);

const handleSuccess = ({ code, data, msg }: Tdata) => {
  if (code != 200) return ElMessage.error(msg);
  if (data.errorCount > 0) return ElMessage.error({ message: data.errMsg, dangerouslyUseHTMLString: true });
  ElMessage.success("用户导入成功");
  emit("success");
};

const handleError = ({ msg }: { msg: string }) => {
  ElMessage.error(msg);
};
const beforeUpload = (rawFile: any) => {
  if (rawFile.size / 1024 > 500) {
    ElMessage.error("文件大小不能超过500KB");
    return false;
  }
  if (rawFile.name.indexOf(".xlsx") === -1 && rawFile.name.indexOf(".xls‌") === -1) {
    ElMessage.error("只能上传excel文件");
    return false;
  }
  dialogVisible.value = false;
};
const dowdDemo = async () => {
  try {
    const response = await exportDemoAccount();
    const blob = new Blob([response], { type: "application/vnd.ms-excel" });
    const link = document.createElement("a");
    link.href = window.URL.createObjectURL(blob);
    link.download = "批量创建用户模板.xlsx";
    link.click();
    window.URL.revokeObjectURL(link.href);
    ElMessage.success("模板下载成功");
  } catch (error) {
    ElMessage.error("模板下载失败");
  }
};
</script>

<style scoped lang="less">
.tip-text {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 10px;
}
.down {
  cursor: pointer;
  text-decoration: underline;
  color: #409eff;
}
/deep/ .el-upload-list {
  display: none;
}
</style>
