<script setup lang="ts">
import { ElMessage } from 'element-plus'
import { useExcel } from '@/hooks/useExcel'

const { importExcel, toTwoArray } = useExcel()

// 表格数据
const tableData = ref<Record<string, any>[]>([])
// 表格二维数据
const tableDataTwo = ref<Record<string, any>[]>([])
// 表头数据
const column = ref<Array<string>>(['A', 'B', 'C', 'D', 'E', 'F', 'G'])

const importFile = (file: File) => {
  importExcel(file).then(({ title, list }: any) => {
    column.value = title
    tableData.value = list

    tableDataTwo.value = toTwoArray(list)
  })

  return false
}

const getTwoData = () => {
  console.log(tableDataTwo.value)
  ElMessage.success('数据已打印在控制台')
}
</script>

<template>
  <el-card shadow="never">
    <div class="flex">
      <el-upload action="" accept=".xls,.xlsx" :show-upload-list="false" :before-upload="importFile">
        <el-button type="primary">导入</el-button>
      </el-upload>
      <el-button type="primary" @click="getTwoData" class="ml-3">获取表格二维数据</el-button>
    </div>
    <table class="table" border="1">
      <colgroup>
        <col width="52" />
        <col v-for="item in column" :key="item" />
      </colgroup>
      <thead>
        <tr>
          <th></th>
          <th v-for="item in column" :key="item" style="text-align: center">
            {{ item }}
          </th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(item, index) in tableData" :key="index">
          <td style="text-align: center">{{ index + 1 }}</td>
          <template v-for="key in column">
            <td
              v-if="item[key]?.colspan !== 0 && item[key].rowspan !== 0"
              :key="key"
              :colspan="item[key].colspan"
              :rowspan="item[key].rowspan"
              style="text-align: center"
            >
              {{ item[key].value }}
            </td>
          </template>
        </tr>
        <tr v-if="!tableData.length">
          <td :colspan="column.length + 1" style="text-align: center; background: none">暂无数据</td>
        </tr>
      </tbody>
    </table>
  </el-card>
</template>

<style scoped>
.table {
  width: 100%;
  border-collapse: collapse;
  border-spacing: 1px;
  border-color: var(--el-border-color);
}
</style>
