import { datetimeToTime } from '@/utils/validate'
import { Ref } from 'vue'
import { CommonTableFormatter, MaybeRef } from '~/common'

export function useFormatter(
  flag: Ref<boolean>,
  tableColumnsCountIndexMap: { [columnName: string]: number },
  UTCFlag?: MaybeRef<boolean>
) {
  const tableColumnFormatter = (columnLabel: string) => {
    return unref(flag) ? columnLabel : columnLabel.replace(/(\/件)|(件\/)/, '')
  }

  const tableDataFormatter: CommonTableFormatter = (
    row,
    { label, property },
    cellValue,
    index
  ) => {
    if (property === 'flightDate' && typeof cellValue === 'string') {
      return cellValue.trim().slice(5)
    }
    if (!unref(flag) && typeof cellValue === 'string') {
      const countIndex = tableColumnsCountIndexMap[property]
      if (countIndex) {
        const splitedValue = cellValue.split('/')
        splitedValue.splice(countIndex, 1)
        return splitedValue.join('/')
      }
      // const matched = label.match(/(?<=\()\S+(?=\))/)
      // if (matched) {
      //   const machedStr = matched[0]
      //   const countIndex = machedStr.split('/').findIndex(str => str === '件')
      //   if (countIndex > -1 && typeof cellValue === 'string') {
      //     return cellValue
      //       .split('/')
      //       .filter((_, index) => index !== countIndex)
      //       .join('/')
      //   }
      // }
    }
    // 临时处理-没有发起货站交接这一节点数据时，不显示发起货站交接时间
    if (property === 'requestDepotJoinTime' && !row['requestDepotJoin']) {
      return ''
    }
    if (property.includes('Time') && typeof cellValue === 'string') {
      // if (
      //   ['planDepartureTime', 'acLandingTime', 'planLandingTime'].includes(
      //     property
      //   )
      // ) {
      //   return cellValue
      //     .trim()
      //     .slice(5, -3)
      //     .replace(/[T|\s]+/, '\n')
      // } else {
      //   return datetimeToTime(cellValue, row.flightDate)
      // }
      return datetimeToTime(cellValue, row.flightDate, unref(UTCFlag))
    }
    if (property === 'jiahuo') {
      return cellValue ? '是' : ''
    }
    return String(cellValue ?? '')
  }

  return {
    tableColumnFormatter,
    tableDataFormatter,
  }
}
