/**
 * 日期管理类
 */
// padStart 的 polyfill，因为某些机型或情况，还无法支持es7的padStart，比如电脑版的微信小程序
// 所以这里做一个兼容polyfill的兼容处理
if (!String.prototype.padStart) {
  // 为了方便表示这里 fillString 用了ES6 的默认参数，不影响理解
  String.prototype.padStart = function(maxLength, fillString = ' ') {
    if (Object.prototype.toString.call(fillString) !== '[object String]') {
      throw new TypeError(
        'fillString must be String'
      )
    }
    const str = this
    // 返回 String(str) 这里是为了使返回的值是字符串字面量，在控制台中更符合直觉
    if (str.length >= maxLength) return String(str)

    const fillLength = maxLength - str.length
    let times = Math.ceil(fillLength / fillString.length)
    while (times >>= 1) {
      fillString += fillString
      if (times === 1) {
        fillString += fillString
      }
    }
    return fillString.slice(0, fillLength) + str
  }
}

export class DateManager {
  constructor() {}

  /**
   * 获取时间戳
   */
  getTimestamp = (time, type = 's') => {
    const now = time ? new Date(time) : new Date();
    let timeTamp = Date.parse(now);
    return (type === 'ms') ? timeTamp : timeTamp / 1000;
  }

  /**
   * 格式化时间
   * 其他更多是格式化有如下:
   * yyyy:mm:dd|yyyy:mm|yyyy年mm月dd日|yyyy年mm月dd日 hh时MM分等,可自定义组合
   * 
   * 来源：uview 2.0
   */
  format = (dateTime = null, formatStr = 'yyyy-mm-dd') => {
    let date
    // 若传入时间为假值，则取当前时间
    if (!dateTime) {
      date = new Date()
    }
    // 若为unix秒时间戳，则转为毫秒时间戳（逻辑有点奇怪，但不敢改，以保证历史兼容）
    else if (/^\d{10}$/.test(dateTime?.toString().trim())) {
      date = new Date(dateTime * 1000)
    }
    // 若用户传入字符串格式时间戳，new Date无法解析，需做兼容
    else if (typeof dateTime === 'string' && /^\d+$/.test(dateTime.trim())) {
      date = new Date(Number(dateTime))
    }
    // 处理平台性差异，在Safari/Webkit中，new Date仅支持/作为分割符的字符串时间
    // 处理 '2022-07-10 01:02:03'，跳过 '2022-07-10T01:02:03'
    else if (typeof dateTime === 'string' && dateTime.includes('-') && !dateTime.includes('T')) {
      date = new Date(dateTime.replace(/-/g, '/'))
    }
    // 其他都认为符合 RFC 2822 规范
    else {
      date = new Date(dateTime)
    }

    const timeSource = {
      'y': date.getFullYear().toString(), // 年
      'm': (date.getMonth() + 1).toString().padStart(2, '0'), // 月
      'd': date.getDate().toString().padStart(2, '0'), // 日
      'h': date.getHours().toString().padStart(2, '0'), // 时
      'M': date.getMinutes().toString().padStart(2, '0'), // 分
      's': date.getSeconds().toString().padStart(2, '0') // 秒
      // 有其他格式化字符需求可以继续添加，必须转化成字符串
    }

    for (const key in timeSource) {
      const [ret] = new RegExp(`${key}+`).exec(formatStr) || []
      if (ret) {
        // 年可能只需展示两位
        const beginIndex = key === 'y' && ret.length === 2 ? 2 : 0
        formatStr = formatStr.replace(ret, timeSource[key].slice(beginIndex))
      }
    }

    return formatStr
  }

