<template>
  <div>
    <input id="excel-upload-input" :ref="'excel-upload-input'+currentIndex" type="file" accept=".xlsx, .xls, .csv" class="c-hide excel-upload-input" @change="handkeFileChange">
    <div id="drop">
      <el-button style="margin-left:16px;" size="mini" type="text" @click="handleUpload"><span class="p-r-8">点击导入会员</span><span class="p-l-8 border-l-dcdfe6 color-e55858" v-if="!!failedData.length" @click="handleDownload">下载失败会员清单</span></el-button>
      <div class="excel-upload__tip">只能上传一个excle文件（2003版本以上），且数据不超过5000条</div>
    </div>
  </div>
</template>

<script>
import XLSX from 'xlsx'

export default {
  props:{
    currentIndex: {
      type: [String,Number]
    },
    excelBodyData: Array,
    excelHeader: Array,
    failHead: {
      type: Array,
      default: function () {
        return []
      }
    },
    failData: {
      type: Array,
      default: function () {
        return []
      }
    }
  },
  data() {
    return {
      loading: false,
      useIndex: null,
      excelData: {
        header: null,
        results: null,
        name: null
      },
      failedData: []
    }
  },
  methods: {
    generateDate({ header, results, fileName }) {
      this.excelData.header = header;
      this.excelData.results = results;
      this.excelData.name = fileName;
      console.log(this.useIndex)
      this.$emit('on-selected-file', this.excelData);
      this.$emit('selectIndex', this.useIndex);
    },
    handleDrop(e) {
      e.stopPropagation()
      e.preventDefault()
      const files = e.dataTransfer.files
      if (files.length !== 1) {
        this.$message.error('Only support uploading one file!')
        return
      }
      const itemFile = files[0] // only use files[0]
      this.readerData(itemFile)
      e.stopPropagation()
      e.preventDefault()
    },
    handleDragover(e) {
      e.stopPropagation()
      e.preventDefault()
      e.dataTransfer.dropEffect = 'copy'
    },
    handleUpload() {
      var that = this
      console.log(this.excelData,this.excelData.header,this.currentIndex)
      if (!!that.excelHeader&&!!that.excelHeader.length) {

        that.$confirm('目前操作没有结束，点击其他导入现有数据不会保存，\n 确认要离开吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }).then(() => {
          // 先清空原有数据
          that.$emit('clearOldData',that.currentIndex)
          document.getElementsByClassName('excel-upload-input')[that.useIndex].click()
        }).catch(() => {

        });
        return false;
      }

      document.getElementsByClassName('excel-upload-input')[that.useIndex].click()

    },
    handkeFileChange(e) {
      const files = e.target.files
      const itemFile = files[0] // only use files[0]
      if (!itemFile) return
        console.log(itemFile.name)
      this.readerData(itemFile)
      this.$refs['excel-upload-input'+this.currentIndex].value = null // fix can't select the same excel
    },
    readerData(itemFile) {
      var that = this;
      console.log(itemFile.name)
      var fileName = itemFile.name;
      const reader = new FileReader()
      reader.onload = e => {
        const data = e.target.result
        const fixedData = this.fixdata(data)

        const workbook = XLSX.read(btoa(fixedData), { type: 'base64' })
        const firstSheetName = workbook.SheetNames[0]
        const worksheet = workbook.Sheets[firstSheetName]
        // console.log(Object.keys(worksheet).indexOf('!ref'),typeof(worksheet))
        if (Object.keys(worksheet).indexOf('!ref') == -1) {
          that.$message.error({
            duration: 1000,
            message: "文档内容为空"
          })
          return false;
        }
        const header = this.get_header_row(worksheet)
        const results = XLSX.utils.sheet_to_json(worksheet)
        this.generateDate({ header, results, fileName })
      }
      reader.readAsArrayBuffer(itemFile)
    },
    fixdata(data) {
      let o = ''
      let l = 0
      const 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
    },
    get_header_row(sheet) {
      const headers = []
      const range = XLSX.utils.decode_range(sheet['!ref'])
      let C
      const R = range.s.r /* start in the first row */
      for (C = range.s.c; C <= range.e.c; ++C) { /* walk every column in the range */
        var cell = sheet[XLSX.utils.encode_cell({ c: C, r: R })] /* find the cell in the first row */
        var hdr = 'UNKNOWN ' + C // <-- replace with your desired default
        if (cell && cell.t) hdr = XLSX.utils.format_cell(cell)
        headers.push(hdr)
      }
      return headers
    },

    /**
     * 导出 excel
     */
    handleDownload() {
      const that = this

      require.ensure([], () => {
          const { export_json_to_excel } = require('@/vendor/Export2Excel')
          const tHeader = ['phoneNum']
          const filterVal = ['phoneNum']
          const list = that.currentExcelData;
          if (!list.length) {
            that.$message.error({
              duration: 1000,
              message: "数据为空"
            })
            return false;
          }
          const data = that.formatJson(filterVal, list)
          console.log(data)
          export_json_to_excel(tHeader, data, '导出列表');

        })
    },

    formatJson(filterVal, jsonData) {
        return jsonData.map(v => filterVal.map(j => v[j]))
    },
  },
  watch: {
    currentIndex: function(newdata,oldData){
      console.log("watch:",newdata)
      this.useIndex = newdata
    },
    failData: function(newdata,oldData){
      console.log("watch:",newdata)
      this.failedData = newdata
    },
  },
  mounted() {
    console.log(this.currentIndex,this.failData)
    this.useIndex = this.currentIndex
    this.failedData = this.failData
  }
}
</script>

<style scoped>
#excel-upload-input{
  display: none;
  z-index: -9999;
}
#drop{
  /*border: 2px dashed #bbb;
  width: 600px;
  height: 160px;
  line-height: 160px;*/
  margin: 0 auto;
  /*font-size: 24px;*/
  /*border-radius: 5px;*/
  /*text-align: center;*/
  /*color: #bbb;*/
  position: relative;


}

.excel-upload__tip {
  margin-left: 16px;
  font-size: 12px;
  color: #909399;
}

.color-e55858 {
  color: #e55858;
}
</style>
