/*
 * @Author: Jensonhui
 * @Date: 2023-08-27 14:21:56
 * @Description: 时间函数工具
 */
import BigNumber from "bignumber.js";

// 格式化date 【2023-08】
export function formatDate(date, flag) {
  const isDate = new Date(date);
  const years = isDate.getFullYear();
  const months = isDate.getMonth() + 1;

  const pad = (n) => (n < 10 ? `0${n}` : n);
  return `${years}${flag ? "/" : "-"}${pad(months)}`;
}

export function createBigNum(value) {
  return new BigNumber(value);
}

// 获取年月时间戳
export function getYearMouthTimestamp(year, month) {
  const date = new Date();

  // 设置年份和月份
  date.setFullYear(year);
  date.setMonth(parseInt(month) - 1); // 月份从 0 开始,所以需要减去 1

  return date.getTime();
}

// 计算时间区间, dateValue必须xxxx-xx格式
export function computedDateRangeFn(dateValue, { newTime, oldTime, maxTime, minTime }) {
  let result = {
    isOldMonth: false,
    isNewMonth: false,
    isRangeMonth: false
  };

  try {
    let maxStamp = null,
      minStamp = null;
    let newStamp = null,
      oldStamp = null;

    const [year, month] = dateValue.split("-");
    const stamp = createBigNum(getYearMouthTimestamp(year, month));

    // 新旧时间
    if (newTime) {
      const [newYear, newMonth] = newTime || [];
      newStamp = createBigNum(getYearMouthTimestamp(newYear, newMonth));
      result.isNewMonth = stamp.isGreaterThanOrEqualTo(newStamp);
    }

    if (oldTime) {
      const [oldYear, oldMonth] = oldTime || [];
      oldStamp = createBigNum(getYearMouthTimestamp(oldYear, oldMonth));
      result.isOldMonth = stamp.isLessThanOrEqualTo(oldStamp);
    }

    // 区间
    if (maxTime && minTime) {
      const [maxYear, maxMonth] = maxTime || [];
      const [minYear, minMonth] = minTime || [];

      maxStamp = createBigNum(getYearMouthTimestamp(maxYear, maxMonth));
      minStamp = createBigNum(getYearMouthTimestamp(minYear, minMonth));
      result.isRangeMonth =
        stamp.isGreaterThanOrEqualTo(minStamp) && stamp.isLessThanOrEqualTo(maxStamp);
    }

    return result;
  } catch (e) {
    return result;
  }
}