<template>
  <div>
    <vue-office-excel ref="a" v-if="+type === 0" v-bind="$attrs" :src="src" @error="$emit('error', $event)" @rendered="handleRendered"/>
  </div>
</template>

<script>
import * as Excel from 'exceljs/dist/exceljs'
// 引入VueOfficeExcel组件
import VueOfficeExcel from '@vue-office/excel'
// 引入相关样式
import '@vue-office/excel/lib/index.css'

const workbook = new Excel.Workbook()

export default {
  name: 'file-review',
  components: {
    VueOfficeExcel
  },
  props: {
    // 预览类型 0: Excel
    type: {
      type: [Number, String],
      default: 0
    },
    src: {
      type: [String, File, ArrayBuffer],
      default: ''
    }
  },
  data () {
    return {
      worksheet: null,
      rendered: 0
    }
  },
  watch: {
    src: {
      async handler (val) {
        await workbook.xlsx.load(val)
        this.worksheet = workbook.worksheets[0]
        this.handleRendered()
      },
      deep: true,
      immediate: true
    }
  },
  mounted () {
    this.$nextTick(() => {
      const _bottom = this.$refs.a.rootRef.childNodes[0].childNodes[3]
      const _ul = _bottom.childNodes[1]
      _ul.addEventListener('click', (evt) => {
        if (evt.target.localName === 'ul') {
          return
        }
        this.worksheet = workbook.getWorksheet(evt.target.innerText)
        this.$emit('click:bottom-bar', evt.target.innerText)
      })
    })
  },
  methods: {
    handleRendered () {
      this.rendered++
      if (this.rendered >= 2) {
        this.$emit('rendered')
        this.rendered = 0
      }
    },
    getRow (index) {
      const row = this.worksheet.getRow(index + 1)
      let _merges = 0
      const text = []
      row.eachCell((cell, colNumber) => {
        if (cell._mergeCount) {
          _merges = cell._mergeCount + colNumber
        }
        if (_merges > colNumber) {
          return
        }
        _merges = 0
        if (typeof cell.value === 'object' && cell.value !== null) {
          text.push(cell.value.text || cell.value.result || '格式异常')
          return
        }
        text.push(cell.value)
      })
      return text
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
