import { ref } from 'vue'
import * as Cesium from 'cesium'
import { ElMessage, ElNotification } from 'element-plus'
import { ANIMATION_CONFIG, ANIMATION_PATHS } from '../constants'
import { useAmapRouting } from './useAmapRouting'
import { useEmergencyRouteSelection } from './useEmergencyRouteSelection'
import { useRouteVisualization } from './useRouteVisualization'

// 灾害中心坐标
const DISASTER_CENTER = {
  lon: 108.010961,
  lat: 30.176459
}

/**
 * 应急调度流程管理
 *
 * 职责：
 * 1. 管理"一键启动"完整流程
 * 2. 协调 loading 动画、路径线绘制、人员移动动画
 * 3. 管理相机飞行到全景位置
 * 4. 清理路径起点标记
 * 5. 集成高德地图路径规划
 *
 * @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, startMultipleAnimationsWithRoutes, isAnimating } =
    entityAnimationComposable

  // 初始化路由相关 composables
  const { calculateRoutes, isCalculating } = useAmapRouting()
  const { selectByType } = useEmergencyRouteSelection()
  const { drawMultipleRoutes, clearRoutes, clearRoute, getRoutesBounds } = useRouteVisualization()

  // Loading 状态
  const showLoading = ref(false)
  const loadingMessage = ref('正在加载...')

  /**
   * 隐藏应急点的静态人员/装备标记
   * @param {Cesium.Viewer} viewer
   */
  const hideEmergencyPointMarkers = (viewer) => {
    if (!viewer) return

    viewer.entities.values.forEach((entity) => {
      if (entity.properties) {
        const type = entity.properties.type?.getValue()
        if (type === 'emergencyPersonnel' || type === 'emergencyEquipment') {
          entity.show = false
        }
      }
    })
    console.log('[useEmergencyDispatch] 已隐藏应急点静态标记')
  }

  /**
   * 启动应急调度流程（新版：使用高德地图路径规划）
   * @param {Object} payload - 调度参数
   */
  const startDispatchWithRouting = async (payload) => {
    console.log('[useEmergencyDispatch] 启动智能路径调度:', payload)

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

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

    try {
      // 1. 显示 loading - 加载应急点
      showLoading.value = true
      loadingMessage.value = '加载应急点数据...'

      // 模拟从 API 加载应急点（这里使用 payload 中的数据）
      // 实际项目中应该调用: await request({ url: '/snow-ops-platform/yhYjll/list', ... })
      const allPoints = payload.emergencyPoints || []

      if (allPoints.length === 0) {
        throw new Error('没有可用的应急点')
      }

      console.log(`[useEmergencyDispatch] 加载了 ${allPoints.length} 个应急点`)

      // 2. 选择最近的应急点
      loadingMessage.value = '选择最近的应急点...'
      await delay(300)

      const { personnel, equipment } = selectByType(DISASTER_CENTER, allPoints, {
        personnelCount: 2,  // 修改为2个人员点
        equipmentCount: 2   // 保持2个装备点
      })

      console.log(`[useEmergencyDispatch] 选择了 ${personnel.length} 个人员点, ${equipment.length} 个装备点`)

      if (personnel.length === 0 && equipment.length === 0) {
        throw new Error('没有选择到合适的应急点')
      }

      // 3. 计算路线
      loadingMessage.value = '计算最优路线...'
      await delay(300)

      const routePairs = [
        ...personnel.map(p => ({
          id: `personnel_${p.id || p.name}`,
          name: p.name || '应急人员',
          type: 'personnel',
          origin: { lon: p.lon, lat: p.lat },
          destination: DISASTER_CENTER
        })),
        ...equipment.map(e => ({
          id: `equipment_${e.id || e.name}`,
          name: e.name || '应急装备',
          type: 'equipment',
          origin: { lon: e.lon, lat: e.lat },
          destination: DISASTER_CENTER
        }))
      ]

      const routes = await calculateRoutes(routePairs)

      console.log(`[useEmergencyDispatch] 计算了 ${routes.length} 条路线`)

      // 检查是否有降级路线
      const fallbackCount = routes.filter(r => r.isFallback).length
      if (fallbackCount > 0) {
        ElMessage.warning(`${fallbackCount} 条路线使用直线距离（API 规划失败）`)
      }

      // 4. 清除旧路线并绘制新路线
      loadingMessage.value = '绘制应急路径...'
      await delay(300)

      clearRoutes(viewer)
      drawMultipleRoutes(viewer, routes)

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

      // 6. 启动动画前隐藏静态标记
      loadingMessage.value = '启动应急调度...'
      await delay(300)

      // 隐藏应急点的静态人员/装备标记
      hideEmergencyPointMarkers(viewer)

      startMultipleAnimationsWithRoutes(viewer, routes, {
        speedMultiplier: 40,
        disablePulse: true,  // 禁用脉冲效果
        // 新增：实体到达时清除对应路线的回调
        onEntityComplete: (routeId) => {
          console.log(`[useEmergencyDispatch] 实体到达目标，清除路线: ${routeId}`)
          clearRoute(viewer, routeId)
        }
      })

      // 7. 相机飞向全景位置
      flyToOverviewPositionForRoutes(routes)

      // 8. 隐藏 loading
      showLoading.value = false

      ElNotification.success({
        title: '调度成功',
        message: `已启动 ${routes.length} 条应急路线`,
        duration: 3000
      })
    } catch (error) {
      console.error('[useEmergencyDispatch] 调度失败:', error)

      showLoading.value = false

      ElNotification.error({
        title: '调度失败',
        message: error.message || '未知错误',
        duration: 5000
      })

      // 降级到旧版调度
      console.warn('[useEmergencyDispatch] 降级到硬编码路径调度')
      startDispatch(payload)
    }
  }

  /**
   * 启动应急调度流程（旧版：使用硬编码路径）
   * @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
    loadingMessage.value = '正在加载...'

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

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

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

  /**
   * 延迟函数
   */
  const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms))

  /**
   * 执行调度步骤
   * @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} 个路径起点标记`)
  }

  /**
   * 相机飞向全景位置（动态路线版本）
   * @param {Array} routes - 路线数组
   */
  const flyToOverviewPositionForRoutes = (routes) => {
    const { camera } = mapStore.services()

    console.log('[useEmergencyDispatch] 相机飞向动态路线全景位置...')

    // 获取所有路线的边界点
    const allPoints = getRoutesBounds(routes)

    // 添加灾害中心点
    allPoints.push(DISASTER_CENTER)

    if (allPoints.length === 0) {
      console.warn('[useEmergencyDispatch] 没有路线点，使用默认视角')
      return
    }

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

  /**
   * 相机飞向全景位置（硬编码路径版本）
   * 计算能看到所有路径的最佳视角
   */
  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,
    loadingMessage,
    isCalculating,

    // 方法
    startDispatch, // 旧版（硬编码路径）
    startDispatchWithRouting, // 新版（高德地图路径规划）
    stopDispatch,
  }
}
