/**
 * 人性化时间显示
 *
 * @param {string | number | Date | null | undefined} datetime
 */
export function formatTime(datetime: string | number | Date | null | undefined): string {
  if (datetime == null) return ''

  const datetimeStr = String(datetime).replace(/-/g, '/')

  const time = new Date()
  let outTime = new Date(datetimeStr)
  if (/^[1-9]\d*$/.test(String(datetime))) {
    outTime = new Date(parseInt(String(datetime)) * 1000)
  }

  if (time.getTime() < outTime.getTime() || time.getFullYear() != outTime.getFullYear()) {
    return parseTime(outTime, '{y}/{m}/{d} {h}:{i}') || ''
  }

  if (time.getMonth() != outTime.getMonth()) {
    return parseTime(outTime, '{m}/{d} {h}:{i}') || ''
  }

  if (time.getDate() != outTime.getDate()) {
    const day = outTime.getDate() - time.getDate()
    if (day == -1) {
      return parseTime(outTime, '昨天 {h}:{i}') || ''
    }

    if (day == -2) {
      return parseTime(outTime, '前天 {h}:{i}') || ''
    }

    return parseTime(outTime, '{m}-{d} {h}:{i}') || ''
  }

  const diff = time.getTime() - outTime.getTime()

  if (time.getHours() != outTime.getHours() || diff > 30 * 60 * 1000) {
    return parseTime(outTime, '{h}:{i}') || ''
  }

  let minutes = outTime.getMinutes() - time.getMinutes()
  if (minutes == 0) {
    return '刚刚'
  }

  minutes = Math.abs(minutes)
  return `${minutes}分钟前`
}

/**
 * 时间格式化方法
 *
 * @param {Date | string | number} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime(time: Date | string | number, cFormat?: string): string | null {
  if (arguments.length === 0) {
    return null
  }

  let date: Date
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'

  if (typeof time === 'object') {
    date = time
  } else {
    let timeValue: string | number = time
    if (typeof timeValue === 'string' && /^[0-9]+$/.test(timeValue)) {
      timeValue = parseInt(timeValue)
    }
    if (typeof timeValue === 'number' && timeValue.toString().length === 10) {
      timeValue = timeValue * 1000
    }

    date = new Date(String(timeValue).replace(/-/g, '/'))
  }

  const formatObj: Record<string, number> = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }

  const time_str = format.replace(/{([ymdhisa])+}/g, (result: string, key: string) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }

    return value.toString().padStart(2, '0')
  })

  return time_str
}

/**
 * 人性化显示时间
 *
 * @param {string | number | Date | null | undefined} datetime
 */
export function beautifyTime(datetime: string | number | Date | null | undefined = ''): string {
  if (datetime == null) {
    return ''
  }

  // 确保 datetime 是字符串
  let datetimeStr = String(datetime).trim()
  
  // 替换 - 为 /
  datetimeStr = datetimeStr.replace(/-/g, '/')

  const time = new Date()
  let outTime: Date

  // 检查是否是纯数字（时间戳）
  if (/^[1-9]\d*$/.test(datetimeStr)) {
    outTime = new Date(parseInt(datetimeStr) * 1000)
  } else {
    // 尝试多种日期格式解析
    outTime = new Date(datetimeStr)
    
    // 如果第一次转换失败，尝试其他方法
    if (isNaN(outTime.getTime())) {
      // 尝试解析 YYYY/MM/DD HH:mm:ss 格式
      const dateTimeMatch = datetimeStr.match(/^(\d{4})\/(\d{1,2})\/(\d{1,2})\s+(\d{1,2}):(\d{1,2}):(\d{1,2})$/)
      if (dateTimeMatch) {
        const [, year, month, day, hour, minute, second] = dateTimeMatch
        outTime = new Date(
          parseInt(year),
          parseInt(month) - 1, // 月份从0开始
          parseInt(day),
          parseInt(hour),
          parseInt(minute),
          parseInt(second)
        )
      } else {
        // 尝试解析 YYYY/MM/DD HH:mm 格式
        const dateTimeMatch2 = datetimeStr.match(/^(\d{4})\/(\d{1,2})\/(\d{1,2})\s+(\d{1,2}):(\d{1,2})$/)
        if (dateTimeMatch2) {
          const [, year, month, day, hour, minute] = dateTimeMatch2
          outTime = new Date(
            parseInt(year),
            parseInt(month) - 1,
            parseInt(day),
            parseInt(hour),
            parseInt(minute),
            0
          )
        }
      }
    }
  }

  // 如果仍然转换失败，返回原始字符串
  if (isNaN(outTime.getTime())) {
    return datetimeStr
  }

  if (time.getTime() < outTime.getTime()) {
    return parseTime(outTime, '{y}/{m}/{d}') || ''
  }

  if (time.getFullYear() != outTime.getFullYear()) {
    return parseTime(outTime, '{y}/{m}/{d}') || ''
  }

  if (time.getMonth() != outTime.getMonth()) {
    return parseTime(outTime, '{m}/{d}') || ''
  }

  if (time.getDate() != outTime.getDate()) {
    const day = outTime.getDate() - time.getDate()
    if (day == -1) {
      return parseTime(outTime, '昨天 {h}:{i}') || ''
    }

    if (day == -2) {
      return parseTime(outTime, '前天 {h}:{i}') || ''
    }

    return parseTime(outTime, '{m}-{d}') || ''
  }

  if (time.getHours() != outTime.getHours()) {
    return parseTime(outTime, '{h}:{i}') || ''
  }

  let minutes = outTime.getMinutes() - time.getMinutes()
  if (minutes == 0) {
    return '刚刚'
  }

  minutes = Math.abs(minutes)
  return `${minutes}分钟前`
} 