export function unwrapResponse(response) {
  return response && Object.prototype.hasOwnProperty.call(response, 'data') ? response.data : response
}

export function normalizePage(response) {
  const page = unwrapResponse(response) || {}
  const records = page.records || page.rows || (Array.isArray(page) ? page : [])
  return {
    records: Array.isArray(records) ? records : [],
    total: Number(page.total ?? records.length) || 0,
    current: Number(page.current ?? page.pageNum ?? 1) || 1,
    size: Number(page.size ?? page.pageSize ?? (records.length || 10)) || 10
  }
}

export function normalizeMonitoringTypeName(record = {}, fallback = '-') {
  const candidate = record.equipmentTypeName ?? record.typeName ?? record.deviceType ?? record.equipmentType
  const normalized = candidate == null ? '' : String(candidate).trim()
  return normalized || String(fallback || '-').trim() || '-'
}
export function normalizeMonitoringRecord(record = {}, metric = 'value', monitorType = '') {
  const metricValue = metric === 'flow'
    ? record.instantFlow
    : metric === 'pressure'
      ? record.pressureValue
      : undefined
  const value = record[metric] ?? metricValue ?? record.currentValue ?? record.value ?? record.monitorValue
  return {
    ...record,
    id: record.id ?? record.equipmentId ?? record.pointId,
    equipmentName: record.equipmentName ?? record.name ?? record.deviceName ?? '未命名设备',
    equipmentCode: record.equipmentCode ?? record.deviceCode ?? record.code ?? '-',
    equipmentTypeName: normalizeMonitoringTypeName(record, monitorType),
    location: record.equipmentLocation ?? record.location ?? record.address ?? '-',
    value: value == null || value === '' ? null : Number(value),
    unit: record.unit ?? (metric === 'pressure' ? 'MPa' : metric === 'power' ? 'kW' : 'm³/h'),
    status: record.status ?? record.onlineStatus ?? record.alarmStatus ?? 0,
    updateTime: record.updateTime ?? record.monitorTime ?? record.createTime ?? record.time ?? '-'
  }
}

export async function readMonitoringExportError(blob) {
  if (!blob || blob.type !== 'application/json') return null
  try {
    const payload = JSON.parse(await blob.text())
    return payload?.msg || payload?.message || '导出失败，请稍后重试'
  } catch (error) {
    return '导出失败：服务端返回了无法解析的错误信息'
  }
}

export function normalizeGeoJson(response) {
  const data = unwrapResponse(response)
  if (data && data.type === 'FeatureCollection') return data
  if (Array.isArray(data)) return { type: 'FeatureCollection', features: data }
  return { type: 'FeatureCollection', features: [] }
}

export function normalizeMapPoints(points = []) {
  const valid = (Array.isArray(points) ? points : []).map(point => ({
    ...point,
    _longitude: Number(point.longitude ?? point.lng),
    _latitude: Number(point.latitude ?? point.lat)
  })).filter(point => Number.isFinite(point._longitude) && Number.isFinite(point._latitude))
  if (!valid.length) return []
  const longitudes = valid.map(point => point._longitude)
  const latitudes = valid.map(point => point._latitude)
  const minLongitude = Math.min(...longitudes)
  const maxLongitude = Math.max(...longitudes)
  const minLatitude = Math.min(...latitudes)
  const maxLatitude = Math.max(...latitudes)
  const longitudeSpan = maxLongitude - minLongitude
  const latitudeSpan = maxLatitude - minLatitude
  return valid.map(({ _longitude, _latitude, ...point }) => ({
    ...point,
    mapX: longitudeSpan ? Math.round((6 + ((_longitude - minLongitude) / longitudeSpan) * 88) * 100) / 100 : 50,
    mapY: latitudeSpan ? Math.round((90 - ((_latitude - minLatitude) / latitudeSpan) * 82) * 100) / 100 : 50
  }))
}
