<script>
import XLSX from 'xlsx'
import sdDataTable from '../sd-data-table.vue'
import components from './_import-components/sd-data-table-export-import'

function getStrCount(str) {
  let len = 0
  for (let i = 0; i < str.length; i++) {
    if (str.charCodeAt(i) > 127 || str.charCodeAt(i) === 94) {
      len += 2
    } else {
      len++
    }
  }
  return len
}

export default {
  name: 'SdDataTableExport',
  components,
  inheritAttrs: false,
  inject: {
    SdTabbedView: { default: undefined },
  },
  data() {
    return {}
  },

  methods: {
    export() {
      const table = this.$el.querySelector('table')
      const workbook = XLSX.utils.table_to_book(table, { raw: true })
      const widthInfos = []
      const sheet = workbook.Sheets[workbook.SheetNames[0]]

      // A1:H30 中的H30
      const lastCell = sheet['!ref'].split(':')[1]
      // H - A 来计算列数
      const columns = lastCell.substring(0, 1).codePointAt() - 'A'.codePointAt() + 1
      // H30 中的 30
      const rows = parseInt(lastCell.substring(1))

      for (let i = 0; i < columns; i++) {
        let maxChars = 0
        for (let j = 1; j <= rows; j++) {
          const cell = sheet[String.fromCodePoint('A'.codePointAt() + i) + j]
          // 一个中文字符等于2个英文字符
          maxChars = Math.max(getStrCount(cell.v.toString()), maxChars)
        }
        // 最宽50个字符
        widthInfos.push({ wch: Math.min(maxChars, 50) })
      }

      sheet['!cols'] = widthInfos
      const pageTitle =
        this.SdTabbedView?.selectedTabTitle || document.title.split('|')[0].trim() || 'export'
      XLSX.writeFile(workbook, pageTitle + '.xlsx')
      this.$emit('finish')
    },
  },
  render() {
    const {
      disableExportTable,
      pagination,
      hidePagination,
      showSelection,
      columns,
      actions, // 去掉操作列
      sorter,
      ...restAttrs
    } = this.$attrs

    const attrs = {
      ...restAttrs,
      disableExportTable: true,
      hidePagination: true,
      showSelection: false,
      pagination: { pageSize: Number.MAX_VALUE },
      columns: columns.map((column) => {
        const {
          sdClickable, // 清除可点击列
          sdCandidate, // 所有列都显示，没有备选列
          ...restColumn
        } = column
        if (sorter?.order) {
          // 用户没有点击排序过，忽略默认排序
          if (sorter.field === column.dataIndex) {
            // 如果当前列就是用户点击的列，把用户排序的方式作为默认排序
            return { ...restColumn, defaultSortOrder: sorter.order }
          } else {
            // 如果当前列不是用户点击的列，清除默认排序的值
            restColumn.defaultSortOrder = undefined
            return restColumn
          }
        } else {
          // 用户没有点击排序过，使用默认排序
          return restColumn
        }
      }),
    }
    return (
      <sdDataTable
        {...{
          attrs,
          class: this.$style.wrapper,
          scopedSlots: this.$scopedSlots,
          on: {
            dataLoaded: () => {
              this.$nextTick(this.export)
            },
          },
        }}
      />
    )
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.wrapper {
  display: none;
}
</style>
