import { ref } from 'vue'
import * as Cesium from 'cesium'
import soldierIcon from '../assets/images/SketchPngfbec927027ff9e49207749ebaafd229429315341fda199251b6dfb1723ff17fb.png'
import deviceIcon from '../assets/images/SketchPng860d54f2a31f5f441fc6a88081224f1e98534bf6d5ca1246e420983bdf690380.png'

/**
 * 实体动画管理 Composable
 * 负责管理地图实体的路径动画,特别是应急人员沿路径移动
 */
export function useEntityAnimation() {
  // 动画实体引用
  const animatedEntity = ref(null)

  // 多组动画实体引用
  const animatedEntities = ref([])

  // 动画是否正在运行
  const isAnimating = ref(false)

  /**
   * 应急人员路径坐标 (Cartesian3 格式)
   * 这些坐标定义了人员从起点到终点的移动路径
   */
  const PERSONNEL_PATH_COORDINATES = [
    { x: -1706079.1327424292, y: 5247893.165552528, z: 3187993.9339800295 },
    { x: -1706116.7863268533, y: 5247923.177994122, z: 3187929.297700776 },
    { x: -1706131.4939896727, y: 5247956.7916397555, z: 3187865.1250298577 },
    { x: -1706117.7768181972, y: 5247999.865521995, z: 3187795.4584125844 },
    { x: -1706148.232862157, y: 5248029.100250082, z: 3187735.2203392833 },
    { x: -1706129.4638550146, y: 5248073.941490989, z: 3187662.59740559 },
    { x: -1706131.3071046746, y: 5248086.057462914, z: 3187643.216358425 },
    { x: -1706164.2362053818, y: 5248120.213627388, z: 3187577.1867482658 },
    { x: -1706255.3513903276, y: 5248175.916851786, z: 3187422.819624157 },
    { x: -1706300.2731912779, y: 5248172.011305182, z: 3187397.8767570513 },
    { x: -1706343.1007708232, y: 5248165.925888667, z: 3187382.186124808 }
  ]

  // 设备组路径坐标
  const DEVICE_PATH_COORDINATES = [
    { x: -1706935.1617290622, y: 5248501.604252841, z: 3186498.2137252213 },
    { x: -1706870.4952433936, y: 5248490.611178698, z: 3186558.182971472 },
    { x: -1706837.227189178, y: 5248420.334709732, z: 3186690.581380162 },
    { x: -1706838.280444158, y: 5248431.37975438, z: 3186708.4743944216 },
    { x: -1706773.0696515848, y: 5248373.01216906, z: 3186823.943446862 },
    { x: -1706727.805384834, y: 5248323.242719114, z: 3186915.9148211516 },
    { x: -1706710.854065587, y: 5248281.031240471, z: 3186987.549384787 },
    { x: -1706660.1034110512, y: 5248266.553680115, z: 3187047.6342452955 },
    { x: -1706604.7906532797, y: 5248253.292764083, z: 3187082.311741225 },
    { x: -1706556.3289747096, y: 5248217.41920621, z: 3187155.538613598 },
    { x: -1706516.2888762353, y: 5248217.691641104, z: 3187197.012414378 },
    { x: -1706436.9808225571, y: 5248198.704904958, z: 3187267.311000274 },
    { x: -1706345.7538517928, y: 5248165.481249246, z: 3187379.4674185305 }
  ]

  // 人员组2路径坐标
  const PERSONNEL_PATH_COORDINATES_2 = [
    { x: -1707020.4106680197, y: 5248239.972166492, z: 3187000.301322692 },
    { x: -1706846.822522451, y: 5248275.0303560095, z: 3186986.011771928 },
    { x: -1706851.3836389545, y: 5248300.681797178, z: 3186942.7035291386 },
    { x: -1706844.580179418, y: 5248304.977808034, z: 3186932.891914393 },
    { x: -1706818.9276717228, y: 5248278.222342581, z: 3186976.253684671 },
    { x: -1706831.3209432173, y: 5248316.447298632, z: 3186957.2249293313 },
    { x: -1706806.3169318594, y: 5248307.832821272, z: 3186919.6375066047 },
    { x: -1706805.9829374112, y: 5248319.428155191, z: 3186900.13906115 },
    { x: -1706795.069820001, y: 5248321.041829423, z: 3186896.925767256 },
    { x: -1706797.8593846853, y: 5248325.909509062, z: 3186906.0008906457 },
    { x: -1706806.3364665583, y: 5248330.644777029, z: 3186917.773814682 },
    { x: -1706778.3135473165, y: 5248282.550132113, z: 3186963.408730601 },
    { x: -1706750.0602398354, y: 5248252.482706784, z: 3187012.7495610164 },
    { x: -1706738.0772460685, y: 5248263.416236532, z: 3187023.8067475185 },
    { x: -1706691.7246759017, y: 5248270.110156667, z: 3187018.588901565 },
    { x: -1706599.6318286993, y: 5248240.149769867, z: 3187087.254778178 },
    { x: -1706564.1779400432, y: 5248218.9292086465, z: 3187146.335302665 },
    { x: -1706486.5598449395, y: 5248207.86588749, z: 3187216.762631293 },
    { x: -1706445.7375556522, y: 5248203.1875622, z: 3187252.8650745875 },
    { x: -1706409.1757614242, y: 5248182.077526832, z: 3187307.1294440767 },
    { x: -1706408.0269636167, y: 5248192.685664652, z: 3187323.2121423096 },
    { x: -1706390.7352810341, y: 5248211.637499602, z: 3187344.1570185754 }
  ]

  /**
   * 启动应急人员沿路径移动动画
   * @param {Cesium.Viewer} viewer - Cesium viewer 实例
   * @param {Object} options - 配置选项
   * @param {number} [options.duration=36] - 动画总时长(秒)
   * @param {boolean} [options.trackEntity=false] - 是否相机跟随实体
   * @param {string} [options.personnelName='应急人员'] - 人员名称
   * @param {string} [options.department='应急救援队'] - 所属部门
   * @returns {Cesium.Entity} 返回创建的动画实体
   */
  const startPersonnelMovement = (viewer, options = {}) => {
    if (!viewer) {
      console.warn('[useEntityAnimation] startPersonnelMovement: viewer 为空')
      return null
    }

    if (isAnimating.value) {
      console.warn('[useEntityAnimation] 动画已在运行中,请先停止当前动画')
      return animatedEntity.value
    }

    const config = {
      duration: options.duration ?? 60, // 默认 60 秒，让移动更清晰可见
      trackEntity: options.trackEntity ?? false,
      personnelName: options.personnelName ?? '应急人员',
      department: options.department ?? '应急救援队'
    }

    console.log('[useEntityAnimation] 开始启动人员移动动画...', config)

    // 设置动画时间范围
    const startTime = Cesium.JulianDate.now()
    const stopTime = Cesium.JulianDate.addSeconds(
      startTime,
      config.duration,
      new Cesium.JulianDate()
    )

    // 配置 viewer 时钟
    viewer.clock.startTime = startTime.clone()
    viewer.clock.stopTime = stopTime.clone()
    viewer.clock.currentTime = startTime.clone()
    viewer.clock.clockRange = Cesium.ClockRange.CLAMPED // 动画到达终点后停止，不循环
    viewer.clock.multiplier = 1 // 实时速度
    viewer.clock.shouldAnimate = true

    // 创建 SampledPositionProperty 定义路径
    const positionProperty = new Cesium.SampledPositionProperty()

    // 计算每个路径点的时间间隔
    const numberOfPoints = PERSONNEL_PATH_COORDINATES.length
    const timeInterval = config.duration / (numberOfPoints - 1)

    // 添加路径采样点
    PERSONNEL_PATH_COORDINATES.forEach((coord, index) => {
      const time = Cesium.JulianDate.addSeconds(
        startTime,
        index * timeInterval,
        new Cesium.JulianDate()
      )
      const position = new Cesium.Cartesian3(coord.x, coord.y, coord.z)
      positionProperty.addSample(time, position)
    })

    // 创建脉冲缩放效果 - 让图标闪烁更醒目
    const pulseScale = options.disablePulse
      ? 1.0
      : new Cesium.CallbackProperty((time) => {
        const elapsed = Cesium.JulianDate.secondsDifference(time, startTime)
        // 使用正弦波产生脉冲效果，频率 3Hz，幅度 ±30%
        return 1.0 + Math.sin(elapsed * 3) * 0.3
      }, false)

    // 创建动画实体
    const entity = viewer.entities.add({
      availability: new Cesium.TimeIntervalCollection([
        new Cesium.TimeInterval({
          start: startTime,
          stop: stopTime
        })
      ]),
      position: positionProperty,
      orientation: new Cesium.VelocityOrientationProperty(positionProperty), // 自动朝向移动方向
      billboard: {
        image: soldierIcon,
        width: 48,  // 增大尺寸，从 36 增加到 48
        height: 56, // 从 40 增加到 56
        scale: pulseScale, // 使用脉冲缩放效果
        verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
        heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
        disableDepthTestDistance: Number.POSITIVE_INFINITY,
        // 添加距离缩放，让图标在不同距离下都清晰可见
        scaleByDistance: new Cesium.NearFarScalar(
          1000, 1.5,   // 近距离（1000米）放大到 1.5 倍
          50000, 0.8   // 远距离（50000米）缩小到 0.8 倍
        )
      },
      // 添加发光轨迹线
      // path: {
      //   resolution: 1,
      //   material: new Cesium.PolylineGlowMaterialProperty({
      //     glowPower: 0.4,      // 发光强度
      //     taperPower: 0.5,     // 渐变效果
      //     color: Cesium.Color.CYAN  // 青色轨迹
      //   }),
      //   width: 8,
      //   leadTime: 0,                 // 前方不显示轨迹
      //   trailTime: config.duration   // 后方显示完整轨迹
      // },
      properties: {
        type: 'animatedSoldier',
        name: config.personnelName,
        department: config.department,
        isAnimating: true
      }
    })

    animatedEntity.value = entity
    isAnimating.value = true

    // 可选: 相机跟随实体
    if (config.trackEntity) {
      viewer.trackedEntity = entity
      // 设置相机视角偏移
      entity.viewFrom = new Cesium.Cartesian3(-100.0, -100.0, 50.0)
    }

    console.log('[useEntityAnimation] 人员移动动画已启动')

    // 监听动画结束事件
    const removeListener = viewer.clock.onStop.addEventListener(() => {
      console.log('[useEntityAnimation] 动画已结束')
      isAnimating.value = false
      removeListener() // 移除监听器
    })

    return entity
  }

  /**
   * 停止人员移动动画
   * @param {Cesium.Viewer} viewer - Cesium viewer 实例
   * @param {boolean} [removeEntity=true] - 是否移除动画实体
   */
  const stopPersonnelMovement = (viewer, removeEntity = true) => {
    if (!viewer) {
      console.warn('[useEntityAnimation] stopPersonnelMovement: viewer 为空')
      return
    }

    console.log('[useEntityAnimation] 停止人员移动动画')

    // 停止时钟动画
    viewer.clock.shouldAnimate = false

    // 取消相机跟随
    if (viewer.trackedEntity === animatedEntity.value) {
      viewer.trackedEntity = undefined
    }

    // 移除实体
    if (removeEntity && animatedEntity.value) {
      viewer.entities.remove(animatedEntity.value)
      animatedEntity.value = null
    }

    isAnimating.value = false
  }

  /**
   * 暂停动画
   * @param {Cesium.Viewer} viewer - Cesium viewer 实例
   */
  const pauseAnimation = (viewer) => {
    if (!viewer) return
    viewer.clock.shouldAnimate = false
    console.log('[useEntityAnimation] 动画已暂停')
  }

  /**
   * 恢复动画
   * @param {Cesium.Viewer} viewer - Cesium viewer 实例
   */
  const resumeAnimation = (viewer) => {
    if (!viewer) return
    if (isAnimating.value) {
      viewer.clock.shouldAnimate = true
      console.log('[useEntityAnimation] 动画已恢复')
    }
  }

  /**
   * 获取路径的起点坐标 (用于初始标记点)
   * @returns {Cesium.Cartesian3} 起点坐标
   */
  const getStartPosition = () => {
    const firstCoord = PERSONNEL_PATH_COORDINATES[0]
    return new Cesium.Cartesian3(firstCoord.x, firstCoord.y, firstCoord.z)
  }

  /**
   * 将 Cartesian3 坐标转换为经纬度
   * @param {Cesium.Cartesian3} cartesian - Cartesian3 坐标
   * @returns {Object} { longitude, latitude, height }
   */
  const cartesianToLonLat = (cartesian) => {
    const cartographic = Cesium.Cartographic.fromCartesian(cartesian)
    return {
      longitude: Cesium.Math.toDegrees(cartographic.longitude),
      latitude: Cesium.Math.toDegrees(cartographic.latitude),
      height: cartographic.height
    }
  }

  /**
   * 创建单个移动实体
   * @param {Cesium.Viewer} viewer
   * @param {Array} pathCoordinates - 路径坐标数组
   * @param {Object} config - 配置
   * @param {Cesium.JulianDate} startTime
   * @param {Cesium.JulianDate} stopTime
   * @returns {Cesium.Entity}
   */
  const createMovingEntity = (viewer, pathCoordinates, config, startTime, stopTime) => {
    try {
      const positionProperty = new Cesium.SampledPositionProperty()
      const numberOfPoints = pathCoordinates.length

      if (numberOfPoints === 0) {
        console.warn('[useEntityAnimation] 路径坐标为空')
        return null
      }

      const timeInterval = config.duration / (numberOfPoints - 1)

      pathCoordinates.forEach((coord, index) => {
        const time = Cesium.JulianDate.addSeconds(
          startTime,
          index * timeInterval,
          new Cesium.JulianDate()
        )
        const position = new Cesium.Cartesian3(coord.x, coord.y, coord.z)
        positionProperty.addSample(time, position)
      })

      const pulseScale = config.disablePulse
        ? 1.0
        : new Cesium.CallbackProperty((time) => {
          const elapsed = Cesium.JulianDate.secondsDifference(time, startTime)
          return 1.0 + Math.sin(elapsed * 3) * 0.3
        }, false)

      const icon = config.type === 'device' ? deviceIcon : soldierIcon

      const entity = viewer.entities.add({
        availability: new Cesium.TimeIntervalCollection([
          new Cesium.TimeInterval({ start: startTime, stop: stopTime })
        ]),
        position: positionProperty,
        orientation: new Cesium.VelocityOrientationProperty(positionProperty),
        billboard: {
          image: icon,
          width: 48,
          height: 56,
          scale: pulseScale,
          verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
          heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
          disableDepthTestDistance: Number.POSITIVE_INFINITY,
          scaleByDistance: new Cesium.NearFarScalar(1000, 1.5, 50000, 0.8)
        },
        properties: {
          type: config.type === 'device' ? 'animatedDevice' : 'animatedSoldier',
          name: config.name,
          department: config.department,
          isAnimating: true
        }
      })

      console.log(`[useEntityAnimation] 创建${config.type === 'device' ? '设备' : '人员'}实体: ${config.name}`)
      return entity

    } catch (error) {
      console.error('[useEntityAnimation] 创建移动实体失败:', error)
      return null
    }
  }


  /**
   * 启动多组移动动画（设备组 + 人员组2）
   * @param {Cesium.Viewer} viewer
   * @param {Object} options
   */
  const startMultipleMovements = (viewer, options = {}) => {
    if (!viewer) {
      console.warn('[useEntityAnimation] startMultipleMovements: viewer 为空')
      return []
    }

    // 先停止所有现有动画
    stopAllMovements(viewer)

    const config = {
      duration: options.duration ?? 60
    }

    console.log('[useEntityAnimation] 启动多组移动动画...')

    const startTime = Cesium.JulianDate.now()
    const stopTime = Cesium.JulianDate.addSeconds(startTime, config.duration, new Cesium.JulianDate())

    // 配置 viewer 时钟
    viewer.clock.startTime = startTime.clone()
    viewer.clock.stopTime = stopTime.clone()
    viewer.clock.currentTime = startTime.clone()
    viewer.clock.clockRange = Cesium.ClockRange.CLAMPED
    viewer.clock.multiplier = 1
    viewer.clock.shouldAnimate = true

    // 确保实体数组是空的
    animatedEntities.value = []

    // 创建设备组移动实体
    const deviceEntity = createMovingEntity(viewer, DEVICE_PATH_COORDINATES, {
      duration: config.duration,
      type: 'device',
      name: '应急设备车',
      department: '应急装备队',
      disablePulse: options.disablePulse
    }, startTime, stopTime)

    if (deviceEntity) {
      animatedEntities.value.push(deviceEntity)
    }

    // 创建人员组2移动实体
    const personnel2Entity = createMovingEntity(viewer, PERSONNEL_PATH_COORDINATES_2, {
      duration: config.duration,
      type: 'soldier',
      name: '应急救援队员',
      department: '应急救援队',
      disablePulse: options.disablePulse
    }, startTime, stopTime)

    if (personnel2Entity) {
      animatedEntities.value.push(personnel2Entity)
    }

    isAnimating.value = true

    // 设置超时清理
    const timeoutId = setTimeout(() => {
      console.log('[useEntityAnimation] 多组动画超时，强制清理')
      stopAllMovements(viewer)
    }, (config.duration + 5) * 1000) // 动画时长+5秒缓冲

    const removeListener = viewer.clock.onStop.addEventListener(() => {
      console.log('[useEntityAnimation] 多组动画已结束')
      clearTimeout(timeoutId)
      isAnimating.value = false
      removeListener()
    })

    console.log('[useEntityAnimation] 已启动 2 组移动动画')
    return animatedEntities.value
  }


  /**
   * 停止所有移动动画
   * @param {Cesium.Viewer} viewer
   */
  const stopAllMovements = (viewer) => {
    if (!viewer) return

    console.log('[useEntityAnimation] 停止所有移动动画')

    // 停止时钟动画
    viewer.clock.shouldAnimate = false

    // 取消相机跟随
    if (viewer.trackedEntity) {
      viewer.trackedEntity = undefined
    }

    // 停止所有脉冲效果
    stopAllPulses(viewer)

    // 移除单个动画实体
    if (animatedEntity.value) {
      try {
        viewer.entities.remove(animatedEntity.value)
      } catch (e) {
        console.warn('[useEntityAnimation] 移除单个实体时出错:', e)
      }
      animatedEntity.value = null
    }

    // 移除所有动画实体
    animatedEntities.value.forEach(entity => {
      if (entity) {
        try {
          viewer.entities.remove(entity)
        } catch (e) {
          console.warn('[useEntityAnimation] 移除实体时出错:', e)
        }
      }
    })
    animatedEntities.value = []

    // 额外清理：移除所有类型为 animatedSoldier 和 animatedDevice 的实体
    const entitiesToRemove = []
    viewer.entities.values.forEach(entity => {
      const entityType = entity.properties?.type?.getValue?.()
      if (entityType === 'animatedSoldier' || entityType === 'animatedDevice') {
        entitiesToRemove.push(entity)
      }
    })

    entitiesToRemove.forEach(entity => {
      try {
        viewer.entities.remove(entity)
        console.log('[useEntityAnimation] 清理残留实体:', entity.properties?.name?.getValue?.() || '未知')
      } catch (e) {
        console.warn('[useEntityAnimation] 清理残留实体时出错:', e)
      }
    })

    isAnimating.value = false
    console.log('[useEntityAnimation] 已停止所有移动动画，并清理残留实体')
  }


  /**
   * 根据动态路线创建动画实体
   * @param {Cesium.Viewer} viewer
   * @param {Object} route - 路线数据 { polyline, duration, type, name, id }
   * @param {Object} options - 配置选项
   * @param {Cesium.JulianDate} startTime
   * @param {Cesium.JulianDate} stopTime
   * @returns {Cesium.Entity}
   */
  const createAnimationFromRoute = (viewer, route, options, startTime, stopTime) => {
    // 将 polyline 字符串转换为 Cartesian3 数组
    const positions = route.polyline
      .split(';')
      .map(pair => {
        const [lon, lat] = pair.split(',').map(Number)
        return Cesium.Cartesian3.fromDegrees(lon, lat, 0)
      })

    // 计算动画时长（使用速度倍数）
    // 装备移动速度更快（speedMultiplier 更大 = 动画时间更短 = 移动更快）
    const baseSpeedMultiplier = options.speedMultiplier || 10
    const speedMultiplier = route.type === 'equipment'
      ? baseSpeedMultiplier * 1.5  // 装备速度是人员的1.5倍
      : baseSpeedMultiplier         // 人员保持原速

    const animationDuration = Math.min(
      Math.max(route.duration / speedMultiplier, 30), // 最小30秒
      120 // 最大120秒
    )

    // 创建位置属性
    const positionProperty = new Cesium.SampledPositionProperty()

    // 关键修复：设置外推类型，确保在采样范围外保持最后位置
    positionProperty.forwardExtrapolationType = Cesium.ExtrapolationType.HOLD
    positionProperty.backwardExtrapolationType = Cesium.ExtrapolationType.HOLD

    const timeInterval = animationDuration / (positions.length - 1)

    positions.forEach((position, index) => {
      const time = Cesium.JulianDate.addSeconds(
        startTime,
        index * timeInterval,
        new Cesium.JulianDate()
      )
      positionProperty.addSample(time, position)
    })

    // 脉冲缩放效果 - 添加状态控制以支持停止脉冲
    const scaleState = {
      isPulsing: !options.disablePulse,
      fixedScale: 1.0
    }

    const pulseScale = options.disablePulse
      ? 1.0
      : new Cesium.CallbackProperty((time) => {
        if (!scaleState.isPulsing) {
          return scaleState.fixedScale  // 停止脉冲，返回固定值
        }

        const elapsed = Cesium.JulianDate.secondsDifference(time, startTime)
        return 1.0 + Math.sin(elapsed * 3) * 0.3
      }, false)

    // 选择图标和轨迹颜色
    const icon = route.type === 'equipment' ? deviceIcon : soldierIcon
    const trailColor = route.type === 'equipment' ? Cesium.Color.ORANGE : Cesium.Color.CYAN

    // 日志输出：显示每个实体的动画时长
    console.log(
      `[useEntityAnimation] ${route.name} (${route.type}): ` +
      `原始时长=${Math.round(route.duration)}秒, ` +
      `速度倍数=${speedMultiplier.toFixed(1)}, ` +
      `动画时长=${Math.round(animationDuration)}秒`
    )

    // 创建动画实体
    return viewer.entities.add({
      position: positionProperty,
      orientation: new Cesium.VelocityOrientationProperty(positionProperty),
      billboard: {
        image: icon,
        width: 48,
        height: 56,
        scale: pulseScale,
        verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
        heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
        disableDepthTestDistance: Number.POSITIVE_INFINITY,
        scaleByDistance: new Cesium.NearFarScalar(1000, 1.5, 50000, 0.8)
      },
      // path: {
      //   resolution: 1,
      //   material: new Cesium.PolylineGlowMaterialProperty({
      //     glowPower: 0.4,
      //     taperPower: 0.5,
      //     color: trailColor
      //   }),
      //   width: 8,
      //   leadTime: 0,
      //   trailTime: animationDuration
      // },
      properties: {
        type: route.type === 'equipment' ? 'animatedDevice' : 'animatedSoldier',
        name: route.name,
        routeId: route.id,
        isAnimating: true,
        isCompleted: false,  // 新增：标记动画是否完成
        scaleState: scaleState,  // 新增：保存状态引用
        animationDuration: animationDuration,  // 新增：保存动画时长
        animationStartTime: startTime.clone()  // 新增：保存开始时间
      }
    })
  }

  /**
   * 启动基于动态路线的多组动画
   * @param {Cesium.Viewer} viewer
   * @param {Array} routes - 路线数组
   * @param {Object} options - 配置选项
   * @returns {Array<Cesium.Entity>}
   */
  const startMultipleAnimationsWithRoutes = (viewer, routes, options = {}) => {
    if (!viewer || !routes || routes.length === 0) {
      console.warn('[useEntityAnimation] startMultipleAnimationsWithRoutes: 参数无效')
      return []
    }

    // 解构回调参数
    const { speedMultiplier: baseSpeedMultiplier, disablePulse, onEntityComplete } = options

    console.log(`[useEntityAnimation] 启动 ${routes.length} 条路线的动画 (disablePulse: ${disablePulse || false})`)

    // 计算最大动画时长
    const speedMultiplier = baseSpeedMultiplier || 10
    const durations = routes.map(r =>
      Math.min(Math.max(r.duration / speedMultiplier, 30), 120)
    )
    const maxDuration = Math.max(...durations)

    // 设置时间范围
    const startTime = Cesium.JulianDate.now()
    const stopTime = Cesium.JulianDate.addSeconds(
      startTime,
      maxDuration,
      new Cesium.JulianDate()
    )

    // 配置 viewer 时钟
    viewer.clock.startTime = startTime.clone()
    viewer.clock.stopTime = stopTime.clone()
    viewer.clock.currentTime = startTime.clone()
    viewer.clock.clockRange = Cesium.ClockRange.UNBOUNDED // 允许时间继续前进，支持不同时长动画独立完成
    viewer.clock.multiplier = 1
    viewer.clock.shouldAnimate = true

    // 清除之前的动画实体
    animatedEntities.value.forEach(entity => {
      if (entity) viewer.entities.remove(entity)
    })
    animatedEntities.value = []

    // 为每条路线创建动画实体
    routes.forEach(route => {
      try {
        const entity = createAnimationFromRoute(
          viewer,
          route,
          { speedMultiplier, disablePulse: options.disablePulse },
          startTime,
          stopTime
        )
        animatedEntities.value.push(entity)
      } catch (error) {
        console.error(`[useEntityAnimation] 创建路线 ${route.name} 的动画失败:`, error)
      }
    })

    isAnimating.value = true

    // 监听时钟，检测动画完成
    const clockListener = viewer.clock.onTick.addEventListener((clock) => {
      checkAnimationsCompletion(viewer, clock.currentTime, (routeId, entity) => {
        // 调用原有的路线清除回调
        if (options.onEntityComplete) {
          options.onEntityComplete(routeId)
        }

        // 延迟移除实体
        setTimeout(() => {
          if (viewer && !viewer.isDestroyed() && entity) {
            viewer.entities.remove(entity)
            console.log(`[useEntityAnimation] 动画完成，已移除实体`)

            // 从动画实体列表中移除
            const index = animatedEntities.value.indexOf(entity)
            if (index > -1) {
              animatedEntities.value.splice(index, 1)
            }
          }
        }, 1000) // 延迟1秒移除
      })
    })

    // 监听动画结束
    const removeListener = viewer.clock.onStop.addEventListener(() => {
      console.log('[useEntityAnimation] 动画已结束')
      isAnimating.value = false
      removeListener()
      clockListener()  // 移除 tick 监听器
    })

    // 新增：60秒超时强制清除所有实体
    const timeoutId = setTimeout(() => {
      console.log('[useEntityAnimation] 60秒超时，强制清除所有动画实体')
      forceCleanupAllAnimations(viewer, options.onEntityComplete)
    }, 60000) // 60秒超时

    console.log(`[useEntityAnimation] 成功启动 ${animatedEntities.value.length} 个动画实体`)

    return animatedEntities.value
  }

  /**
 * 强制清理所有动画实体和路线
 * @param {Cesium.Viewer} viewer
 * @param {Function} onEntityComplete - 路线清除回调
 */
  const forceCleanupAllAnimations = (viewer, onEntityComplete) => {
    if (!viewer) return

    // 停止时钟
    viewer.clock.shouldAnimate = false

    // 停止所有脉冲
    stopAllPulses(viewer)

    // 移除所有实体并触发回调
    animatedEntities.value.forEach(entity => {
      if (!entity || !entity.properties) return

      const routeId = entity.properties.routeId?.getValue()

      // 触发路线清除回调
      if (onEntityComplete && typeof onEntityComplete === 'function' && routeId) {
        console.log(`[useEntityAnimation] 超时清除路线: ${routeId}`)
        onEntityComplete(routeId)
      }

      // 移除实体
      if (viewer && !viewer.isDestroyed()) {
        viewer.entities.remove(entity)
      }
    })

    // 清空实体列表
    animatedEntities.value = []

    // 清除单个动画实体
    if (animatedEntity.value) {
      viewer.entities.remove(animatedEntity.value)
      animatedEntity.value = null
    }

    isAnimating.value = false
    console.log('[useEntityAnimation] 强制清理完成')
  }


  /**
 * 检查动画是否完成，如果完成则停止脉冲、清除路线并移除实体
 * @param {Cesium.Viewer} viewer
 * @param {Cesium.JulianDate} currentTime
 * @param {Function} onEntityComplete - 完成回调 (routeId, entity) => void
 */
  const checkAnimationsCompletion = (viewer, currentTime, onEntityComplete) => {
    animatedEntities.value.forEach(entity => {
      if (!entity || !entity.properties) return

      const scaleState = entity.properties.scaleState?.getValue()
      const startTime = entity.properties.animationStartTime?.getValue()
      const duration = entity.properties.animationDuration?.getValue()
      const isCompleted = entity.properties.isCompleted?.getValue()
      const routeId = entity.properties.routeId?.getValue()

      if (!scaleState || !startTime || !duration || !routeId) return

      // 如果已经完成，跳过（避免重复触发）
      if (isCompleted) return

      // 计算已过时间
      const elapsed = Cesium.JulianDate.secondsDifference(currentTime, startTime)

      // 如果动画已完成（留0.5秒容差）
      if (elapsed >= duration - 0.5) {
        const entityName = entity.properties.name?.getValue() || '未知实体'
        console.log(`[useEntityAnimation] ========================================`)
        console.log(`[useEntityAnimation] 实体 "${entityName}" 动画完成`)
        console.log(`[useEntityAnimation] - routeId: ${routeId}`)
        console.log(`[useEntityAnimation] - elapsed: ${elapsed.toFixed(2)}秒`)
        console.log(`[useEntityAnimation] - duration: ${duration}秒`)
        console.log(`[useEntityAnimation] ========================================`)

        // 1. 停止脉冲效果
        scaleState.isPulsing = false
        scaleState.fixedScale = 1.0

        // 2. 标记为已完成（使用 ConstantProperty）
        entity.properties.isCompleted = new Cesium.ConstantProperty(true)

        // 3. 触发回调清除对应路线，并传递实体信息以便移除
        if (onEntityComplete && typeof onEntityComplete === 'function') {
          console.log(`[useEntityAnimation] 触发 onEntityComplete 回调，routeId: ${routeId}`)
          onEntityComplete(routeId, entity) // 传递实体信息
        } else {
          console.warn(`[useEntityAnimation] onEntityComplete 回调不存在或不是函数`)
          // 如果没有回调，直接移除实体
          setTimeout(() => {
            if (viewer && !viewer.isDestroyed()) {
              viewer.entities.remove(entity)
              console.log(`[useEntityAnimation] 已自动移除实体: ${entityName}`)
            }
          }, 1000) // 延迟1秒移除，确保动画完全结束
        }
      }
    })
  }


  /**
   * 停止所有实体的脉冲效果
   * @param {Cesium.Viewer} viewer
   */
  const stopAllPulses = (viewer) => {
    if (!viewer) return

    animatedEntities.value.forEach(entity => {
      if (!entity || !entity.properties) return

      const scaleState = entity.properties.scaleState?.getValue()
      if (scaleState) {
        scaleState.isPulsing = false
        scaleState.fixedScale = 1.0
      }
    })

    console.log('[useEntityAnimation] 已停止所有脉冲效果')
  }

  /**
   * 检查所有动画是否都已完成
   * @returns {boolean}
   */
  const areAllAnimationsCompleted = () => {
    if (animatedEntities.value.length === 0) return false

    return animatedEntities.value.every(entity => {
      const isCompleted = entity.properties?.isCompleted?.getValue()
      return isCompleted === true
    })
  }

  return {
    animatedEntity,
    animatedEntities,
    isAnimating,
    startPersonnelMovement,
    startMultipleMovements,
    stopPersonnelMovement,
    stopAllMovements,
    pauseAnimation,
    resumeAnimation,
    getStartPosition,
    cartesianToLonLat,
    PERSONNEL_PATH_COORDINATES,
    DEVICE_PATH_COORDINATES,
    PERSONNEL_PATH_COORDINATES_2,
    // 新增：动态路线动画方法
    createAnimationFromRoute,
    startMultipleAnimationsWithRoutes,
    // 新增：脉冲控制方法
    checkAnimationsCompletion,
    stopAllPulses,
    // 新增：强制清理方法
    forceCleanupAllAnimations
  }
}

export default useEntityAnimation