  /**
   * @description 时间戳转为多久之前
   * @param {String|Number} timestamp 时间戳
   * @param {String|Boolean} format
   * 格式化规则如果为时间格式字符串，超出一定时间范围，返回固定的时间格式；
   * 如果为布尔值false，无论什么时间，都返回多久以前的格式
   * @returns {string} 转化后的内容
   * 
   * 来源：uview 2.0
   */
  from = (timestamp = null, format = 'yyyy-mm-dd') => {
    if (timestamp == null) timestamp = Number(new Date())
    timestamp = parseInt(timestamp)
    // 判断用户输入的时间戳是秒还是毫秒,一般前端js获取的时间戳是毫秒(13位),后端传过来的为秒(10位)
    if (timestamp.toString().length == 10) timestamp *= 1000
    let timer = (new Date()).getTime() - timestamp
    timer = parseInt(timer / 1000)
    // 如果小于5分钟,则返回"刚刚",其他以此类推
    let tips = ''
    switch (true) {
      case timer < 300:
        tips = '刚刚'
        break
      case timer >= 300 && timer < 3600:
        tips = `${parseInt(timer / 60)}分钟前`
        break
      case timer >= 3600 && timer < 86400:
        tips = `${parseInt(timer / 3600)}小时前`
        break
      case timer >= 86400 && timer < 2592000:
        tips = `${parseInt(timer / 86400)}天前`
        break
      default:
        // 如果format为false，则无论什么时间戳，都显示xx之前
        if (format === false) {
          if (timer >= 2592000 && timer < 365 * 86400) {
            tips = `${parseInt(timer / (86400 * 30))}个月前`
          } else {
            tips = `${parseInt(timer / (86400 * 365))}年前`
          }
        } else {
          tips = this.format(timestamp, format)
        }
    }
    return tips
  }

  /**
   * @description 日期的月或日补零操作
   * @param {String} value 需要补零的值
   * 
   * 来源：uview 2.0
   */
  padZero = (value) => {
    return `00${value}`.slice(-2)
  }

  /**
   * 获取昨天
   */
  yesterday = () => {
    let day = new Date();
    day.setTime(day.getTime() - 24 * 60 * 60 * 1000);
    let yesterday = day.getFullYear() + "-" + this.padZero((day.getMonth() + 1)) + "-" + this.padZero(day.getDate());
    return yesterday;
  }

  /**
   * 周日期
   */
  week = (operator = 1) => {
    let now = new Date()
    let nowTime = now.getTime()
    // getDay()返回0-6，其中0表示周日，需特殊处理
    let day = now.getDay() > 0 ? now.getDay() : 7 // 表示当前是周几
    let oneDayTime = 24 * 60 * 60 * 1000 // 一天的总ms
    // 周一时间戳
    let mondayTime = nowTime - (day - 1) * oneDayTime
    // 周日时间戳
    let sundayTime = nowTime + (7 - day) * oneDayTime
    if (operator < 0) {
      mondayTime = mondayTime - oneDayTime * (Math.abs(operator) * 7);
      sundayTime = sundayTime - oneDayTime * (Math.abs(operator) * 7);
    } else if (operator > 1) {
      mondayTime = mondayTime + oneDayTime * ((operator - 1) * 7);
      sundayTime = sundayTime + oneDayTime * ((operator - 1) * 7);
    }
    let mondayDate = this.format(mondayTime);
    let sundayDate = this.format(sundayTime);
    return [mondayDate, sundayDate];
  }

  // 月
  month = (operator = 1) => {
    let date = new Date();
    if (operator < 0) {
      let operatorValue = Math.abs(operator);
      date.setMonth(date.getMonth() - operatorValue);
    } else if (operator > 1) {
      date.setMonth(date.getMonth() - 1 + operator);
    }
    let year = date.getFullYear();
    let month = date.getMonth();
    // 日期
    let monthDate = new Date(year, month + 1, 0);
    // 日期的天数
    let monthDay = monthDate.getDate();
    // 年份
    let newYear = monthDate.getFullYear();
    // 月份
    let newMonth = monthDate.getMonth() + 1;
    newMonth = newMonth < 10 ? "0" + newMonth : newMonth;
    // 开始日期
    let startDate = newYear + "-" + newMonth + "-01"
    // 结束日期
    let endDate = newYear + "-" + newMonth + "-" + monthDay;
    return [startDate, endDate];
  }

