<script setup lang="ts">
import { type VxeGridInstance, type VxeGridProps } from 'vxe-table'
// import { autoWidth } from '@/utils/table'
import { useRowClickStyle } from '@/hooks/rowClickStyle'
import { formatTimezone, formatNumber } from '@/utils/tools'

const props = defineProps({
  data: Object
})
const tableRef = ref<VxeGridInstance | null>(null)
const tableData = ref<VxeGridProps<any>>({
  minHeight: 70,
  border: true,
  round: true,
  columns: [],
  data: [],
  scrollY: { enabled: true, oSize: 20, gt: 30 },
  stripe: true,
  emptyText: ' ',
  showHeaderOverflow: true,
  showOverflow: true,
  headerRowStyle: {
    backgroundColor: 'var(--color-table-header-bg)'
  },
  columnConfig: { resizable: true, useKey: true },
  rowConfig: { isHover: true }
})

const handleColumns = (columns: any) => {
  const newColumns = columns.map((item: any) => {
    let curColumn: any = {
      title: item.title,
      field: item.field,
      minWidth: 30
    }

    // 格式化
    if (item.formatter === 'date' || item.formatter === 'dateTime') {
      curColumn = {
        ...curColumn,
        formatter: ({ cellValue }: any) => formatTimezone(cellValue)
      }
    } else if (item.formatter === 'number') {
      curColumn = {
        ...curColumn,
        formatter: ({ cellValue }: any) => formatNumber(Number(cellValue), item?.digits)
      }
    }
    return curColumn
  })
  return newColumns
}
watch(
  () => props.data,
  (newVal) => {
    const containers = newVal?.containers
    if (containers && containers.container_column) {
      tableData.value.columns = handleColumns(containers.container_column)
      tableData.value.data = containers.container_data
      // nextTick(() => {
      //   tableRef.value && autoWidth(tableData.value, tableRef.value)
      // })
    }
  },
  {
    immediate: true,
    deep: true
  }
)

// 实现行点击样式
useRowClickStyle(tableRef)
</script>

<template>
  <div class="containers">
    <vxe-grid ref="tableRef" v-bind="tableData">
      <template #empty>
        <div class="empty">No data</div>
      </template>
    </vxe-grid>
  </div>
</template>

<style lang="scss" scoped>
.containers {
  padding: 8px 16px;
}
</style>
