import { warningTypeLabel } from '../lstatistics/statisticsShared'

export const warningLevelLabels = {
  // 预警级别编码遵循国家常用颜色规范：1 蓝、2 黄、3 橙、4 红。
  '1': '蓝色（IV级）',
  '2': '黄色（III级）',
  '3': '橙色（II级）',
  '4': '红色（I级）',
  I: '红色（I级）',
  II: '橙色（II级）',
  III: '黄色（III级）',
  IV: '蓝色（IV级）',
  RED: '红色',
  ORANGE: '橙色',
  YELLOW: '黄色',
  BLUE: '蓝色'
}

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

export function dashboardData(response, fallback = {}) {
  return response?.data ?? fallback
}

export function pageRecords(response) {
  const data = dashboardData(response, {})
  if (Array.isArray(data)) return data
  return data.records || data.list || []
}

export function pageTotal(response) {
  const data = dashboardData(response, {})
  return Number(data.total ?? data.totalCount ?? 0)
}

export function listValue(row, ...keys) {
  for (const key of keys) {
    if (row?.[key] !== undefined && row?.[key] !== null && row?.[key] !== '') return row[key]
  }
  return ''
}

export function warningTypeText(row) {
  return warningTypeLabel(listValue(row, 'warningTypeName', 'warning_type_name', 'warningType', 'warning_type'))
}

export function isSupportedWarningType(row) {
  return ['供水管网', '排水管网', '燃气管网', '窨井'].includes(warningTypeText(row))
}

export function warningLevelText(row) {
  const value = listValue(row, 'warningLevel', 'warning_level')
  return warningLevelLabels[String(value)] || value || '未设置'
}

export function warningLevelCode(row) {
  const value = String(listValue(row, 'warningLevel', 'warning_level')).toUpperCase()
  if (['4', 'I', 'RED'].includes(value)) return '4'
  if (['3', 'II', 'ORANGE'].includes(value)) return '3'
  if (['2', 'III', 'YELLOW'].includes(value)) return '2'
  if (['1', 'IV', 'BLUE'].includes(value)) return '1'
  return ''
}

export function warningStatusText(row) {
  const value = listValue(row, 'status', 'warningStatus', 'warning_status')
  const normalizedValue = String(value || '').toUpperCase()
  return warningStatusLabels[normalizedValue] || value || '未设置'
}

export function warningLevelTag(row) {
  const value = warningLevelCode(row)
  if (value === '4') return 'danger'
  if (value === '3' || value === '2') return 'warning'
  if (value === '1') return 'primary'
  return 'info'
}

export function warningStatusTag(row) {
  const value = String(listValue(row, 'status', 'warningStatus', 'warning_status')).toUpperCase()
  if (['CLOSED', 'RESOLVED', 'HANDLED'].includes(value)) return 'success'
  if (['PENDING', 'PROCESSING'].includes(value)) return 'warning'
  if (value === 'DRAFT') return 'info'
  return 'primary'
}

export function formatDashboardTime(value, fallback = '-') {
  if (!value) return fallback
  const date = value instanceof Date ? value : new Date(value)
  if (Number.isNaN(date.getTime())) return String(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 detailView(row = {}) {
  return {
    warningId: listValue(row, 'warningId', 'warning_id'),
    warningNo: listValue(row, 'warningNo', 'warning_no'),
    warningName: listValue(row, 'warningName', 'warning_name') || '未命名预警',
    warningType: warningTypeText(row),
    warningLevel: warningLevelText(row),
    warningSpecial: listValue(row, 'warningSpecial', 'warning_special') || '未设置',
    location: listValue(row, 'location') || '未设置',
    ownershipUnit: listValue(row, 'ownershipUnit', 'ownership_unit') || '未设置',
    publisher: listValue(row, 'publisher') || '未设置',
    publishTime: formatDashboardTime(listValue(row, 'publishTime', 'publish_time'), '未设置'),
    createTime: formatDashboardTime(listValue(row, 'createTime', 'create_time'), '未设置'),
    status: warningStatusText(row),
    warningContent: listValue(row, 'warningContent', 'warning_content') || '暂无预警描述',
    todoInfo: row.todoInfo || row.todo_info || null
  }
}

export function filterRows(rows, keyword) {
  const value = String(keyword || '').trim().toLowerCase()
  if (!value) return rows || []
  return (rows || []).filter(row => {
    const detail = detailView(row)
    return [detail.warningName, detail.warningSpecial, detail.location, detail.ownershipUnit, detail.warningType]
      .some(item => String(item).toLowerCase().includes(value))
  })
}
