format-utils.uts 2.63 KB
/**
 * 格式化工具函数(系统级)
 * 包含文本处理、时间格式化等通用功能
 */

/**
 * 判断文本是否为空或无效值
 * 后端偶发将缺省序列化为字符串 "null"/"undefined";仅用于展示判断
 */
export function isBlankDisplayText(text: string | null): boolean {
  if (text == null) {
    return true
  }
  const t = text.trim()
  if (t.length == 0) {
    return true
  }
  const lower = t.toLowerCase()
  return lower == 'null' || lower == 'undefined'
}

/**
 * 卡片信息区:无有效文案时统一展示占位符
 */
export function textOrDash(text: string | null): string {
  if (isBlankDisplayText(text)) {
    return '--'
  }
  return text as string
}

/**
 * 格式化电话号码:3-4-4 格式
 */
export function formatPhone(phone: string | null): string {
  if (phone == null || phone == '') {
    return ''
  }
  const p = phone as string
  if (isBlankDisplayText(p)) {
    return ''
  }
  const s = p.replace(/\s/g, '')
  if (s.length >= 11) {
    return s.substring(0, 3) + ' ' + s.substring(3, 7) + ' ' + s.substring(7, 11)
  }
  return p
}

/**
 * 格式化时间戳为日期时间字符串:yyyy.MM.dd HH:mm:ss
 */
export function formatTimestamp(ts: number | null): string {
  if (ts == null || ts <= 0) {
    return ''
  }
  const d = new Date(ts)
  const y = d.getFullYear()
  const m = (d.getMonth() + 1).toString().padStart(2, '0')
  const day = d.getDate().toString().padStart(2, '0')
  const h = d.getHours().toString().padStart(2, '0')
  const min = d.getMinutes().toString().padStart(2, '0')
  const sec = d.getSeconds().toString().padStart(2, '0')
  return `${y}.${m}.${day} ${h}:${min}:${sec}`
}

/**
 * 格式化时间戳为日期字符串:yyyy-MM-dd
 */
export function formatDateOnly(ts: number | null): string {
  if (ts == null || ts <= 0) {
    return ''
  }
  const d = new Date(ts)
  const y = d.getFullYear()
  const m = (d.getMonth() + 1).toString().padStart(2, '0')
  const day = d.getDate().toString().padStart(2, '0')
  return `${y}-${m}-${day}`
}

/**
 * 格式化类日期字段(支持字符串、数字时间戳)
 * 入参可为 null(JSON 缺字段),避免调用方 `as any` 在 Kotlin 侧触发非空 Any 强转 NPE
 */
export function formatDateTimeLike(value: any | null): string {
  if (value == null) {
    return ''
  }
  if (typeof value == 'string') {
    if (isBlankDisplayText(value)) {
      return ''
    }
    return value
  }
  if (typeof value == 'number') {
    return formatTimestamp(value)
  }
  const s = `${value}`
  if (isBlankDisplayText(s)) {
    return ''
  }
  const n = parseFloat(s)
  if (!isNaN(n) && n > 0) {
    return formatTimestamp(n)
  }
  return s
}