<template>
  <div style="display: inline-block;width: 100%;height: 100%;margin-top: 5px">
    <input
      id="excel-upload-input"
      ref="excel-upload-input"
      accept=".xlsx, .xls"
      class="c-hide"
      type="file"
      @change="handkeFileChange">
    <div id="drop" @dragenter="handleDragover" @dragover="handleDragover" @drop="handleDrop">
      将Excel文件拖到这或
      <el-button
        icon="el-icon-search"
        plain
        size="small"
        style="margin-left:16px;"
        type="primary"
        @click="handleUpload">浏览
      </el-button>
      <template v-if="templateFileName">
        <a
          :href="templateDownloadUrl"
          style="margin-left: 20px; color: #409EFF; text-decoration: underline; font-size: 14px;"
          :download="templateFileName"
          target="_blank"
        >下载模板</a>
      </template>
    </div>
  </div>
</template>

<script>
import XLSX from 'xlsx'

export default {
  props: {
    templateFileName: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      loading: false,
      excelData: {
        itemFile: [],
        worksheet: []
      },
      sheetNames: []
    }
  },
  computed: {
    templateDownloadUrl() {
      // 兼容开发和生产环境，static为public目录
      return this.templateFileName ? `/static/template/${this.templateFileName}` : ''
    }
  },
  methods: {
    generateDate({ itemFile, worksheet }) {
      this.excelData.itemFile = [itemFile]
      this.excelData.worksheet = [worksheet]
    },
    handleDrop(e) {
      this.excelData.itemFile = []
      this.excelData.worksheet = []
      e.stopPropagation()
      e.preventDefault()
      const files = e.dataTransfer.files
      if (files.length > 1) {
        this.$message.error('只能选择一个Excel文件！')
        return
      }
      if (files.length === 1) {
        const itemFile = files[0]
        this.readerData(itemFile)
      }
      e.stopPropagation()
      e.preventDefault()
    },
    handleDragover(e) {
      e.stopPropagation()
      e.preventDefault()
      e.dataTransfer.dropEffect = 'copy'
    },
    handleUpload() {
      this.excelData.itemFile = []
      this.excelData.worksheet = []
      document.getElementById('excel-upload-input').click()
    },
    handkeFileChange(e) {
      const files = e.target.files
      if (files.length > 1) {
        this.$message.error('只能选择一个Excel文件！')
        this.$refs['excel-upload-input'].value = null
        return
      }
      if (files.length === 1) {
        const itemFile = files[0]
        if (!itemFile) return
        this.readerData(itemFile)
      }
      this.$refs['excel-upload-input'].value = null
    },
    readerData(itemFile) {
      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' })
        this.sheetNames = workbook.SheetNames
        this.excelData.itemFile = [itemFile]
        this.excelData.worksheet = []
        for (const item of workbook.SheetNames) {
          const worksheet = workbook.Sheets[item]
          this.excelData.worksheet.push(worksheet)
        }
        this.$emit('on-selected-file', {
          itemFile: [itemFile],
          worksheet: this.excelData.worksheet,
          sheetNames: workbook.SheetNames
        })
      }
      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
    }
  }
}
</script>

<style scoped>
#excel-upload-input {
  display: none;
  z-index: -9999;
}

#drop {
  border: 2px dashed #bbb;
  width: 100%;
  min-width: 400px;
  max-width: 700px;
  line-height: 160px;
  margin: 0 auto;
  font-size: 24px;
  border-radius: 5px;
  text-align: center;
  color: #bbb;
  position: relative;
  box-sizing: border-box;
}
</style>
