<template>
  <el-dropdown
    :class="{
      export_dropdown_mobile: mobile,
    }"
    trigger="click"
    @command="handleCommand"
  >
    <span
      class="el-dropdown-link"
      :class="{
        export_link: !mobile,
        export_link_mobile: mobile,
      }"
    >
      <ht-icon name="export" />
      <span v-if="!mobile">子表导出</span>
    </span>
    <el-dropdown-menu slot="dropdown">
      <el-dropdown-item command="current">当前页数据</el-dropdown-item>
      <el-dropdown-item command="all">所有数据</el-dropdown-item>
    </el-dropdown-menu>
  </el-dropdown>
</template>
<script>
  import SubPagination from '@/services/SubPagination.js'
  import { decode } from '@/util/base64.js'
  const { saveAs } = require('file-saver')
  import utils from '@/utils.js'

  export default {
    name: 'HtSubExportDialog',
    props: {
      dataSubname: {
        type: String,
        required: true,
      },
      dataColumns: {
        type: String,
        required: true,
      },
      subtablePagination: {
        type: Boolean,
        default: false,
      },
      dataSubdesc: {
        type: String,
        default: '子表数据',
      },
      mobile: {
        type: Boolean,
        default: false,
      },
    },
    computed: {
      columns: function () {
        return eval(decode(this.dataColumns))
      },
    },
    created() {
      if (!this.$XLSX) {
        console.warn('要使用子表导入/导出功能需要安装XLSX插件')
      }
    },
    methods: {
      changeRowKey(rows) {
        var exportData = []
        rows.forEach((row) => {
          var exportRow = {}
          this.columns.forEach((col) => {
            if (col.ctrlType != 'suntable') {
              let value = row[col.name]
              // 转换成字符串
              try {
                value = row[col.name] + ''
              } catch (e) {
                console.error('导出转字符串异常', e)
              }
              exportRow[col.desc] = value
            }
          })
          exportData.push(exportRow)
        })
        return exportData
      },
      handleCommand(type) {
        const pInst = utils.getOnlineFormInstance(this)
        SubPagination.exportData(
          this.dataSubname,
          type,
          pInst,
          this.subtablePagination
        )
          .then((data) => {
            let exportData = this.changeRowKey(data)
            const sheet = this.$XLSX.utils.json_to_sheet(exportData),
              blob = this.sheet2blob(sheet)

            saveAs(blob, `${this.dataSubdesc}.xls`)
          })
          .catch((err) => {
            this.$message.error(`数据导出失败：${err}`)
          })
      },
      sheet2blob(sheet, sheetName) {
        sheetName = sheetName || 'sheet1'
        var workbook = {
          SheetNames: [sheetName],
          Sheets: {},
        }
        workbook.Sheets[sheetName] = sheet
        // 生成excel的配置项
        var wopts = {
          bookType: 'xls', // 要生成的文件类型
          bookSST: false, // 是否生成Shared String Table，官方解释是，如果开启生成速度会下降，但在低版本IOS设备上有更好的兼容性
          type: 'binary',
        }
        var wbout = this.$XLSX.write(workbook, wopts)
        var blob = new Blob([s2ab(wbout)], { type: 'application/octet-stream' })
        // 字符串转ArrayBuffer
        function s2ab(s) {
          var buf = new ArrayBuffer(s.length)
          var view = new Uint8Array(buf)
          for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xff
          return buf
        }
        return blob
      },
    },
  }
</script>
<style lang="scss" scoped>
  .export_link {
    font-weight: normal;
    color: $base-color-blue;
    cursor: pointer;
  }
  .export_link_mobile {
    svg {
      font-size: 18px;
    }
  }
  .export_dropdown_mobile.el-dropdown {
    padding: 0 !important;
  }
</style>
