<template>
  <div>
    <el-upload
      class="upload-demo"
      ref="upload"
      drag
      action="#"
      :auto-upload="false"
      :on-change="handleExcelChange"
      multiple
    >
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <div class="el-upload__tip" slot="tip">只能上传xls/xlsx文件</div>
    </el-upload>

    <el-button type="primary" @click="emitData" style="margin-top: 10px;"
      >确认</el-button
    >
  </div>
</template>

<script>
export default {
  name: "ReadExcel",
  data() {
    return {
      excelData: undefined,
      fileList: undefined
    };
  },
  created() {},
  methods: {
    handleExcelChange(file, fileList) {
      console.log(file);
      let _this = this;
      let inputDOM = this.$refs.inputer;
      // 通过DOM取文件数据

      this.file = event.currentTarget.files[0];

      var rABS = false; //是否将文件读取为二进制字符串
      var f = this.file;

      var reader = new FileReader();
      //if (!FileReader.prototype.readAsBinaryString) {
      FileReader.prototype.readAsBinaryString = function(f) {
        var binary = "";
        var rABS = false; //是否将文件读取为二进制字符串
        var pt = this;
        var wb; //读取完成的数据
        var outdata;
        var reader = new FileReader();
        reader.onload = function(e) {
          var bytes = new Uint8Array(reader.result);
          var length = bytes.byteLength;
          for (var i = 0; i < length; i++) {
            binary += String.fromCharCode(bytes[i]);
          }
          var XLSX = require("xlsx");
          if (rABS) {
            wb = XLSX.read(btoa(fixdata(binary)), {
              //手动转化
              type: "base64"
            });
          } else {
            wb = XLSX.read(binary, {
              type: "binary"
            });
          }
          outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]); //outdata就是你想要的东西
          _this.excelData = outdata;
        };
        reader.readAsArrayBuffer(f);
      };
      if (rABS) {
        reader.readAsArrayBuffer(f);
      } else {
        reader.readAsBinaryString(f);
      }
    },
    emitData() {
      let excelData = this.excelData;
      // let keys = [];
      // let total = [];

      let obj = {
        avatar:
          "http://rangtang-1.oss-cn-chengdu.aliyuncs.com/ce1e99bf-40df-49cd-a77f-05849b662859.png",
        description: "zz",
        descriptionZ: "zzzw",
        duty: "zw",
        dutyZ: "zwzw",
        idCard: "510105198807190533",
        idCardAddress: "32323",
        isConvenience: true,
        isConvenienceLeader: false,
        isNews: false,
        isNewsLeader: false,
        isResidentsAdministrator: [],
        name: "abc",
        nameZ: "bbc",
        permanentResidenceRegion: "壤塘县",
        permanentResidenceTown: "石里乡",
        permanentResidenceTownShip: "阿斗村",
        phone: "13408085719",
        sex: 1,
        sort: "1"
      };
      let residentList = [];
      excelData.map(item => {
        let resident = {
          avatar: item["头像"],
          description: item["职责"],
          descriptionZ: item["职责（藏文）"],
          duty: item["职务"],
          dutyZ: item["职务（藏文）"],
          idCard: item["身份证号"],
          idCardAddress: item["身份证地址"],
          isConvenience: item["是否是便民工作人员"] === "是" ? true : false,
          isConvenienceLeader: item["是否是便民领导"] === "是" ? true : false,
          isNews: false,
          isNewsLeader: false,
          isResidentsAdministrator: [],
          name: item["姓名"],
          nameZ: item["姓名（藏文）"],
          permanentResidenceRegion: item["县"],
          permanentResidenceTown: item["乡镇"],
          permanentResidenceTownShip: item["村"],
          phone: item["手机号"],
          sex: item["性别"] === "女" ? 0 : item["性别"] === "男" ? 1 : 2,
          sort: item["序号"]
        };
        residentList.push(resident);
        // keys.push(item["手机号"]);
        // total.push(item["数量"]);
      });
      // const payload = {
      //   // batchId: this.$route.query.id,
      //   keys,
      //   total
      // };
      // console.log(residentList);
      this.$emit("listenToChildEvent", residentList);
    },
    clearFileList() {
      this.excelData = undefined;
      this.$refs.upload.clearFiles();
    }
  }
};
</script>

<style scoped></style>
