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

const props = defineProps({
  height: {
    type: Number,
    default: 240
  },
  data: Object
})

const tableData = ref<VxeGridProps<any>>({
  border: true,
  minHeight: 70,
  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 === 'dateTime') {
      curColumn = {
        ...curColumn,
        formatter: ({ cellValue, row }: any) => formatTimezone(cellValue, row.timezone)
      }
    }
    return curColumn
  })
  return newColumns
}
watch(
  () => props.data,
  (newVal) => {
    const milestones = newVal?.Milestones
    if (milestones && milestones.Milestones_column) {
      tableData.value.columns = handleColumns(milestones.Milestones_column)
      tableData.value.data = milestones.Milestones_data
      // nextTick(() => {
      //   tableRef.value && autoWidth(tableData.value, tableRef.value)
      // })
    }
  },
  {
    immediate: true,
    deep: true
  }
)

const tableRef = ref<VxeGridInstance | null>(null)
// 实现行点击样式
useRowClickStyle(tableRef)
</script>

<template>
  <div class="containers">
    <vxe-grid ref="tableRef" :style="{ border: 'none' }" 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>
