import * as Cesium from 'cesium'
import { cartesianToDegrees } from '@/map/utils/utils'

// deps: { viewerOrThrow, getLayers }
export function createQueryService(deps) {
  const { viewerOrThrow, getLayers } = deps

  return {
    /**
     * 获取屏幕像素位置对应的地理坐标（经纬度/高度）。
     * clamp: 默认 true，优先使用 pickPosition（贴地），失败时回退到椭球体。
     */
    getCoordinateAtScreenPosition(x, y, clamp) {
      const viewer = viewerOrThrow()
      const scene = viewer.scene
      const screenPoint = new Cesium.Cartesian2(x, y)
      let cartesian = null
      const clampToSurface = clamp !== false
      if (clampToSurface && scene.pickPositionSupported) {
        try {
          cartesian = scene.pickPosition(screenPoint)
        } catch (e) {}
      }
      if (!cartesian) cartesian = viewer.camera.pickEllipsoid(screenPoint, scene.globe.ellipsoid)
      if (!cartesian) return null
      return cartesianToDegrees(cartesian)
    },

    /**
     * 在屏幕坐标拾取实体，并返回实体 id 与所在图层 id（若可判定）。
     */
    pickEntityAt(x, y) {
      const viewer = viewerOrThrow()
      const picked = viewer.scene.pick(new Cesium.Cartesian2(x, y))
      if (!picked || !picked.id) return null
      const entity = picked.id
      let layerId = null
      const layers = getLayers()
      for (const id in layers) {
        const layerRecord = layers[id]
        if (
          (layerRecord.type === 'vector' || layerRecord.type === 'datasource') &&
          layerRecord.obj.entities &&
          layerRecord.obj.entities.contains &&
          layerRecord.obj.entities.contains(entity)
        ) {
          layerId = id
          break
        }
      }
      return { entityId: entity.id || entity.name || null, layerId }
    },

    cartesianToDegrees,
    degreesToCartesian(lon, lat, height) {
      const h = typeof height === 'number' ? height : 0
      return Cesium.Cartesian3.fromDegrees(lon, lat, h)
    },
  }
}
