import { ref } from 'vue'
import * as Cesium from 'cesium'
import { ANIMATION_CONFIG, ANIMATION_PATHS } from '../constants'

/**
 * 应急调度流程管理
 *
 * 职责：
 * 1. 管理"一键启动"完整流程
 * 2. 协调 loading 动画、路径线绘制、人员移动动画
 * 3. 管理相机飞行到全景位置
 * 4. 清理路径起点标记
 *
 * @param {Object} dependencies - 依赖的 composables
 * @param {Object} dependencies.pathLinesComposable - usePathLines 返回的对象
 * @param {Object} dependencies.entityAnimationComposable - useEntityAnimation 返回的对象
 * @param {Object} dependencies.mapStore - 地图 store
 * @param {Function} dependencies.registerTimeoutFn - 注册定时器的函数（来自 useCesiumLifecycle）
 * @returns {Object} 应急调度 API
 */
export function useEmergencyDispatch({
  pathLinesComposable,
  entityAnimationComposable,
  mapStore,
  registerTimeoutFn,
}) {
  const { drawAllPathLines } = pathLinesComposable
  const { startPersonnelMovement, startMultipleMovements, isAnimating } =
    entityAnimationComposable

  // Loading 状态
  const showLoading = ref(false)

  /**
   * 启动应急调度流程
   * @param {Object} payload - 调度参数
   */
  const startDispatch = (payload) => {
    console.log('[useEmergencyDispatch] 启动力量调度:', payload)

    // 防止重复启动
    if (isAnimating.value) {
      console.warn('[useEmergencyDispatch] 动画正在运行，忽略重复启动')
      return
    }

    const viewer = mapStore.viewer
    if (!viewer) {
      console.error('[useEmergencyDispatch] viewer 未就绪')
      return
    }

    // 1. 显示 loading 动画
    showLoading.value = true

    // 2. 绘制红色路径线
    drawAllPathLines(viewer, {
      color: Cesium.Color.RED,
      width: 5,
      clampToGround: true,
    })

    // 3. 延迟执行后续步骤
    const timeoutId = setTimeout(() => {
      executeDispatchSteps(viewer)
    }, ANIMATION_CONFIG.loadingDuration)

    // 注册定时器到生命周期管理
    registerTimeoutFn(timeoutId)
  }

  /**
   * 执行调度步骤
   * @param {Cesium.Viewer} viewer - Cesium viewer 实例
   */
  const executeDispatchSteps = (viewer) => {
    // 1. 隐藏 loading 动画
    showLoading.value = false

    // 2. 移除路径起点标记
    removePathStartMarkers(viewer)

    // 3. 启动人员移动动画
    startPersonnelMovement(viewer, {
      duration: ANIMATION_CONFIG.duration,
      trackEntity: false,
      personnelName: '应急救援人员',
      department: '应急救援队',
    })

    // 4. 启动多组移动动画
    startMultipleMovements(viewer, {
      duration: ANIMATION_CONFIG.duration,
    })

    // 5. 相机飞向全景位置
    flyToOverviewPosition()
  }

  /**
   * 移除路径起点标记
   * @param {Cesium.Viewer} viewer - Cesium viewer 实例
   */
  const removePathStartMarkers = (viewer) => {
    const entitiesToRemove = []

    viewer.entities.values.forEach((entity) => {
      if (entity.properties && entity.properties.isPathStartMarker) {
        entitiesToRemove.push(entity)
      }
    })

    entitiesToRemove.forEach((entity) => {
      viewer.entities.remove(entity)
    })

    console.log(`[useEmergencyDispatch] 已移除 ${entitiesToRemove.length} 个路径起点标记`)
  }

  /**
   * 相机飞向全景位置
   * 计算能看到所有路径的最佳视角
   */
  const flyToOverviewPosition = () => {
    const { camera } = mapStore.services()

    console.log('[useEmergencyDispatch] 相机缓慢飞向最佳全景位置...')

    // 收集所有路径的起点和终点
    const allPathPoints = []

    Object.values(ANIMATION_PATHS).forEach((path) => {
      const { startPoint, waypoints } = path

      // 起点
      allPathPoints.push(
        new Cesium.Cartesian3(startPoint.x, startPoint.y, startPoint.z)
      )

      // 终点
      const endPoint = waypoints[waypoints.length - 1]
      allPathPoints.push(new Cesium.Cartesian3(endPoint.x, endPoint.y, endPoint.z))
    })

    // 转换为经纬度格式
    const trajectoryPoints = allPathPoints.map((point) => {
      const cartographic = Cesium.Cartographic.fromCartesian(point)
      return {
        lon: Cesium.Math.toDegrees(cartographic.longitude),
        lat: Cesium.Math.toDegrees(cartographic.latitude),
      }
    })

    // 使用智能聚焦方法飞向能看到所有路径的最佳位置
    camera.fitBoundsWithTrajectory(trajectoryPoints, {
      duration: ANIMATION_CONFIG.cameraFlyDuration,
      padding: ANIMATION_CONFIG.cameraPadding,
    })
  }

  /**
   * 停止调度流程
   */
  const stopDispatch = () => {
    showLoading.value = false
    // 停止动画由 useEntityAnimation 管理
    console.log('[useEmergencyDispatch] 调度流程已停止')
  }

  return {
    showLoading,
    startDispatch,
    stopDispatch,
  }
}
