<template>
  <el-upload action="#" class="upload" drag :before-upload="beforeUpload">
    <i class="el-icon-upload"></i>
    <div class="el-upload__text">
      将文件拖到此处，或
      <em>点击上传</em>
    </div>
    <div class="el-upload__tip" slot="tip">
      <span>请上传 .xls,.xlsx 标准格式文件 </span>
      <span class="redFont"> 最多可上传1000条Excel数据</span>
      </div>
  </el-upload>
</template>

<script>
import { isExcel } from "@/util/validate";
import XLSX from "xlsx";

function fixdata(data) {
  let o = "";
  let l = 0;
  let w = 10240;
  for (; l < data.byteLength / w; ++l) {
    o += String.fromCharCode.apply(
      null,
      new Uint8Array(data.slice(l * w, l * w + w))
    );
  }
  o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w)));
  return o;
}

export default {
  props: { success: Function },
  methods: {
    beforeUpload(file) {
      if (!isExcel(file)) {
        this.$message.error("上传参保信息只能是 .xls,.xlsx 标准格式文件!");
        return;
      }
      let reader = new FileReader();
      let self = this;
      reader.onload = function(e) {
        var data = e.target.result;
        var wb = XLSX.read(btoa(fixdata(data)), {
          type: "base64"
        });
        var questions = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
        self.success(questions);
      };
      reader.readAsArrayBuffer(file);
      return false;
    }
  }
};
</script>

<style scoped>
.upload {
  display: inline-block;
}
.redFont{
  color:#ff0000;
}
</style>
