function finiteCoordinate(value) {
  if (value === null || value === undefined || value === '') return null
  const coordinate = Number(value)
  return Number.isFinite(coordinate) ? coordinate : null
}

function featureIdentity(feature, properties) {
  return {
    id: properties.id ?? feature.id,
    featureId: feature.id,
    type: properties.facilityType || properties.type || '',
    name: properties.facilityName || properties.name || properties.pipeName || properties.facilityTypeName || '供水设施',
    code: properties.facilityCode || properties.code || properties.pipeCode || '-',
    status: properties.status,
    road: properties.road || properties.address || properties.location || '',
    raw: feature
  }
}

export function buildFacilityMapModel(collection = {}) {
  const points = []
  const lines = []

  for (const feature of Array.isArray(collection.features) ? collection.features : []) {
    const properties = feature.properties || {}
    const identity = featureIdentity(feature, properties)
    const coordinates = feature.geometry?.coordinates

    if (feature.geometry?.type === 'Point' && Array.isArray(coordinates)) {
      const lng = finiteCoordinate(coordinates[0])
      const lat = finiteCoordinate(coordinates[1])
      if (lng === null || lat === null) continue
      points.push({
        ...identity,
        address: properties.address || properties.location || '',
        lng,
        lat
      })
    }

    if (feature.geometry?.type === 'LineString' && Array.isArray(coordinates) && coordinates.length >= 2) {
      const linePoints = coordinates.map(pair => ({
        lng: finiteCoordinate(pair?.[0]),
        lat: finiteCoordinate(pair?.[1])
      }))
      if (linePoints.some(point => point.lng === null || point.lat === null)) continue
      lines.push({
        ...identity,
        type: identity.type || 'pipe',
        material: properties.pipeMaterial,
        diameter: properties.pipeDiameter,
        startPoint: properties.startPoint,
        endPoint: properties.endPoint,
        layingYear: properties.layingYear,
        length: properties.pipeLength,
        points: linePoints
      })
    }
  }

  return { points, lines }
}

export function filterFacilityMapModel(model = {}, enabledTypes = {}) {
  const points = (model.points || []).filter(item => enabledTypes[item.type] !== false)
  const lines = (model.lines || []).filter(item => enabledTypes[item.type] !== false)
  return { points, lines, isEmpty: points.length === 0 && lines.length === 0 }
}

export function findFacilityFeature(model = {}, keyword = '') {
  const normalized = String(keyword).trim().toLocaleLowerCase()
  if (!normalized) return null
  const items = [
    ...(model.points || []).map(item => ({ ...item, kind: 'point' })),
    ...(model.lines || []).map(item => {
      const first = item.points[0]
      const last = item.points[item.points.length - 1]
      const midpoint = {
        lng: Number(((first.lng + last.lng) / 2).toFixed(8)),
        lat: Number(((first.lat + last.lat) / 2).toFixed(8))
      }
      return { ...item, kind: 'pipeline', lng: midpoint.lng, lat: midpoint.lat }
    })
  ]
  return items.find(item => [item.name, item.code, item.road]
    .some(value => String(value || '').toLocaleLowerCase().includes(normalized))) || null
}
