import dayjs from '@/plugins/dayjs'
import type { DurationUnitType } from 'dayjs/plugin/duration'

export const fromNow = (time: string) => {
  return dayjs(time).fromNow()
}

export const calendar = (time: string) => {
  return dayjs(time).calendar()
}

export const getTimeText = (time: any = new Date()) => {
  return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
}

export const getDurationText = (seconds: number, unit: DurationUnitType = 's') => {
  const t = dayjs.duration(seconds, unit)
  const h = t.hours()
  const m = t.minutes()
  const s = t.seconds()

  return (
    (h ? String(h).padStart(2, '0') + 'h ' : '') +
    (h || m ? String(m).padStart(2, '0') + 'm ' : '') +
    String(s).padStart(2, '0') +
    's'
  )
}

// 毫秒格式化为 "1h2m3s" 格式
export const mill2duration = (time: any) => {
  // 转换为 duration 对象
  const durationObj = dayjs.duration(time)

  // 提取小时、分钟和秒
  const hours = durationObj.hours()
  const minutes = durationObj.minutes()
  const seconds = durationObj.seconds()

  // 构建格式化的字符串
  let result = ''
  if (hours > 0) result += `${hours}h`
  if (minutes > 0) result += `${minutes}m`
  if (seconds > 0 || result === '') result += `${seconds}s` // 确保至少显示秒数

  return result
}

// 计算两个时间之间的差异并格式化为 "1h2m3s" 格式
export const timeDiff = (startTime: any, endTime: any) => {
  const start = dayjs(startTime)
  const end = dayjs(endTime)
  return mill2duration(end.diff(start))
}
