import { parseTime } from '@/utils/ruoyi';

/**
 * 计算周年
 */
export function calcFullYear(date) {
  if (date == null ) {
    return 0;
  }
  let start = toDate(date);
  let end = new Date();

  return Math.floor((end.getTime() - start.getTime()) / 31536000000)
}

/**
 * 计算年龄
 */
export function calcBirthDay(birthday) {
  if (birthday === null) {
    return 0;
  }
  let now = new Date();
  let start = toDate(birthday);

  return now.getFullYear() - start.getFullYear() + 1;
}

/**
 * 转为日期
 */
export function toDate(data) {
  let date = data;
  if (typeof date === 'string') {
    date = new Date(data);
  }
  return date;
}

/**
 * 计算两个时间相差多少秒
 */
export function calcSecond(start, end) {
  if (start == null || end == null) {
    return 0;
  }
  let startDate = toDate(start);
  let endDate = toDate(end);
  return Math.floor((endDate.getTime() - startDate.getTime()) / 1000);
}



// 获取前n天的日期
export function getLastDate(n) {
  let now = new Date();
  return new Date(now.getTime() - n * 24 * 3600 * 1000)
}

// 获取前n月的日期
export function getLastMonth(n) {
  const date = new Date();
  const year = date.getFullYear();
  const month = date.getMonth();
  const day = date.getDate();

  // 减去 n 个月
  date.setMonth(month - n);

  // 确保日期不超过当月的最大天数
  const maxDay = new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate();
  date.setDate(Math.min(day, maxDay));

  return date;
}

// 获取前n月的日期字符串
export function getLastMonthDateStr(n) {
  let date = getLastMonth(n);
  return parseTime(date, "{y}-{m}-{d}")
}

// 获取前n天的日期字符串
export function getLastDateStr(n) {
  let date = getLastDate(n);
  return parseTime(date, "{y}-{m}-{d}");
}

// 获取前n天的日期时间字符串00:00:00
export function getLastDateTimeStartStr(n) {
  let date = getLastDate(n);
  return parseTime(date, "{y}-{m}-{d} 00:00:00");
}

// 获取前n天的日期时间字符串23:59:59
export function getLastDateTimeEndStr(n) {
  let date = getLastDate(n);
  return parseTime(date, "{y}-{m}-{d} 23:59:59");
}

// 获取前n天的日期时间00:00:00
export function getLastDateTimeStart(n) {
  return new Date(getLastDateTimeStartStr(n));
}

// 获取前n天的日期时间23:59:59
export function getLastDateTimeEnd(n) {
  return new Date(getLastDateTimeEndStr(n));
}