  /**
   * 验证日期格式
   */
  isDate = (value, separator = "-") => {
    if (value == "") return false;
    if (typeof value !== 'string') return false;
    let valueArr = value.split(separator);
    if (valueArr.length != 3) return false;
    let intYear = parseInt(valueArr[0]);
    let intMonth = parseInt(valueArr[1]);
    let intDay = parseInt(valueArr[2]);
    if (isNaN(intYear) || isNaN(intMonth) || isNaN(intDay)) return false;
    if (intMonth > 12 || intMonth < 1) return false;
    if (intDay < 1 || intDay > 31) return false;
    if ((intMonth == 4 || intMonth == 6 || intMonth == 9 || intMonth == 11) && (intDay > 30)) return false;
    if (intMonth == 2) {
      if (intDay > 29) return false;
      if ((((intYear % 100 == 0) && (intYear % 400 != 0)) || (intYear % 4 != 0)) && (intDay > 28)) return false;
    }
    return true;
  }

  /**
   * 两个日期之间的天数
   * @param startDate 开始日期
   * @param endDate 结束日期日期
   */
  betweenDays = (startDate, endDate) => {
    let strSeparator = "-"; //日期分隔符
    let oDate1;
    let oDate2;
    let iDays;
    oDate1 = startDate.split(strSeparator);
    oDate2 = endDate.split(strSeparator);
    let strDateS = new Date(oDate1[0], oDate1[1] - 1, oDate1[2]);
    let strDateE = new Date(oDate2[0], oDate2[1] - 1, oDate2[2]);
    iDays = parseInt(Math.abs(strDateS - strDateE) / 1000 / 60 / 60 / 24) //把相差的毫秒数转换为天数
    return iDays;
  }

  /**
   * 某个月的天数
   * @param value 月份，格式：2023-05
   */
  monthDays = (value) => {
    let monthArr = value.split("-");
    let year = parseInt(monthArr[0]);
    let month = parseInt(monthArr[1], 10);
    let d = new Date(year, month, 0);
    return d.getDate();
  }

  /**
   * 两个日期之间的所有日期
   */
  betweenDates = (startDate, endDate) => {
    let result = [];
    let beginDay = startDate.split("-");
    let endDay = endDate.split("-");
    let diffDay = new Date();
    let dateList = new Array;
    let i = 0;
    diffDay.setDate(beginDay[2]);
    diffDay.setMonth(beginDay[1] - 1);
    diffDay.setFullYear(beginDay[0]);
    result.push(startDate);
    while (i == 0) {
      let countDay = diffDay.getTime() + 24 * 60 * 60 * 1000;
      diffDay.setTime(countDay);
      dateList[2] = diffDay.getDate();
      dateList[1] = diffDay.getMonth() + 1;
      dateList[0] = diffDay.getFullYear();
      if (String(dateList[1]).length == 1) {
        dateList[1] = "0" + dateList[1]
      };
      if (String(dateList[2]).length == 1) {
        dateList[2] = "0" + dateList[2]
      };
      result.push(dateList[0] + "-" + dateList[1] + "-" + dateList[2]);
      if (dateList[0] == endDay[0] && dateList[1] == endDay[1] && dateList[2] == endDay[2]) {
        i = 1;
      }
    };
    return result;
  }

  /**
   * 加多少天后的日期
   */
  addDay = (day) => {
    let date = new Date();
    date.setTime(date.getTime() + 24 * 60 * 60 * 1000 * day);
    let dateFormat = date.getFullYear() + "-" + this.padZero((date.getMonth() + 1)) + "-" + this.padZero(date.getDate());
    return dateFormat;
  }

  /**
   * 减多少天后的日期
   */
  reduceDay = (day) => {
    let date = new Date();
    date.setTime(date.getTime() - 24 * 60 * 60 * 1000 * day);
    let dateFormat = date.getFullYear() + "-" + this.padZero((date.getMonth() + 1)) + "-" + this.padZero(date.getDate());
    return dateFormat;
  }
}