const DATE_TIME_FORMAT = 'YYYY-MM-DD HH:mm:ss'

function pad(value) {
  return String(value).padStart(2, '0')
}

export function formatMonitoringDateTime(value) {
  if (value == null || value === '') return undefined
  if (value instanceof Date) {
    return `${value.getFullYear()}-${pad(value.getMonth() + 1)}-${pad(value.getDate())} ${pad(value.getHours())}:${pad(value.getMinutes())}:${pad(value.getSeconds())}`
  }
  const text = String(value).trim()
  return text || undefined
}

function hasValue(value) {
  return value !== undefined && value !== null && value !== ''
}

function numberOrNull(value) {
  return hasValue(value) && Number.isFinite(Number(value)) ? Number(value) : undefined
}

export function buildMonitoringQuery(query = {}, minKey = 'flowMin', maxKey = 'flowMax') {
  const timeRange = Array.isArray(query.timeRange) ? query.timeRange : []
  const result = {
    pageNum: query.pageNum ?? 1,
    pageSize: query.pageSize ?? 10,
    equipmentName: hasValue(query.equipmentName) ? query.equipmentName : undefined,
    equipmentCode: hasValue(query.equipmentCode) ? query.equipmentCode : undefined,
    equipmentLocation: hasValue(query.equipmentLocation) ? query.equipmentLocation : undefined,
    startTime: formatMonitoringDateTime(timeRange[0]),
    endTime: formatMonitoringDateTime(timeRange[1]),
    [minKey]: numberOrNull(query[minKey]),
    [maxKey]: numberOrNull(query[maxKey])
  }
  return Object.fromEntries(Object.entries(result).filter(([, value]) => hasValue(value)))
}

export function buildTrendQuery(timeRange = []) {
  const range = Array.isArray(timeRange) ? timeRange : []
  return Object.fromEntries(Object.entries({
    startTime: formatMonitoringDateTime(range[0]),
    endTime: formatMonitoringDateTime(range[1])
  }).filter(([, value]) => hasValue(value)))
}

export { DATE_TIME_FORMAT }
