/**
 * 应急点选择算法 Composable
 * 负责从应急点中选择最近的 N 个点
 */

import { calculateDistance, isValidCoordinate } from '../utils/geoUtils'

export function useEmergencyRouteSelection() {
  /**
   * 按直线距离选择最近的 N 个点
   * @param {Object} center - 中心点 { lon, lat }
   * @param {Array} points - 应急点数组
   * @param {number} count - 选择数量
   * @returns {Array} 选中的应急点数组
   */
  const selectNearestPoints = (center, points, count) => {
    if (!center || !points || points.length === 0) {
      console.warn('[useEmergencyRouteSelection] 参数无效')
      return []
    }

    // 验证中心点坐标
    if (!isValidCoordinate(center)) {
      console.error('[useEmergencyRouteSelection] 中心点坐标无效:', center)
      return []
    }

    // 过滤并计算距离
    const validPoints = points
      .filter(point => {
        // 确保点有坐标
        const hasCoords = point.lon != null && point.lat != null

        if (!hasCoords) {
          console.warn('[useEmergencyRouteSelection] 点缺少坐标:', point)
          return false
        }

        // 验证坐标有效性
        if (!isValidCoordinate({ lon: point.lon, lat: point.lat })) {
          console.warn('[useEmergencyRouteSelection] 点坐标无效:', point)
          return false
        }

        return true
      })
      .map(point => {
        const distance = calculateDistance(center, { lon: point.lon, lat: point.lat })

        return {
          ...point,
          distance: distance // 公里
        }
      })

    // 按距离排序
    const sorted = validPoints.sort((a, b) => a.distance - b.distance)

    // 选择前 N 个
    const selected = sorted.slice(0, count)

    console.log(`[useEmergencyRouteSelection] 从 ${points.length} 个点中选择了 ${selected.length} 个最近的点`)

    return selected
  }

  /**
   * 按类型分别选择应急点
   * @param {Object} center - 中心点
   * @param {Array} points - 应急点数组
   * @param {Object} config - 配置 { personnelCount, equipmentCount }
   * @returns {Object} { personnel: [], equipment: [] }
   */
  const selectByType = (center, points, config = {}) => {
    const { personnelCount = 3, equipmentCount = 2 } = config

    console.log(`[useEmergencyRouteSelection] 选择应急点: 人员=${personnelCount}, 装备=${equipmentCount}`)

    // 根据 API 数据结构推断类型
    // lx: 1 = 应急基地（人员）
    // lx: 2 = 储备中心（装备）
    const personnel = points.filter(p => {
      // 优先使用 type 字段
      if (p.type === 'soldier' || p.type === 'personnel') {
        return true
      }

      // 其次使用 lx 字段
      if (p.lx === 1) {
        return true
      }

      // 最后使用 category 字段
      if (p.category && (p.category.includes('人员') || p.category.includes('基地'))) {
        return true
      }

      return false
    })

    const equipment = points.filter(p => {
      // 优先使用 type 字段
      if (p.type === 'device' || p.type === 'equipment') {
        return true
      }

      // 其次使用 lx 字段
      if (p.lx === 2) {
        return true
      }

      // 最后使用 category 字段
      if (p.category && (p.category.includes('装备') || p.category.includes('物资') || p.category.includes('储备'))) {
        return true
      }

      return false
    })

    console.log(`[useEmergencyRouteSelection] 分类结果: 人员=${personnel.length}, 装备=${equipment.length}`)

    // 如果分类失败，尝试平均分配
    if (personnel.length === 0 && equipment.length === 0 && points.length > 0) {
      console.warn('[useEmergencyRouteSelection] 无法分类，使用平均分配策略')

      const totalCount = personnelCount + equipmentCount
      const allSelected = selectNearestPoints(center, points, totalCount)

      return {
        personnel: allSelected.slice(0, personnelCount).map(p => ({ ...p, type: 'personnel' })),
        equipment: allSelected.slice(personnelCount).map(p => ({ ...p, type: 'equipment' }))
      }
    }

    // 分别选择最近的点
    const selectedPersonnel = selectNearestPoints(center, personnel, personnelCount)
    const selectedEquipment = selectNearestPoints(center, equipment, equipmentCount)

    // 确保类型字段正确
    return {
      personnel: selectedPersonnel.map(p => ({ ...p, type: 'personnel' })),
      equipment: selectedEquipment.map(p => ({ ...p, type: 'equipment' }))
    }
  }

  /**
   * 按距离排序点
   * @param {Object} center - 中心点
   * @param {Array} points - 点数组
   * @returns {Array} 排序后的点数组
   */
  const sortByDistance = (center, points) => {
    return points
      .map(point => ({
        ...point,
        distance: calculateDistance(center, { lon: point.lon, lat: point.lat })
      }))
      .sort((a, b) => a.distance - b.distance)
  }

  /**
   * 两阶段选择：先直线距离预筛选，再路线距离精确选择
   * @param {Object} center - 中心点
   * @param {Array} points - 应急点数组
   * @param {number} finalCount - 最终选择数量
   * @param {number} candidateMultiplier - 候选倍数（默认2倍）
   * @returns {Array} 候选点数组
   */
  const selectCandidates = (center, points, finalCount, candidateMultiplier = 2) => {
    const candidateCount = finalCount * candidateMultiplier

    console.log(`[useEmergencyRouteSelection] 两阶段选择: 最终=${finalCount}, 候选=${candidateCount}`)

    return selectNearestPoints(center, points, candidateCount)
  }

  return {
    selectNearestPoints,
    selectByType,
    sortByDistance,
    selectCandidates
  }
}

export default useEmergencyRouteSelection
