<template>
  <a href="javascript:;" class="file">
    <slot></slot>
    {{ file && file.name ? file.name : "选择文件" }}
    <input
      ref="referenceUpload"
      id="fileSelect"
      type="file"
      accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
      runat="server"
      @change="upload"
    />
  </a>
</template>

<script>
import * as XLSX from "xlsx";
export default {
  name: "BatchUpload",
  data() {
    return {
      file: null,
    };
  },
  methods: {
    upload(e) {
      // 若出现files赋值未知错误值或照片长度不对则return
      if (!e.target.files || e.target.files.length < 1) {
        return;
      }
      this.file = e.target.files[0];
      this.getJsonList(this.file);
    },
    doUpload(photoList) {
      this.$emit("getFileList", photoList);
      this.$refs.referenceUpload.value = null;
    },
    // 处理excel文件的内容
    getJsonList(file) {
      const reader = new FileReader();
      const photoList = {
        correct: [],
        incorrect: [],
      };
      reader.readAsBinaryString(file);
      reader.onload = (e) => {
        // 获取传递的表格
        const binaryString = e.target.result;
        // 以二进制流方式读取到整份的excel 表格对象
        const workbook = XLSX.read(binaryString, {
          type: "binary",
          sheetRows: 0,
          codepage: 936,
        });
        let data = [];
        // 遍历每张表读取
        for (const sheet in workbook.Sheets) {
          data = data.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]));
        }
        photoList["correct"] = data;
        this.doUpload(photoList);
      };
    },
    clearFile() {
      this.file = null;
    },
  },
};
</script>

<style scoped>
/*批量导入按钮*/
.file {
  position: relative;
  background: #d0eeff;
  border: 1px solid #99d3f5;
  border-radius: 4px;
  padding: 10px 20px;
  box-sizing: border-box;
  overflow: hidden;
  color: #1e88c7;
  text-decoration: none;
  text-indent: 0;
}
.file input {
  position: absolute;
  font-size: 14px;
  width: 100%;
  height: 40px;
  left: 0;
  top: 0;
  opacity: 0;
  cursor: pointer;
}
.file:hover {
  background: #aadffd;
  border-color: #78c3f3;
  color: #004974;
  text-decoration: none;
}
.el-button {
  margin-left: 20px;
}
</style>
