/**
 * 通用工具类
 * 此代码由AI生成
 */

/**
 * 格式化时间
 * @param {string|Date} time 
 * @param {string} pattern 
 */
export function formatTime(time, pattern = 'yyyy-MM-dd HH:mm:ss') {
  if (!time) return ''
  const date = new Date(time)
  const o = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'H+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds()
  }
  if (/(y+)/.test(pattern)) {
    pattern = pattern.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  for (const k in o) {
    if (new RegExp('(' + k + ')').test(pattern)) {
      pattern = pattern.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length))
    }
  }
  return pattern
}

/**
 * 日期格式化展示（5分钟前，今天 HH:mm 等）
 */
export function displayTime(time) {
  if (!time) return ''
  const date = new Date(time)
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  
  if (diff < 60000) return '刚刚'
  if (diff < 3600000) return Math.floor(diff / 60000) + '分钟前'
  if (now.toDateString() === date.toDateString()) return '今天 ' + formatTime(date, 'HH:mm')
  
  const yesterday = new Date(now.getTime() - 86400000)
  if (yesterday.toDateString() === date.toDateString()) return '昨天 ' + formatTime(date, 'HH:mm')
  
  return formatTime(date, 'MM-dd HH:mm')
}
