import dayjs from 'dayjs';

/**
 * Calculates the elapsed time between two dates and returns a formatted string representing the duration.
 *
 * @param {string | null | undefined} begin - The starting date.
 * @param {string | null | undefined} end - The ending date.
 * @return {string} The formatted elapsed time string.
 */
export const elapsedTime = (begin?: string | null, end?: string | null): string => {
  if (begin === undefined || begin === null) {
    return '--';
  }

  const beginDate = dayjs(begin);
  const endDate = end === undefined || end === null ? dayjs() : dayjs(end);
  if (!beginDate.isValid() || !endDate.isValid()) {
    return '--';
  }

  const timestamp = endDate.valueOf() - beginDate.valueOf();
  if (timestamp < 0) {
    return '时间有误';
  }
  const duration = dayjs.duration(timestamp);
  const years = duration.years();
  const months = duration.months();
  const days = duration.days();
  const hours = duration.hours();
  const minutes = duration.minutes();
  const seconds = duration.seconds();
  if (years !== 0) {
    return `${years}年${months}个月`;
  }
  if (months !== 0) {
    return `${months}个月${days}天`;
  }
  if (days !== 0) {
    return `${days}天${hours}小时`;
  }
  if (hours !== 0) {
    return `${hours}小时${minutes}分`;
  }
  return `${minutes}分${seconds}秒`;
};

/**
 * 是否是有效的日期
 *
 * @param {Date} date - The date to check.
 * @return {boolean} True if the date is valid, false otherwise.
 */
export const isValidDate = (date: Date): boolean => {
  if (date instanceof Date) {
    return !Number.isNaN(date.getTime()); // valueOf() 也可以
  }
  return false;
};

/**
 * 能否使用 dayjs 转换成 Date
 *
 * @param {Date | string | number | null | undefined} date - The date to be checked.
 * @return {boolean} Returns true if the date can be converted to a valid Date object, otherwise returns false.
 */
export const canBeConvertToDate = (date?: Date | string | number | null): boolean => {
  if (date === undefined || date === null || date === '') {
    return false;
  }
  const convertedDate = dayjs(date);
  return convertedDate.isValid();
};

/**
 * 转换日期
 *
 * @param {Date | string | number | null | undefined} date - The date to format.
 * @param {string} [format='YYYY-MM-DD HH:mm:ss'] - The format string to use.
 * @return {string} The formatted date string.
 */
export const formatDate = (
  date?: Date | string | number | null,
  format: string = 'YYYY-MM-DD HH:mm:ss',
): string => {
  if (date === undefined || date === null || date === '') {
    return '--';
  }
  const convertedDate = dayjs(date);
  if (!convertedDate.isValid()) {
    return '--';
  }

  return convertedDate.format(format);
};
