export const warningTypeLabels = {
  WATER_PIPE: '供水管网',
  SEWER_PIPE: '排水管网',
  GAS_PIPE: '燃气管网',
  MANHOLE: '窨井',
  '供水': '供水管网',
  '供水管网': '供水管网',
  '供水管网预警': '供水管网',
  '排水': '排水管网',
  '排水管网': '排水管网',
  '排水管网预警': '排水管网',
  '燃气': '燃气管网',
  '燃气管网': '燃气管网',
  '燃气管网预警': '燃气管网',
  '窨井预警': '窨井'
}

// 业务范围固定为四类城市生命线设施；别名仅用于兼容历史数据，不在筛选器中重复展示。
export const warningTypeOptions = [
  { value: 'WATER_PIPE', label: '供水管网' },
  { value: 'SEWER_PIPE', label: '排水管网' },
  { value: 'GAS_PIPE', label: '燃气管网' },
  { value: 'MANHOLE', label: '窨井' }
]

export const statusLabels = {
  DRAFT: '草稿',
  PENDING: '待处置',
  PROCESSING: '处置中',
  RELEASED: '已发布',
  HANDLED: '已处置',
  CLOSED: '已解除',
  RESOLVED: '已解除'
}

export const disposalTypeLabels = {
  RELEASE: '发布处置',
  RESOLVE: '解除预警',
  RETURN: '退回重办',
  UPGRADE: '升级预警'
}

export function labelOf(map, value) {
  const legacyTypeLabels = { '1': '供水管网', '2': '排水管网', '3': '燃气管网', '4': '窨井' }
  const normalizedValue = value === undefined || value === null ? '' : String(value).toUpperCase()
  return map[value] || map[normalizedValue] || (map === warningTypeLabels ? legacyTypeLabels[String(value)] : undefined) || value || '未设置'
}

export function warningTypeLabel(value) {
  if (value === undefined || value === null || value === '') return '未设置'
  const legacyLabels = { '1': '供水管网', '2': '排水管网', '3': '燃气管网', '4': '窨井' }
  return warningTypeLabels[value] || legacyLabels[String(value)] || (Object.values(warningTypeLabels).includes(value) ? value : '未设置')
}

export function responseData(response, fallback = []) {
  return response?.data ?? fallback
}

export function rowsOf(response) {
  const data = responseData(response, {})
  return Array.isArray(data) ? data : data.records || []
}

export function totalOf(response) {
  const data = responseData(response, {})
  return Number(data.total || 0)
}

export function defaultRange(days = 30) {
  const end = new Date()
  const start = new Date(end.getTime() - days * 24 * 60 * 60 * 1000)
  return [formatDateTime(start), formatDateTime(end)]
}

export function formatDateTime(value) {
  const date = value instanceof Date ? value : new Date(value)
  const pad = number => String(number).padStart(2, '0')
  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`
}

export function rangeParams(range) {
  return {
    startTime: range?.[0] || undefined,
    endTime: range?.[1] || undefined
  }
}

export function safeNumber(value, digits = 2) {
  const number = Number(value)
  return Number.isFinite(number) ? number.toFixed(digits) : '-'
}
