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

const props = defineProps({
  data: Object
})

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 tableRef = ref<VxeGridInstance | null>(null)

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') {
      curColumn = {
        ...curColumn,
        sortBy: ({ row, column }: any) => {
          return dayjs(row[column.field]).unix()
        },
        formatter: ({ cellValue }: any) =>
          cellValue ? dayjs(cellValue).format('MMM-DD-YYYY ') : '--'
      }
    } else if (item.formatter === 'dateTime') {
      curColumn = {
        ...curColumn,
        formatter: ({ cellValue }: any) =>
          cellValue ? dayjs(cellValue).format('MMM-DD-YYYY HH:mm:ss') : '--'
      }
    }
    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 16px;
}
</style>
<style lang="scss"></style>
