import { type VxeGridInstance, type VxeGridProps } from 'vxe-table'

/**
 * 根据表格内容自动调整列宽
 * @param tableData 表格整体数据
 * @param grid 表格实例
 * @returns
 */
export const autoWidth = (tableData: VxeGridProps, grid: VxeGridInstance) => {
  const columns = tableData.columns
  const data = tableData.data
  const columnsWidth: { width: number; field: any }[] = []
  if (!columns || !data) return
  columns.forEach((column: any) => {
    if (column?.field) {
      let curStr = ''
      let width = 0
      const field = column.field
      // 判断表头的宽度
      if (column.title.length < 12) {
        width = column.title.length * 11 + 40
      } else if (column.title.length < 20) {
        width = column.title.length * 8 + 40
      } else {
        width = column.title.length * 7 + 40
      }
      const curData = data.length > 1000 ? data.slice(0, 1000) : data
      // 判断表格内容的宽度
      // 找到最长的字符串
      curData.forEach((row: any) => {
        curStr.length < row[field]?.toString().length && (curStr = row[field].toString())
      })
      // column.title.length > curStr.length && (curStr = column.title)
      // 表头的宽度如果小于表格内容的宽度
      if (width < curStr.length * 11 + 20) {
        // width = curStr.length * 10 + 20
        if (curStr.length > 20) {
          width = curStr.length * 9 + 40
        } else {
          width = curStr.length * 11 + 20
        }
      }
      // 宽度不能小于100
      // width < 100 && (width = 100)
      // 最终宽度不能超过400
      width > 400 && (width = 400)

      columnsWidth.push({
        width,
        field: field
      })
    }
  })
  columnsWidth.forEach((item) => {
    const curColumn: any = columns.find((column: any) => column.field === item.field)
    curColumn.width = item.width
  })
  // 表格重新刷新列配置
  grid.reloadColumn(columns)
}
