/**
 * 日期工具类
 */
export default class DateTools {
  static instance = new DateTools()

  constructor () {
    if (DateTools.instance) {
      return DateTools.instance
    }
    DateTools.instance = this
  }

  static getInstance () {
    if (!DateTools.instance) {
      DateTools.instance = new DateTools()
    }
    return DateTools.instance
  }

  /**
   * 获取当前时间
   * @returns {string} yyyy-MM-dd HH:mm:ss
   */
  getNow2 () {
    const now = new Date()
    const year = now.getFullYear()
    const month = String(now.getMonth() + 1).padStart(2, '0') // 月份从 0 开始，所以要 +1
    const day = String(now.getDate()).padStart(2, '0')
    const hours = String(now.getHours()).padStart(2, '0')
    const minutes = String(now.getMinutes()).padStart(2, '0')
    const seconds = String(now.getSeconds()).padStart(2, '0')
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  }

  /**
   * 延迟指定毫秒
   * @param {number} ms 延迟毫秒数
   * @param {Object} [config] 可选配置
   * @param {AbortSignal} [config.signal] AbortSignal，用于支持取消延迟
   * @returns {Promise}
   */
  async delay (ms, config) {
    let signal = config?.signal
    if (!signal) {
      try {
        const LogicRunner = (await import('../../LogicRunner')).default
        signal = LogicRunner?.getCurrentAbortSignal?.()
      } catch (e) {
        // 忽略导入错误
      }
    }
    if (signal?.aborted) {
      const err = new Error('delay aborted')
      err.name = 'AbortError'
      return Promise.reject(err)
    }
    return new Promise((resolve, reject) => {
      const timeoutId = setTimeout(resolve, ms)
      if (signal) {
        signal.addEventListener('abort', () => {
          clearTimeout(timeoutId)
          const err = new Error('delay aborted')
          err.name = 'AbortError'
          reject(err)
        })
      }
    })
  }
}
