/**
 * 高德地图路由 Composable
 * 负责路径规划和坐标转换
 */

import { ref } from 'vue'
import * as Cesium from 'cesium'
import { calculateDrivingRoute, calculateMultipleRoutes, clearRouteCache, getCacheStats } from '../utils/amapApi'
import { calculateDistance, simplifyRoute } from '../utils/geoUtils'

export function useAmapRouting() {
  const isCalculating = ref(false)
  const lastError = ref(null)

  /**
   * 计算单条路线
   * @param {Object} origin - 起点 { lon, lat }
   * @param {Object} destination - 终点 { lon, lat }
   * @param {Object} options - 可选参数
   * @returns {Promise<Object>} 路线数据
   */
  const calculateRoute = async (origin, destination, options = {}) => {
    try {
      isCalculating.value = true
      lastError.value = null

      const routeData = await calculateDrivingRoute(origin, destination, options)

      // 可选：简化路线
      if (options.simplify) {
        routeData.polyline = simplifyRoute(routeData.polyline, options.maxPoints || 50)
      }

      return routeData
    } catch (error) {
      lastError.value = error.message
      console.error('[useAmapRouting] 路线计算失败:', error)

      // // 降级：生成直线路径
      // if (options.fallbackToStraightLine !== false) {
      //   console.warn('[useAmapRouting] 使用直线降级方案')
      //   return generateStraightLineRoute(origin, destination)
      // }

      throw error
    } finally {
      isCalculating.value = false
    }
  }

  /**
   * 批量计算路线
   * @param {Array} routePairs - 路线对数组
   * @returns {Promise<Array>} 路线结果数组
   */
  const calculateRoutes = async (routePairs) => {
    try {
      isCalculating.value = true
      lastError.value = null

      const results = await calculateMultipleRoutes(routePairs)

      // // 对失败的路线使用直线降级
      // const processedResults = results.map(result => {
      //   if (!result.success) {
      //     console.warn(`[useAmapRouting] 路线 ${result.name} 失败，使用直线降级`)
      //     const fallbackRoute = generateStraightLineRoute(result.origin, result.destination)
      //     return {
      //       ...result,
      //       ...fallbackRoute,
      //       isFallback: true,
      //       success: true
      //     }
      //   }
      //   return result
      // })

      // return processedResults
      return results
    } catch (error) {
      lastError.value = error.message
      console.error('[useAmapRouting] 批量路线计算失败:', error)
      throw error
    } finally {
      isCalculating.value = false
    }
  }

  /**
   * 将高德 polyline 字符串转换为 Cesium Cartesian3 数组
   * @param {string} polylineString - 高德 polyline 格式 "lon1,lat1;lon2,lat2;..."
   * @returns {Array<Cesium.Cartesian3>} Cartesian3 坐标数组
   */
  const transformToCartesian3 = (polylineString) => {
    if (!polylineString) {
      console.warn('[useAmapRouting] polyline 为空')
      return []
    }

    try {
      return polylineString
        .split(';')
        .map(pair => {
          const [lon, lat] = pair.split(',').map(Number)

          if (isNaN(lon) || isNaN(lat)) {
            console.warn('[useAmapRouting] 无效坐标:', pair)
            return null
          }

          return Cesium.Cartesian3.fromDegrees(lon, lat, 0)
        })
        .filter(Boolean)
    } catch (error) {
      console.error('[useAmapRouting] polyline 转换失败:', error)
      return []
    }
  }

  /**
   * 生成直线路径（降级方案）
   * @param {Object} origin - 起点
   * @param {Object} destination - 终点
   * @returns {Object} 直线路径数据
   */
  const generateStraightLineRoute = (origin, destination) => {
    const distance = calculateDistance(origin, destination) * 1000 // 转为米

    // 假设平均速度 40 km/h
    const duration = (distance / 1000) * 60 * 1.5 // 秒

    return {
      polyline: `${origin.lon},${origin.lat};${destination.lon},${destination.lat}`,
      distance: Math.round(distance),
      duration: Math.round(duration),
      steps: [],
      isFallback: true
    }
  }

  /**
   * 清除路由缓存
   */
  const clearCache = () => {
    clearRouteCache()
  }

  /**
   * 获取缓存统计
   */
  const getCacheInfo = () => {
    return getCacheStats()
  }

  return {
    // 状态
    isCalculating,
    lastError,

    // 方法
    calculateRoute,
    calculateRoutes,
    transformToCartesian3,
    generateStraightLineRoute,
    clearCache,
    getCacheInfo
  }
}

export default useAmapRouting
