<template>
  <div>
    <Form :label-width="80"
          style="width:360px;background:#fff;padding:20px 16px;z-index:999;">
      <FormItem label="文件名"
                style="width:320px">
        <Input v-model="exportTitle"></Input>
      </FormItem>
      <FormItem style="margin-top:0px;"
                label="导出数据">
        <RadioGroup v-model="dataSrc">
          <Radio label="all">所有数据</Radio>
          <Radio label="checked">已选择数据</Radio>

        </RadioGroup>
      </FormItem>
    </Form>
    <div style="display:none;">
      <vxe-table border
                 :auto-resize="true"
                 :span-method="vucTable.spanMethod"
                 :footer-method="vucTable.footerMethod"
                 :footer-span-method="vucTable.footerSpanMethod"
                 :show-footer="true"
                 :height="1000"
                 ref="pageGrid">
      </vxe-table>
    </div>
    <div class="action-group">
      <Button type="primary"
              @click="doExport">导出</Button>
    </div>
  </div>
</template>

<script>
import XLSX from 'xlsx'
import FileSaver from 'file-saver'
export default {
  name: 'ExportXLSX',

  props: {
    vucTable: null,
    printTitle: {
      type: String,
      default: '导出数据'
    }
  },
  data() {
    return {
      exportTitle: this.printTitle,
      dataSrc: 'all'
    }
  },
  computed: {
    expCols() {
      return this.vucTable.columns
    }
  },
  methods: {
    prepearExport() {

    },
    handleEnd() {
    },
    toBuffer(wbout) {
      let buf = new ArrayBuffer(wbout.length)
      let view = new Uint8Array(buf)
      for (let index = 0; index !== wbout.length; ++index) view[index] = wbout.charCodeAt(index) & 0xFF
      return buf
    },
    async doExport_json() {
      let tableData = []
      if (this.dataSrc === 'all') {
        tableData = this.vucTable.getTableData().fullData
      } else {
        tableData = this.vucTable.getCheckedData()
      }
      const { customs } = this.vucTable
      // const exportCols = columns.filter(item => !['index', 'selection', 'tools'].includes(item.type))
      const header = []
      const headerDisplay = {}
      for (let i = 0, len = customs.length; i < len; i++) {
        const col = customs[i]
        if (col.visible === false || !col.field) {
          continue
        }
        header.push(col.field)
        headerDisplay[col.field] = col.title
      }
      const expData = [headerDisplay]
      for (let i = 0, len = tableData.length; i < len; i++) {
        let row = {}
        for (let j = 0, jlen = header.length; j < jlen; j++) {
          const key = header[j]
          row[key] = tableData[i][key]
        }
        expData.push(row)
      }
      let book = XLSX.utils.book_new()
      let sheet = XLSX.utils.json_to_sheet(expData, { header, skipHeader: true, raw: true })
      XLSX.utils.book_append_sheet(book, sheet)
      let wbout = XLSX.write(book, { bookType: 'xlsx', bookSST: false, type: 'binary' })
      let blob = new Blob([this.toBuffer(wbout)], { type: 'application/octet-stream' })
      // 保存导出
      FileSaver.saveAs(blob, this.exportTitle + '.xlsx')
      this.$emit('close')
    },
    async doExport() {
      let tableData = []
      if (this.dataSrc === 'all') {
        tableData = this.vucTable.getTableData().fullData
      } else {
        tableData = this.vucTable.getCheckedData()
      }
      const { columns, customColumns } = this.vucTable
      // console.log(this.vucTable)
      const exportCols = columns.filter(item => !['index', 'selection', 'tools'].includes(item.type))
      await this.$refs.pageGrid.loadColumn(exportCols)
      // await this.$refs.pageGrid.loadData(tableData)

      // 转换数据
      let table = document.createElement('table')
      let tableHeader = this.$refs.pageGrid.$el.querySelector('.body--wrapper>.vxe-table--header')

      /*       let tableBody = this.$refs.pageGrid.$el.querySelector('.body--wrapper>.vxe-table--body')
            table.innerHTML = tableHeader.innerHTML + tableBody.innerHTML
       */
      const bodyInnerHtml = []
      const header = []

      for (let i = 0, len = tableData.length; i < len; i++) {
        bodyInnerHtml.push('<tr>')
        for (let j = 0, jlen = customColumns.length; j < jlen; j++) {
          const key = customColumns[j].property
          if (!key || header.indexOf(key) >= 0) {
            header.push(key)
            continue
          }

          bodyInnerHtml.push(`<td>${tableData[i][key] || ''}</td>`)
        }
        bodyInnerHtml.push('</tr>')
      }

      table.innerHTML = tableHeader.innerHTML + bodyInnerHtml.join('')

      let book = XLSX.utils.book_new()
      let sheet = XLSX.utils.table_to_sheet(table, { raw: true })
      XLSX.utils.book_append_sheet(book, sheet)
      let wbout = XLSX.write(book, { bookType: 'xlsx', bookSST: false, type: 'binary' })
      let blob = new Blob([this.toBuffer(wbout)], { type: 'application/octet-stream' })
      // 保存导出
      FileSaver.saveAs(blob, this.exportTitle + '.xlsx')
      table.remove()
      this.$emit('close')
    }
  },
  mounted() {
    // console.log(this.printTitle)
  }
}
</script>
<style lang="less" scoped>
.action-group {
  position: absolute;
  right: 32px;
  bottom: 16px;
}
.ivu-form-item {
  margin-bottom: 8px;
}
.number {
  width: 80px;
  min-width: 80px;
}
</style>
