/**
 * 时间格式化工具
 */

/**
 * 格式化时间为 HH:mm:ss
 */
export function formatTime(date = new Date()) {
  const d = typeof date === 'number' ? new Date(date) : date
  const hours = String(d.getHours()).padStart(2, '0')
  const minutes = String(d.getMinutes()).padStart(2, '0')
  const seconds = String(d.getSeconds()).padStart(2, '0')
  return `${hours}:${minutes}:${seconds}`
}

/**
 * 格式化时间为 HH:mm
 */
export function formatTimeShort(date = new Date()) {
  const d = typeof date === 'number' ? new Date(date) : date
  const hours = String(d.getHours()).padStart(2, '0')
  const minutes = String(d.getMinutes()).padStart(2, '0')
  return `${hours}:${minutes}`
}

/**
 * 格式化日期为 YYYY-MM-DD
 */
export function formatDate(date = new Date()) {
  const d = typeof date === 'number' ? new Date(date) : date
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

/**
 * 格式化日期时间为 YYYY-MM-DD HH:mm:ss
 */
export function formatDateTime(date = new Date()) {
  return `${formatDate(date)} ${formatTime(date)}`
}

/**
 * 格式化日期为中文显示
 */
export function formatDateCN(date = new Date()) {
  const d = typeof date === 'number' ? new Date(date) : date
  const year = d.getFullYear()
  const month = d.getMonth() + 1
  const day = d.getDate()
  const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
  const weekday = weekdays[d.getDay()]
  return `${year}年${month}月${day}日 ${weekday}`
}

/**
 * 格式化相对时间
 */
export function formatRelativeTime(timestamp) {
  const now = Date.now()
  const diff = now - timestamp

  if (diff < 60000) {
    return '刚刚'
  } else if (diff < 3600000) {
    return Math.floor(diff / 60000) + '分钟前'
  } else if (diff < 86400000) {
    return Math.floor(diff / 3600000) + '小时前'
  } else if (diff < 604800000) {
    return Math.floor(diff / 86400000) + '天前'
  } else {
    return formatDate(timestamp)
  }
}

/**
 * 格式化时长为 mm:ss 或 HH:mm:ss
 */
export function formatDuration(seconds) {
  if (seconds < 0) return '00:00'

  const h = Math.floor(seconds / 3600)
  const m = Math.floor((seconds % 3600) / 60)
  const s = seconds % 60

  if (h > 0) {
    return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`
  }
  return `${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`
}

/**
 * 获取当前时间戳
 */
export function getTimestamp() {
  return Date.now()
}

/**
 * 判断是否为今天
 */
export function isToday(date) {
  const d = typeof date === 'number' ? new Date(date) : date
  const today = new Date()
  return (
    d.getFullYear() === today.getFullYear() &&
    d.getMonth() === today.getMonth() &&
    d.getDate() === today.getDate()
  )
}

export default {
  formatTime,
  formatTimeShort,
  formatDate,
  formatDateTime,
  formatDateCN,
  formatRelativeTime,
  formatDuration,
  getTimestamp,
  isToday
}
