import { Ref } from 'vue'
import { CommonTableFormatter } from '~/common'
import { CellRenderProps } from '../../type'

export function useFormatter(flag: Ref<boolean>) {
  const tableColumnFormatter = (columnLabel: string) => {
    return unref(flag) ? columnLabel : columnLabel.replace('/件', '')
  }

  const tableDataFormatter: CommonTableFormatter = (
    row,
    { label, property },
    cellValue,
    index
  ) => {
    if (!unref(flag)) {
      const matched = label.match(/(?<=\()\S+(?=\))/)
      if (matched) {
        const machedStr = matched[0]
        const countIndex = machedStr.split('/').findIndex(str => str === '件')
        if (
          countIndex > -1 &&
          typeof cellValue === 'string' &&
          cellValue.split('/')[countIndex]
        ) {
          return cellValue
            .split('/')
            .filter((_, index) => index !== countIndex)
            .join('/')
        }
      }
    }
    if (property.includes('Time') && typeof cellValue === 'string') {
      return cellValue
        .trim()
        .slice(5, -3)
        .replace(/(T|\s)+/, '\n')
    }
    if (property === 'jiahuo') {
      return cellValue ? '是' : '否'
    }
    return String(cellValue ?? '')
  }

  return {
    tableColumnFormatter,
    tableDataFormatter,
  }
}
