import { XbTableClass } from '@/utils'
import { processNumberValue } from '../column'
import { TableColumnCtx } from 'element-plus'

export interface SummaryMethodProps<T = anyObj> {
  columns: TableColumnCtx<T>[]
  data: T[]
}

export function useTable() {
  const tableRef = ref()
  const xbTable = reactive(
    new XbTableClass({
      column: [],
      page: {
        size: -1,
        current: 1,
        total: 0,
      },
      expandAll: false,
      data: [],
    }),
  )
  provide('xbTable', xbTable)

  async function handleHeaderClick(data: anyObj) {
    if (!data.sortable) return
    tableRef.value.getRef().sort(data.property, 'descending')
  }

  // 底部的那行数据
  function getSummaries(param: SummaryMethodProps) {
    const { columns, data } = param
    const sums: (string | number)[] = []
    const len = xbTable.table.data?.length || 0
    columns.forEach((column, index) => {
      if (index === 0) {
        sums[index] = '平均'
        return
      }
      if (column.property === 'name') {
        sums[index] = ''
        return
      }
      const values = data.map(item => Number(item[column.property]))
      sums[index] = processNumberValue(values, column, len)
    })
    return sums
  }

  return {
    getSummaries,
    handleHeaderClick,
    tableRef,
    xbTable,
  }
}
