import { getGisAccessToken, getGisBaseUrl, getGisDefaultCenter } from './gisLoader'

/** GIS POI 接口成功状态码 */
const POI_STATUS_OK = 2000

/** POI 查询方式：1=中心点周边，2=多边形区域（默认） */
export const GIS_POI_SEARCH_MODE = {
  NEARBY: 1,
  POLYGON: 2
}

/** 巴青大屏 POI 多边形范围（[经度, 纬度]） */
export const BA_QING_POI_POLYGON = [
  [94.039551, 31.927503],
  [94.061348, 31.922841],
  [94.058913, 31.916612],
  [94.038479, 31.922559]
]

/**
 * 读取 POI 搜索模式（VITE_GIS_POI_SEARCH_MODE：1 中心点，2 多边形，默认 2）
 */
export function getGisPoiSearchMode() {
  const n = Number(import.meta.env.VITE_GIS_POI_SEARCH_MODE)
  return n === GIS_POI_SEARCH_MODE.NEARBY ? GIS_POI_SEARCH_MODE.NEARBY : GIS_POI_SEARCH_MODE.POLYGON
}

/**
 * 解析 POI location 字段（文档格式：纬度,经度）为地图坐标 [经度, 纬度]
 */
export function parsePoiLngLat(location) {
  if (!location || typeof location !== 'string') {
    return null
  }
  const parts = location.split(',').map((n) => Number(String(n).trim()))
  if (parts.length < 2 || !parts.every((n) => Number.isFinite(n))) {
    return null
  }
  const [lat, lng] = parts
  return [lng, lat]
}

/**
 * 将 [lng, lat] 顶点列表转为接口 polygon 参数（纬度,经度；首尾闭合）
 */
export function formatPolygonParam(points) {
  if (!Array.isArray(points) || points.length < 3) {
    return ''
  }
  const ring = points.map(([lng, lat]) => [Number(lng), Number(lat)])
  const [firstLng, firstLat] = ring[0]
  const [lastLng, lastLat] = ring[ring.length - 1]
  if (firstLng !== lastLng || firstLat !== lastLat) {
    ring.push([firstLng, firstLat])
  }
  return ring.map(([lng, lat]) => `${lat},${lng}`).join(';')
}

function normalizePoiList(data) {
  if (data?.status !== POI_STATUS_OK || !Array.isArray(data?.body?.pois)) {
    return []
  }
  return data.body.pois
    .map((row) => row?.poi || row)
    .filter((poi) => poi && typeof poi === 'object')
}

/**
 * 周边搜索（GIS 接口文档 §2.2 /agis/search/v1/pois/region）
 * @param {{ center?: [number, number], radius?: number, pageNum?: number, pageSize?: number }} [options]
 */
export async function searchNearbyPois(options = {}) {
  const base = getGisBaseUrl()
  const key = getGisAccessToken()
  if (!base || !key) {
    return []
  }

  const center = options.center || getGisDefaultCenter()
  const [longitude, latitude] = center
  const radius = options.radius ?? 5000
  const pageNum = options.pageNum ?? 1
  const pageSize = options.pageSize ?? 1000

  const params = new URLSearchParams({
    longitude: String(longitude),
    latitude: String(latitude),
    radius: String(radius),
    page_num: String(pageNum),
    page_size: String(pageSize),
    key
  })

  const url = `${base}/agis/search/v1/pois/region?${params.toString()}`
  const res = await fetch(url)
  if (!res.ok) {
    return []
  }

  return normalizePoiList(await res.json())
}

/**
 * 多边形区域搜索（GIS 接口文档 §2.3 /agis/search/v1/pois/polygon）
 * @param {{ polygon?: [number, number][], pageNum?: number, pageSize?: number }} [options]
 */
export async function searchPolygonPois(options = {}) {
  const base = getGisBaseUrl()
  const key = getGisAccessToken()
  if (!base || !key) {
    return []
  }

  const points = options.polygon || BA_QING_POI_POLYGON
  const polygon = formatPolygonParam(points)
  if (!polygon) {
    return []
  }

  const params = new URLSearchParams({
    polygon,
    page_num: String(options.pageNum ?? 1),
    page_size: String(options.pageSize ?? 1000),
    key
  })

  const url = `${base}/agis/search/v1/pois/polygon?${params.toString()}`
  const res = await fetch(url)
  if (!res.ok) {
    return []
  }

  return normalizePoiList(await res.json())
}

/**
 * 按 VITE_GIS_POI_SEARCH_MODE 自动选择 POI 搜索方式
 * @param {{ center?: [number, number], polygon?: [number, number][], radius?: number, pageNum?: number, pageSize?: number }} [options]
 */
export async function searchPois(options = {}) {
  if (getGisPoiSearchMode() === GIS_POI_SEARCH_MODE.NEARBY) {
    return searchNearbyPois(options)
  }
  return searchPolygonPois(options)
}
