/**
 * Independent time operation tool to facilitate subsequent switch to dayjs
 */
import dayjs from 'dayjs';

const DATE_TIME_FORMAT = 'YYYY-MM-DD HH:mm:ss';
const DATE_FORMAT = 'YYYY-MM-DD';

export function formatToDateTime(
  date: dayjs.Dayjs | undefined = undefined,
  format = DATE_TIME_FORMAT,
): string {
  return dayjs(date).format(format);
}

export function formatToDate(
  date: dayjs.Dayjs | undefined = undefined,
  format = DATE_FORMAT,
): string {
  return dayjs(date).format(format);
}

export const dateUtil = dayjs;

export function getRelativeTime(timeStamp: number) {
  const ONE_SECONDS = 1000;
  const ONE_MINUTES = ONE_SECONDS * 60;
  const ONE_HOUR = ONE_MINUTES * 60;
  const ONE_DAY = ONE_HOUR * 24;
  const currentTime = new Date().getTime();

  // Determine whether the incoming timestamp is earlier than the current timestamp
  const isBefore = dateUtil(timeStamp).isBefore(currentTime);

  let diff = currentTime - timeStamp;
  if (!isBefore) {
    diff = -diff;
  }

  let resStr = '';

  if (diff < ONE_SECONDS) {
    resStr = '刚刚';
    // Less than or equal to 59 seconds
  } else if (diff < ONE_MINUTES) {
    resStr = parseInt(diff / ONE_SECONDS) + '秒';
    // More than 59 seconds, less than or equal to 59 minutes and 59 seconds
  } else if (diff >= ONE_MINUTES && diff < ONE_HOUR) {
    resStr = Math.floor(diff / ONE_MINUTES) + '分钟';
    // More than 59 minutes and 59 seconds, less than or equal to 23 hours, 59 minutes and 59 seconds
  } else if (diff >= ONE_HOUR && diff < ONE_DAY) {
    resStr = Math.floor(diff / ONE_HOUR) + '小时';
    // More than 23 hours, 59 minutes and 59 seconds, less than or equal to 29 days, 59 minutes and 59 seconds
  } else if (diff >= ONE_DAY && diff < 31567860000 * 1000 * 50) {
    resStr = Math.floor(diff / ONE_DAY) + '天';
  } else {
    resStr = dateUtil(timeStamp).format('MM-DD-HH-mm');
  }
  return resStr;
}
