// 时间戳转换为年月日时分秒
export const timesTampChange = (timestamp, format = 'Y-M-D h:m:s') => {
  if (!timestamp) return ''
  const date = new Date(timestamp)
  const Y = date.getFullYear().toString()
  const M = (date.getMonth() + 1).toString().padStart(2, '0')
  const D = date.getDate().toString().padStart(2, '0')

  const h = date.getHours().toString().padStart(2, '0')
  const m = date.getMinutes().toString().padStart(2, '0')
  const s = date.getSeconds().toString().padStart(2, '0')

  const formatter = { 'Y': Y, 'M': M, 'D': D, 'h': h, 'm': m, 's': s } // 替换format中的占位符
  let formattedDate = format.replace(/Y|M|D|h|m|s/g, matched => formatter[matched]) // 使用正则表达式匹配并替换占位符
  
  if (!formattedDate) formattedDate = Y + '-' + M + '-' + D + ' ' + h + ':' + m + ':' + s

  return formattedDate
}

// 将 Wed May 01 2024 00:00:00 GMT+0800 (中国标准时间) 转换为时间戳
export const getTimeStamp = (str) => {
  if (!str) return ''
  const date = new Date(str)
  return date.getTime()
}

// 传入一个时间戳返回这个日期的最早时间点以及最晚时间点 输出：[1721232000000, 1721318399999]
export const getDayBounds = (timestamp) => {
  const date = new Date(timestamp)
  date.setHours(0, 0, 0, 0)
  const startOfDay = date.getTime()
  const endOfDay = new Date(timestamp)
  endOfDay.setHours(23, 59, 59, 999)
  if (endOfDay.getDate() !== date.getDate()) {
    endOfDay.setDate(endOfDay.getDate() - 1)
    endOfDay.setHours(23, 59, 59, 999)
  }
  // 返回包含最早和最晚时间点的时间戳的数组
  return [startOfDay, endOfDay.getTime()]
}

// 传入 Wed May 01 2024 00:00:00 GMT+0800 (中国标准时间) 输出 [2024-07-18 00:00:00, 2024-07-18 23:59:59]
export const getStartAndEndOfDay = (dateTimeStr) => {
  const date = new Date(dateTimeStr)

  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')

  const startTime = `${year}-${month}-${day} 00:00:00`
  const endTime = `${year}-${month}-${day} 23:59:59`
  return [startTime, endTime]
}

// 传入一组时间戳，返回 [最早时间点，最晚时间点]
export const  convertTimestampsToDayRange = (timestamps) => {
  if (timestamps.length < 2) {
    throw new Error('Timestamps array must contain at least two elements')
  }
  function formatDate(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    const seconds = String(date.getSeconds()).padStart(2, '0')
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  }

  const startDate = new Date(timestamps[0])
  const endDate = new Date(timestamps[1])

  const startOfDay = new Date(startDate.getFullYear(), startDate.getMonth(), startDate.getDate())

  const endOfDay = new Date(endDate.getFullYear(), endDate.getMonth(), endDate.getDate() + 1, 0, 0, 0, -1)

  return [formatDate(startOfDay), formatDate(endOfDay)]
}