<!-- https://github.com/SheetJS/js-xlsx -->
<template>
  <el-upload
    v-bind="uploadprops"
  >
    <slot>
      <el-button type="primary" size="mini">导入</el-button>
    </slot>
  </el-upload>
</template>
<script>
import XLSX from 'xlsx'

export default {
  name: 'ThImportExcel',
  props: {
    // 列
    columns: {
      type: Array,
      default: () => []
    },
    // 文件类型限制
    type: {
      type: Array,
      default: () => []
    },
    // 文件大小限制
    size: {
      type: Number,
      default: 0
    },
    // 文件大小单位，mb || kb(默认)
    unit: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      dataSource: [],
      loading: false,
      file: null,
      percentage: 0,
      uploadprops: {
        ref: 'upload',
        class: 'th-import-excel',
        action: '',
        accept: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel',
        autoUpload: false,
        showFileList: false,
        beforeUpload: this.beforeUpload,
        onChange: this.onChange
      }
    }
  },
  methods: {
    // 上传到页面前进行检查
    beforeUpload(file) {
      // 判断文件类型 windows下accept无效
      let checkType = true
      var i = file.name.lastIndexOf('.')
      var suffix = file.name.substring(i + 1)
      if (this.type.length) {
        checkType = this.type.includes(suffix)
      }

      // 判断文件大小
      let checkSize = true
      if (this.size > 0) {
        const allowSize = this.unit.toLowerCase() === 'mb' ? (1024 * 1024) : 1024
        checkSize = file.size / allowSize < Number(this.size)
      }
      // 提示错误信息
      if (!checkType) {
        this.$message.error(`上传文件只能是 ${this.type.join(',')} 格式!`)
      }
      if (!checkSize) {
        this.$message.error(`上传文件大小不能超过 ${this.size}${this.unit || 'KB'}!`)
      }
      return checkType && checkSize
    },
    // 上传-选择文件
    onChange(file, fileList) {
      if (this.beforeUpload(file)) {
        const that = this
        const rABS = true
        const reader = new FileReader()
        reader.onload = function(e) {
          // 以二进制流方式读取得到整份excel表格对象
          let data = e.target.result
          if (!rABS) data = new Uint8Array(data)
          const workbook = XLSX.read(data, {
            type: rABS ? 'binary' : 'array'
          })
          // 取第一个标签页数据
          var ws = workbook.Sheets[workbook.SheetNames[0]]
          var jsonArr = XLSX.utils.sheet_to_json(ws, { header: 1 })
          that.handleExcelData(jsonArr)
        }
        if (rABS) {
          reader.readAsBinaryString(file.raw)
        } else {
          reader.readAsArrayBuffer(file.raw)
        }
      }
    },
    // 处理、转换表格数据
    handleExcelData(data) {
      this.dataSource = data
      this.$emit('ochange', data)
    }
  }
}
</script>
