import type { Optional } from '@/types';
import dayjs from 'dayjs';
import duration from 'dayjs/plugin/duration';

dayjs.extend(duration);

export const formatDuration = (startTime: Optional<string>, endTime: Optional<string>) => {
  if (!startTime || !endTime) return '';
  const start = dayjs(startTime);
  const end = dayjs(endTime);
  const diffSeconds = end.diff(start, 'second');
  const duration = dayjs.duration(Math.abs(diffSeconds), 'second');
  const d = Math.floor(duration.asDays());
  const h = duration.hours();
  const m = duration.minutes();
  const s = duration.seconds();
  let result = '';
  if (d > 0) result += `${d}天`;
  if (h > 0) result += `${h}小时`;
  if (m > 0) result += `${m}分钟`;
  if (s > 0) result += `${s}秒`;
  return diffSeconds < 0 ? `-${result}` : result;
};
