<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>>({
  border: true,
  round: true,
  minHeight: 70,
  maxHeight: 500,
  columns: [
    {
      field: 'milestones',
      title: 'Milestones',
      minWidth: 120
    },
    {
      field: 'dateTime',
      title: 'Date Time',
      minWidth: 80
    },
    {
      field: 'locations',
      title: 'Locations',
      minWidth: 80
    },
    {
      field: 'remarks',
      title: 'Remarks',
      minWidth: 80
    }
  ],
  data: [
    {
      milestones: 'Milestone 1',
      dateTime: 'Jun-08-2024 12:00 AM',
      locations: 'Shenzhen',
      remarks: 'Remarks 1'
    },
    {
      milestones: 'Milestone 2',
      dateTime: 'Jun-10-2024 12:00 AM',
      locations: 'Valencia',
      remarks: 'Remarks 2'
    }
  ],
  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
    }

    // 格式化
    if (item.formatter === 'date') {
      curColumn = {
        ...curColumn,
        sortBy: ({ row, column }: any) => {
          return dayjs(row[column.field]).unix()
        },
        formatter: ({ cellValue }: any) => dayjs(cellValue).format('MMM-YYYY-DD ') || '--'
      }
    } else if (item.formatter === 'dateTime') {
      curColumn = {
        ...curColumn,
        formatter: ({ cellValue }: any) => dayjs(cellValue).format('MMM-YYYY-DD HH:mm:ss') || '--'
      }
    }
    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
  }
)

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

<template>
  <div class="Milestones">
    <vxe-grid class="radius-bottom" ref="tableRef" :style="{ border: 'none' }" v-bind="tableData">
    </vxe-grid>
  </div>
</template>

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