import { inject, ref } from 'vue'
import * as Cesium from 'cesium'
import { cesiumDataConfig } from '../config/cesiumData'
import { collapseBoundaryData } from '../config/collapseBoundary'

// 图标导入
import soldierIcon from '../assets/images/SketchPngfbec927027ff9e49207749ebaafd229429315341fda199251b6dfb1723ff17fb.png'
import deviceIcon from '../assets/images/SketchPng860d54f2a31f5f441fc6a88081224f1e98534bf6d5ca1246e420983bdf690380.png'
import emergencyBaseIcon from '../assets/images/应急基地.png'
import emergencyCenterIcon from '../assets/images/应急中心icon定位.png'
import reserveCenterIcon from '../assets/images/储备中心.png'
// 新增：根据级别的应急点图标
import cityEmergencyIcon from '../assets/images/市应急点.png'
import districtEmergencyIcon from '../assets/images/区县应急点.png'
import otherEmergencyIcon from '../assets/images/其他应急点.png'

// 默认高度偏移（米）- 与 WuRenJi 保持一致
const DEFAULT_HEIGHT_OFFSET = 100

/**
 * 地图标记管理 Composable
 * 负责添加单兵、设备、应急基地标记以及塌陷区域
 */
export function useMapMarkers() {
  const collapseAreaEntities = ref([])
  const markerEntities = ref([])
  const emergencyResourceEntities = ref([]) // 应急资源标记（由API数据动态生成）
  const reserveCenterEntities = ref([]) // 储备中心和预置点标记
  const collapseBoundaryEntity = ref(null) // 坍塌边界线实体（右侧实线）
  const collapseBoundaryLeftEntity = ref(null) // 坍塌边界线实体（左侧虚线）

  /**
   * 获取塌陷区域的所有位置点
   * @returns {Cesium.Cartesian3[]}
   */
  const getCollapsePositions = () => {
    if (!Array.isArray(cesiumDataConfig) || !cesiumDataConfig.length) {
      return []
    }
    return cesiumDataConfig.map(point =>
      new Cesium.Cartesian3(point.x, point.y, point.z)
    )
  }

  /**
   * 计算塌陷区域中心点
   * 这个函数不依赖地形数据，可以在初始化早期调用
   * @returns {Cesium.Cartesian3 | null}
   */
  const calculateCollapseCenter = () => {
    const positions = getCollapsePositions()
    if (!positions.length) {
      console.warn('[useMapMarkers] 无法计算塌陷区域中心：配置数据为空')
      return null
    }
    return Cesium.BoundingSphere.fromPoints(positions).center
  }

  /**
   * 等待地形提供者就绪
   * 用于确保地形数据已加载，以便准确采样地面高度
   * @param {Cesium.Viewer} viewer
   * @returns {Promise<void>}
   */
  const waitForTerrainReady = async (viewer) => {
    if (!viewer?.terrainProvider?.readyPromise) {
      return
    }

    try {
      await viewer.terrainProvider.readyPromise
      console.log('[useMapMarkers] 地形提供者已就绪')
    } catch (error) {
      console.warn('[useMapMarkers] 地形加载失败，将使用默认高度:', error)
    }
  }

  /**
   * 解析经纬度坐标
   * 对于3D Tiles场景，直接返回经纬度坐标，不进行高度采样
   * 配合 RELATIVE_TO_GROUND 让Cesium自动处理高度
   *
   * @param {Cesium.Viewer} viewer
   * @param {number} lon - 经度（度）
   * @param {number} lat - 纬度（度）
   * @param {number} heightOffset - 相对地面的高度偏移（米）
   * @param {boolean} useSampledHeights - 是否使用采样高度（3D Tiles场景忽略此参数）
   * @returns {Promise<{ position: Cesium.Cartesian3, samplingSucceeded: boolean }>}
   */
  const resolveCartesianFromDegrees = async (viewer, lon, lat, heightOffset, useSampledHeights) => {
    // 对于3D Tiles场景，直接使用经纬度坐标
    // heightOffset 会通过 RELATIVE_TO_GROUND 自动应用
    return {
      position: Cesium.Cartesian3.fromDegrees(lon, lat, heightOffset),
      samplingSucceeded: false // 标记为未采样，使用 RELATIVE_TO_GROUND
    }
  }

  /**
   * 返回统一的高度参考模式
   * 所有标记统一使用 CLAMP_TO_GROUND，让 Cesium 自动处理贴地
   * 这样标记会自动跟随地形变化，但由于已禁用 3D Tiles 的动态细化，变化会很小
   *
   * @param {boolean} samplingSucceeded - 采样是否成功（保留参数用于日志）
   * @returns {Cesium.HeightReference}
   */
  const resolveBillboardHeightReference = (samplingSucceeded) => {
    // 统一使用 CLAMP_TO_GROUND 让 Cesium 自动贴地
    // 配合禁用的 3D Tiles 动态细化，标记位置会保持稳定
    // return Cesium.HeightReference.CLAMP_TO_GROUND
    return Cesium.HeightReference.RELATIVE_TO_GROUND
  }

  /**
   * 绘制坍塌边界红色实线（右侧地图）
   * 在右侧地图上显示灾后坍塌的边界轮廓
   * @param {Cesium.Viewer} viewer
   * @returns {Cesium.Entity | null} 返回创建的边界线实体
   */
  const drawCollapseBoundary = (viewer) => {
    if (!viewer) {
      console.warn('[useMapMarkers] drawCollapseBoundary: viewer 为空')
      return null
    }

    if (!Array.isArray(collapseBoundaryData) || collapseBoundaryData.length === 0) {
      console.warn('[useMapMarkers] drawCollapseBoundary: 配置数据为空')
      return null
    }

    // 清除旧的边界线（如果存在）
    if (collapseBoundaryEntity.value) {
      viewer.entities.remove(collapseBoundaryEntity.value)
      collapseBoundaryEntity.value = null
    }

    // 转换坐标点
    const positions = collapseBoundaryData.map(point =>
      new Cesium.Cartesian3(point.x, point.y, point.z)
    )

    // 闭合线条（连接最后一个点到第一个点）
    positions.push(positions[0])

    console.log('[useMapMarkers] 右侧坍塌边界点位数量:', positions.length)

    // 创建红色实线边界
    const boundaryEntity = viewer.entities.add({
      polyline: {
        positions: positions,
        width: 4, // 增加线宽，更明显
        material: Cesium.Color.fromCssColorString('#FF0000').withAlpha(1.0), // 纯红色实线
        clampToGround: true,
        classificationType: Cesium.ClassificationType.BOTH, // 同时分类到地形和3D Tiles
        zIndex: 1 // 提高层级
      },
      properties: new Cesium.PropertyBag({
        type: 'collapseBoundary',
        name: '坍塌边界（右侧实线）'
      }),
      show: true // 明确设置为显示
    })

    collapseBoundaryEntity.value = boundaryEntity
    console.log('[useMapMarkers] 右侧坍塌边界红色实线绘制完成, entityId:', boundaryEntity.id)

    // 强制渲染场景
    viewer.scene.requestRender()

    return boundaryEntity
  }

  /**
   * 绘制坍塌边界蓝色虚线（左侧地图）
   * 在左侧地图上显示灾前位置的虚线轮廓
   * @param {HTMLElement} leftContainer - 左侧地图容器元素
   * @returns {Cesium.Entity | null} 返回创建的边界线实体
   */
  const drawCollapseBoundaryLeft = (leftContainer) => {
    if (!leftContainer) {
      console.warn('[useMapMarkers] drawCollapseBoundaryLeft: leftContainer 为空')
      return null
    }

    // 获取左侧 viewer（假设已经创建）
    const leftViewer = leftContainer._cesiumViewer
    if (!leftViewer) {
      console.warn('[useMapMarkers] drawCollapseBoundaryLeft: 左侧 viewer 未创建')
      return null
    }

    if (!Array.isArray(collapseBoundaryData) || collapseBoundaryData.length === 0) {
      console.warn('[useMapMarkers] drawCollapseBoundaryLeft: 配置数据为空')
      return null
    }

    // 清除旧的边界线（如果存在）
    if (collapseBoundaryLeftEntity.value) {
      leftViewer.entities.remove(collapseBoundaryLeftEntity.value)
      collapseBoundaryLeftEntity.value = null
    }

    // 转换坐标点
    const positions = collapseBoundaryData.map(point =>
      new Cesium.Cartesian3(point.x, point.y, point.z)
    )

    // 闭合线条（连接最后一个点到第一个点）
    positions.push(positions[0])

    console.log('[useMapMarkers] 左侧坍塌边界点位数量:', positions.length)

    // 创建蓝色虚线边界
    const boundaryEntity = leftViewer.entities.add({
      polyline: {
        positions: positions,
        width: 4,
        material: new Cesium.PolylineDashMaterialProperty({
          color: Cesium.Color.fromCssColorString('#FF0000').withAlpha(1.0), // 红色
          dashLength: 16.0, // 虚线段长度
          dashPattern: 255.0 // 虚线模式
        }),
        clampToGround: true,
        classificationType: Cesium.ClassificationType.BOTH,
        zIndex: 1
      },
      properties: new Cesium.PropertyBag({
        type: 'collapseBoundaryLeft',
        name: '坍塌边界（左侧虚线）'
      }),
      show: true
    })

    collapseBoundaryLeftEntity.value = boundaryEntity
    console.log('[useMapMarkers] 左侧坍塌边界蓝色虚线绘制完成, entityId:', boundaryEntity.id)

    // 强制渲染场景
    leftViewer.scene.requestRender()

    return boundaryEntity
  }

  /**
   * 清除坍塌边界线
   * @param {Cesium.Viewer} viewer - 右侧 viewer
   * @param {HTMLElement} leftContainer - 左侧地图容器（可选）
   */
  const clearCollapseBoundary = (viewer, leftContainer = null) => {
    // 清除右侧边界线
    if (viewer && collapseBoundaryEntity.value) {
      viewer.entities.remove(collapseBoundaryEntity.value)
      collapseBoundaryEntity.value = null
      console.log('[useMapMarkers] 右侧坍塌边界线已清除')
    }

    // 清除左侧边界线
    if (leftContainer && collapseBoundaryLeftEntity.value) {
      const leftViewer = leftContainer._cesiumViewer
      if (leftViewer) {
        leftViewer.entities.remove(collapseBoundaryLeftEntity.value)
        collapseBoundaryLeftEntity.value = null
        console.log('[useMapMarkers] 左侧坍塌边界线已清除')
      }
    }
  }

  /**
   * 显示坍塌边界线
   */
  const showCollapseBoundary = () => {
    if (collapseBoundaryEntity.value) {
      collapseBoundaryEntity.value.show = true
      console.log('[useMapMarkers] 显示右侧坍塌边界线')
    }
    if (collapseBoundaryLeftEntity.value) {
      collapseBoundaryLeftEntity.value.show = true
      console.log('[useMapMarkers] 显示左侧坍塌边界线')
    }
  }

  /**
   * 隐藏坍塌边界线
   */
  const hideCollapseBoundary = () => {
    if (collapseBoundaryEntity.value) {
      collapseBoundaryEntity.value.show = false
      console.log('[useMapMarkers] 隐藏右侧坍塌边界线')
    }
    if (collapseBoundaryLeftEntity.value) {
      collapseBoundaryLeftEntity.value.show = false
      console.log('[useMapMarkers] 隐藏左侧坍塌边界线')
    }
  }

  /**
   * 绘制塌陷区域多边形
   * 这个函数不涉及高度采样，直接使用配置中的绝对坐标
   * @param {Cesium.Viewer} viewer
   * @returns {Cesium.Cartesian3 | null} 返回塌陷区域中心点
   */
  const drawCollapseArea = (viewer) => {
    if (!viewer) {
      console.warn('[useMapMarkers] drawCollapseArea: viewer 为空')
      return null
    }

    const positions = getCollapsePositions()
    if (!positions.length) {
      console.warn('[useMapMarkers] drawCollapseArea: 配置数据为空')
      return null
    }

    const entities = []

    // 创建红色多边形
    const polygonEntity = viewer.entities.add({
      polygon: {
        hierarchy: positions,
        material: Cesium.Color.RED.withAlpha(0.35),
        perPositionHeight: true,
        outline: true,
        outlineColor: Cesium.Color.RED.withAlpha(0.8),
        classificationType: Cesium.ClassificationType.TERRAIN
      }
    })
    entities.push(polygonEntity)

    // 计算中心点
    const center = Cesium.BoundingSphere.fromPoints(positions).center

    // 将中心点转换为经纬度，然后重新创建位置，确保高度为0
    // 这样 CLAMP_TO_GROUND 才能正确工作
    const centerCartographic = Cesium.Cartographic.fromCartesian(center)
    const centerPosition = Cesium.Cartesian3.fromRadians(
      centerCartographic.longitude,
      centerCartographic.latitude,
      0  // 高度设为0，让 CLAMP_TO_GROUND 自动贴地
    )

    // 添加标签
    const labelEntity = viewer.entities.add({
      position: centerPosition,
      label: {
        text: '模拟塌陷区域',
        font: '18px "Microsoft YaHei", sans-serif',
        fillColor: Cesium.Color.WHITE,
        outlineColor: Cesium.Color.BLACK,
        outlineWidth: 2,
        showBackground: true,
        backgroundColor: Cesium.Color.fromAlpha(Cesium.Color.BLACK, 0.4),
        pixelOffset: new Cesium.Cartesian2(0, -20),
        horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
        verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
        heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
        disableDepthTestDistance: Number.POSITIVE_INFINITY
      }
    })
    entities.push(labelEntity)

    // 添加中心点标记
    const pointEntity = viewer.entities.add({
      position: centerPosition,
      point: {
        color: Cesium.Color.ORANGE,
        pixelSize: 12,
        outlineColor: Cesium.Color.WHITE,
        outlineWidth: 2,
        heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
        disableDepthTestDistance: Number.POSITIVE_INFINITY
      }
    })
    entities.push(pointEntity)

    collapseAreaEntities.value = entities
    console.log('[useMapMarkers] 塌陷区域绘制完成')

    // 强制渲染场景，确保 CLAMP_TO_GROUND 立即生效
    viewer.scene.requestRender()

    return center
  }

  /**
   * 添加固定标记点（单兵、设备、应急基地）
   * 支持地面高度采样，确保标记在地形加载后位置正确
   *
   * @param {Cesium.Viewer} viewer
   * @param {Object} options - 配置选项
   * @param {number} [options.heightOffset=10] - 相对地面的高度偏移（米）
   * @param {boolean} [options.useSampledHeights=true] - 是否使用采样高度
   * @returns {Promise<Cesium.Entity[]>}
   */
  const addFixedMarkers = async (viewer, options = {}) => {
    if (!viewer) {
      console.warn('[useMapMarkers] addFixedMarkers: viewer 为空')
      return []
    }

    const markerOptions = {
      heightOffset: options.heightOffset ?? DEFAULT_HEIGHT_OFFSET,
      useSampledHeights: options.useSampledHeights !== false
    }

    const entities = []

    // 单兵标记
    const soldierResult = await resolveCartesianFromDegrees(
      viewer,
      106.398030213,
      29.7099573,
      markerOptions.heightOffset,
      markerOptions.useSampledHeights
    )

    const soldierEntity = viewer.entities.add({
      position: soldierResult.position,
      billboard: {
        image: soldierIcon,
        width: 36,
        height: 40,
        verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
        heightReference: resolveBillboardHeightReference(soldierResult.samplingSucceeded),
        disableDepthTestDistance: Number.POSITIVE_INFINITY
      },
      properties: {
        type: 'soldier',
        name: '黄政强',
        department: '安全生产部',
        location: '目前为止距离现场0.6公里'
      }
    })
    entities.push(soldierEntity)

    // 设备标记
    const deviceResult = await resolveCartesianFromDegrees(
      viewer,
      106.402018756,
      29.7061436,
      markerOptions.heightOffset,
      markerOptions.useSampledHeights
    )

    const deviceEntity = viewer.entities.add({
      position: deviceResult.position,
      billboard: {
        image: deviceIcon,
        width: 36,
        height: 40,
        verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
        heightReference: resolveBillboardHeightReference(deviceResult.samplingSucceeded),
        disableDepthTestDistance: Number.POSITIVE_INFINITY
      },
      properties: {
        type: 'device',
        name: '无人机A',
        deviceType: 'DJI',
        location: '目前为止距离现场0.5公里'
      }
    })
    entities.push(deviceEntity)

    // 应急基地标记（距中心点北12公里）
    const center = calculateCollapseCenter()
    if (center) {
      const cartographic = Cesium.Cartographic.fromCartesian(center)
      const centerLat = Cesium.Math.toDegrees(cartographic.latitude)
      const centerLon = Cesium.Math.toDegrees(cartographic.longitude)
      const emergencyBaseLat = centerLat + 0.11 // 约12km

      const emergencyBaseResult = await resolveCartesianFromDegrees(
        viewer,
        centerLon,
        emergencyBaseLat,
        markerOptions.heightOffset,
        markerOptions.useSampledHeights
      )

      const emergencyBaseEntity = viewer.entities.add({
        position: emergencyBaseResult.position,
        billboard: {
          image: emergencyBaseIcon,
          width: 48,
          height: 48,
          verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
          heightReference: resolveBillboardHeightReference(emergencyBaseResult.samplingSucceeded),
          disableDepthTestDistance: Number.POSITIVE_INFINITY
        },
        properties: {
          type: 'emergencyBase',
          name: '应急指挥中心',
          address: 'XX区应急管理局',
          distance: '距离现场12.0公里'
        }
      })
      entities.push(emergencyBaseEntity)
    }

    markerEntities.value.push(...entities)
    console.log(`[useMapMarkers] 添加固定标记 ${entities.length} 个`)

    // 强制渲染场景，确保 CLAMP_TO_GROUND 立即生效
    viewer.scene.requestRender()

    return entities
  }

  /**
   * 生成随机标记（在中心点周围5km半径）
   * 支持地面高度采样，确保标记在地形加载后位置正确
   *
   * @param {Cesium.Viewer} viewer
   * @param {number} count - 要生成的随机标记数量
   * @param {Object} options - 配置选项
   * @param {number} [options.heightOffset=10] - 相对地面的高度偏移（米）
   * @param {boolean} [options.useSampledHeights=true] - 是否使用采样高度
   * @returns {Promise<Cesium.Entity[]>}
   */
  const addRandomMarkers = async (viewer, count = 10, options = {}) => {
    if (!viewer) {
      console.warn('[useMapMarkers] addRandomMarkers: viewer 为空')
      return []
    }

    const center = calculateCollapseCenter()
    if (!center) {
      console.warn('[useMapMarkers] addRandomMarkers: 无法计算中心点')
      return []
    }

    const cartographic = Cesium.Cartographic.fromCartesian(center)
    const centerLat = Cesium.Math.toDegrees(cartographic.latitude)
    const centerLon = Cesium.Math.toDegrees(cartographic.longitude)

    const radiusMeters = 5000
    const soldierNames = ['张三', '李四', '王五', '赵六', '刘七']
    const soldierDepartments = ['安全生产部', '应急管理部', '消防救援队']
    const deviceNames = ['无人机B', '无人机C', '监控设备A', '监控设备B', '应急车辆A']
    const deviceTypes = ['DJI']

    const latInRadians = Cesium.Math.toRadians(centerLat)
    const metersPerDegreeLat = 111320
    const metersPerDegreeLon = Math.max(1e-6, metersPerDegreeLat * Math.cos(latInRadians))

    const markerOptions = {
      heightOffset: options.heightOffset ?? DEFAULT_HEIGHT_OFFSET,
      useSampledHeights: options.useSampledHeights !== false
    }

    const entities = []

    for (let i = 0; i < count; i++) {
      const angle = Math.random() * Math.PI * 2
      const distance = Math.random() * radiusMeters
      const deltaLat = (distance * Math.cos(angle)) / metersPerDegreeLat
      const deltaLon = (distance * Math.sin(angle)) / metersPerDegreeLon
      const locationDistance = (0.3 + Math.random() * 1.7).toFixed(1)
      const isSoldier = Math.random() < 0.5

      const lon = centerLon + deltaLon
      const lat = centerLat + deltaLat

      const result = await resolveCartesianFromDegrees(
        viewer,
        lon,
        lat,
        markerOptions.heightOffset,
        markerOptions.useSampledHeights
      )

      const entity = viewer.entities.add({
        position: result.position,
        billboard: {
          image: isSoldier ? soldierIcon : deviceIcon,
          width: 36,
          height: 40,
          verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
          heightReference: resolveBillboardHeightReference(result.samplingSucceeded),
          disableDepthTestDistance: Number.POSITIVE_INFINITY
        },
        properties: isSoldier
          ? {
            type: 'soldier',
            name: soldierNames[Math.floor(Math.random() * soldierNames.length)],
            department: soldierDepartments[Math.floor(Math.random() * soldierDepartments.length)],
            location: `目前为止距离现场${locationDistance}公里`
          }
          : {
            type: 'device',
            name: deviceNames[Math.floor(Math.random() * deviceNames.length)],
            deviceType: deviceTypes[Math.floor(Math.random() * deviceTypes.length)],
            location: `目前为止距离现场${locationDistance}公里`
          }
      })
      entities.push(entity)
    }

    markerEntities.value.push(...entities)
    console.log(`[useMapMarkers] 添加随机标记 ${entities.length} 个`)

    // 强制渲染场景，确保 CLAMP_TO_GROUND 立即生效
    viewer.scene.requestRender()

    return entities
  }

  /**
   * 初始化所有标记
   * 按顺序绘制塌陷区域、添加固定标记和随机标记
   *
   * @param {Cesium.Viewer} viewer
   * @param {Object} options - 配置选项
   * @param {number} [options.heightOffset=10] - 相对地面的高度偏移（米）
   * @param {boolean} [options.useSampledHeights=true] - 是否使用采样高度
   * @param {number} [options.randomCount=10] - 随机标记数量
   * @returns {Promise<Cesium.Cartesian3 | null>} 返回塌陷区域中心点
   */
  const initializeMarkers = async (viewer, options = {}) => {
    if (!viewer) {
      console.warn('[useMapMarkers] initializeMarkers: viewer 为空')
      return null
    }

    const markerOptions = {
      heightOffset: options.heightOffset ?? DEFAULT_HEIGHT_OFFSET,
      useSampledHeights: options.useSampledHeights !== false,
      randomCount: options.randomCount ?? 10
    }

    console.log('[useMapMarkers] 开始初始化地图标记...', markerOptions)

    // 绘制塌陷区域（不涉及采样）
    const center = drawCollapseArea(viewer)

    // 添加固定标记（支持采样）
    await addFixedMarkers(viewer, markerOptions)

    // 添加随机标记（支持采样）
    await addRandomMarkers(viewer, markerOptions.randomCount, markerOptions)

    console.log('[useMapMarkers] 标记初始化完成')
    return center
  }

  /**
   * 清除所有标记
   */
  const clearMarkers = (viewer) => {
    if (!viewer) return

    // 清除塌陷区域
    collapseAreaEntities.value.forEach(entity => {
      if (entity) viewer.entities.remove(entity)
    })
    collapseAreaEntities.value = []

    // 清除标记点
    markerEntities.value.forEach(entity => {
      if (entity) viewer.entities.remove(entity)
    })
    markerEntities.value = []
  }

  /**
   * 设置所有标记点的 splitDirection
   * 用于模型对比模式，控制标记点在左侧/右侧/全屏显示
   *
   * 注意：Cesium 需要同时在 entity 和其图形属性（billboard/polygon）上设置 splitDirection
   *
   * @param {Cesium.SplitDirection} splitDirection - 分割方向
   */
  const setMarkersSplitDirection = (splitDirection) => {
    console.log(`[useMapMarkers] 设置所有标记点的 splitDirection 为: ${splitDirection}`)

    let updatedCount = 0

    // 更新塌陷区域的 splitDirection
    collapseAreaEntities.value.forEach(entity => {
      if (entity) {
        // 设置 entity 级别的 splitDirection
        entity.splitDirection = splitDirection

        // 如果有 polygon，也需要设置
        if (entity.polygon) {
          // 使用 Cesium 的 ConstantProperty 确保正确设置
          if (typeof entity.polygon.splitDirection === 'object' && entity.polygon.splitDirection.setValue) {
            entity.polygon.splitDirection.setValue(splitDirection)
          } else {
            entity.polygon.splitDirection = new Cesium.ConstantProperty(splitDirection)
          }
          console.log(`[useMapMarkers] 塌陷区域 polygon.splitDirection 已设置为:`, entity.polygon.splitDirection)
        }

        updatedCount++
      }
    })

    // 更新所有标记点的 splitDirection
    markerEntities.value.forEach((entity, index) => {
      if (entity) {
        // 设置 entity 级别的 splitDirection
        entity.splitDirection = splitDirection

        // 如果有 billboard，也需要设置（这是关键！）
        if (entity.billboard) {
          // 使用 Cesium 的 ConstantProperty 确保正确设置
          if (typeof entity.billboard.splitDirection === 'object' && entity.billboard.splitDirection.setValue) {
            entity.billboard.splitDirection.setValue(splitDirection)
          } else {
            entity.billboard.splitDirection = new Cesium.ConstantProperty(splitDirection)
          }

          // 调试输出前3个标记点的设置情况
          if (index < 3) {
            console.log(`[useMapMarkers] 标记点 ${index} (${entity.properties?.type?.getValue() || 'unknown'}) billboard.splitDirection 已设置为:`, entity.billboard.splitDirection)
          }
        }

        updatedCount++
      }
    })

    console.log(`[useMapMarkers] 已更新 ${updatedCount} 个实体的 splitDirection（包括图形属性）`)
    console.log(`[useMapMarkers] 塌陷区域数量: ${collapseAreaEntities.value.length}, 标记点数量: ${markerEntities.value.length}`)
  }

  /**
   * 隐藏所有标记点（用于模型对比模式）
   * 如果 splitDirection 不起作用，可以使用这个方法直接隐藏标记点
   */
  const hideMarkers = () => {
    console.log('[useMapMarkers] 隐藏所有标记点')

    markerEntities.value.forEach(entity => {
      if (entity) {
        entity.show = false
      }
    })
  }

  /**
   * 显示所有标记点（退出模型对比模式）
   */
  const showMarkers = () => {
    console.log('[useMapMarkers] 显示所有标记点')

    markerEntities.value.forEach(entity => {
      if (entity) {
        entity.show = true
      }
    })
  }

  /**
   * 清除应急资源标记
   * @param {Cesium.Viewer} viewer
   */
  const clearEmergencyResourceMarkers = (viewer) => {
    if (!viewer) return

    console.log(`[useMapMarkers] 清除 ${emergencyResourceEntities.value.length} 个应急资源标记`)

    emergencyResourceEntities.value.forEach(entity => {
      if (entity) viewer.entities.remove(entity)
    })
    emergencyResourceEntities.value = []
  }

  /**
   * 清除储备中心和预置点标记
   * @param {Cesium.Viewer} viewer
   */
  const clearReserveCenterMarkers = (viewer) => {
    if (!viewer) return

    console.log(`[useMapMarkers] 清除 ${reserveCenterEntities.value.length} 个储备中心/预置点标记`)

    reserveCenterEntities.value.forEach(entity => {
      if (entity) viewer.entities.remove(entity)
    })
    reserveCenterEntities.value = []
  }

  /**
   * 根据API数据添加储备中心和预置点标记
   * @param {Cesium.Viewer} viewer
   * @param {Array} reserveData - API返回的储备中心和预置点数据列表
   * @param {string} reserveData[].gl1Id - ID
   * @param {string} reserveData[].gl1Yjllmc - 名称
   * @param {number} reserveData[].gl1Lng - 经度
   * @param {number} reserveData[].gl1Lat - 纬度
   * @param {string} reserveData[].gl1Qxmc - 区县名称
   * @param {string} reserveData[].gl1Rysl - 人员数量
   * @param {string} reserveData[].gl1Zdmj - 占地面积
   * @param {string} reserveData[].gl1Lx - 级别 (1=市级, 2=区县级, 3=其他)
   * @param {Object} options - 配置选项
   * @param {number} [options.heightOffset=10] - 相对地面的高度偏移（米）
   * @returns {Promise<void>}
   */
  const addReserveCenterMarkers = async (viewer, reserveData, options = {}, disasterCenter = {}) => {
    if (!viewer) {
      console.warn('[useMapMarkers] addReserveCenterMarkers: viewer 为空')
      return
    }

    if (!Array.isArray(reserveData) || reserveData.length === 0) {
      console.warn('[useMapMarkers] addReserveCenterMarkers: reserveData 为空或不是数组')
      return
    }

    const markerOptions = {
      heightOffset: options.heightOffset ?? DEFAULT_HEIGHT_OFFSET
    }

    console.log('[useMapMarkers] 开始添加储备中心和预置点标记...', reserveData.length)
    // console.log('reserverData@@@@@', reserveData)

    const entities = []

    for (const item of reserveData) {
      if (!item.gl1Lat || !item.gl1Lng) {
        console.warn('[useMapMarkers] 数据缺少坐标信息:', item)
        continue
      }

      const result = await resolveCartesianFromDegrees(
        viewer,
        item.gl1Lng,
        item.gl1Lat,
        markerOptions.heightOffset,
        false
      )

      // 根据级别选择图标和类型标识
      // gl1Lx: "1市级", "2区县级", "3其他" 或者可能只是 "1", "2", "3"
      const levelString = String(item.gl1Lx || '').trim()
      let icon = otherEmergencyIcon // 默认使用其他应急点图标
      let type = 'other'
      let levelName = '其他'

      // 判断级别（兼容 "1市级" 和 "1" 两种格式）
      if (levelString.startsWith('1') || levelString === '1') {
        icon = cityEmergencyIcon
        type = 'city'
        levelName = '市级'
      } else if (levelString.startsWith('2') || levelString === '2') {
        icon = districtEmergencyIcon
        type = 'district'
        levelName = '区县级'
      } else if (levelString.startsWith('3') || levelString === '3') {
        icon = otherEmergencyIcon
        type = 'other'
        levelName = '其他'
        // return;
      }



      console.log(`[useMapMarkers] 添加标记: ${item.gl1Yjllmc}, 级别: ${levelString} (${levelName})`)



      // 3. 计算距离(如果接口未提供)

      let distance = null
      if (
        item.gl1Lng !== null &&
        item.gl1Lat !== null &&
        typeof disasterCenter?.longitude === 'number' &&
        typeof disasterCenter?.latitude === 'number'
      ) {
        distance = Number(
          calculateDistance(
            { longitude: item.gl1Lng, latitude: item.gl1Lat },
            { longitude: disasterCenter.longitude, latitude: disasterCenter.latitude }
          ).toFixed(2)
        )
      }

      const entity = viewer.entities.add({
        position: result.position,
        billboard: {
          image: icon,
          width: 32,
          height: 32,
          verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
          heightReference: resolveBillboardHeightReference(result.samplingSucceeded),
          disableDepthTestDistance: Number.POSITIVE_INFINITY
        },
        properties: {
          type,
          level: levelName,
          id: item.gl1Id,
          name: item.gl1Yjllmc || `${levelName}应急点`,
          district: item.gl1Qxmc || '-',
          personnelCount: item.gl1Rysl || '0',
          area: item.gl1Zdmj || '-',
          distance: distance || 0,
        }
      })
      entities.push(entity)
    }

    reserveCenterEntities.value = entities
    console.log(`[useMapMarkers] 添加储备中心/预置点标记 ${entities.length} 个`)

    // 强制渲染场景，确保 CLAMP_TO_GROUND 立即生效
    if (entities.length > 0) {
      viewer.scene.requestRender()
    }
  }


  /**
 * 角度转弧度
 * @param {number} degrees - 角度值
 * @returns {number} 弧度值
 */
  const toRadians = (degrees) => (degrees * Math.PI) / 180

  /**
 * 计算两个经纬度点之间的距离(公里)
 * 使用 Haversine 公式
 * @param {Object} pointA - { longitude, latitude }
 * @param {Object} pointB - { longitude, latitude }
 * @returns {number} 距离(km)
 */
  const EARTH_RADIUS_KM = 6371
  const calculateDistance = (pointA, pointB) => {
    if (
      typeof pointA?.longitude !== 'number' ||
      typeof pointA?.latitude !== 'number' ||
      typeof pointB?.longitude !== 'number' ||
      typeof pointB?.latitude !== 'number'
    ) {
      console.warn('[useDisasterData] calculateDistance: 坐标参数无效')
      return 0
    }

    const lat1 = toRadians(pointA.latitude)
    const lat2 = toRadians(pointB.latitude)
    const deltaLat = toRadians(pointB.latitude - pointA.latitude)
    const deltaLon = toRadians(pointB.longitude - pointA.longitude)

    const a =
      Math.sin(deltaLat / 2) ** 2 +
      Math.cos(lat1) * Math.cos(lat2) * Math.sin(deltaLon / 2) ** 2
    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))

    return EARTH_RADIUS_KM * c
  }

  /**
   * 根据API数据添加应急资源标记（养护站）
   * @param {Cesium.Viewer} viewer
   * @param {Object} emergencyData - API返回的应急资源数据
   * @param {Array} emergencyData.stations - 养护站列表
   * @param {string} emergencyData.stations[].stationId - 养护站ID
   * @param {string} emergencyData.stations[].stationName - 养护站名称
   * @param {number} emergencyData.stations[].longitude - 经度
   * @param {number} emergencyData.stations[].latitude - 纬度
   * @param {number} emergencyData.stations[].distance - 距离灾害点的距离(km)
   * @param {number} emergencyData.equipmentCount - 应急装备数量
   * @param {number} emergencyData.personnelCount - 应急人员数量
   * @param {Object} disasterPoint - 灾害点坐标 { longitude, latitude }
   * @param {Object} options - 配置选项
   * @param {number} [options.heightOffset=10] - 相对地面的高度偏移（米）
   * @returns {Promise<void>}
   */
  const addEmergencyResourceMarkers = async (viewer, emergencyData, disasterPoint, options = {}) => {
    if (!viewer) {
      console.warn('[useMapMarkers] addEmergencyResourceMarkers: viewer 为空')
      return
    }

    if (!emergencyData) {
      console.warn('[useMapMarkers] addEmergencyResourceMarkers: emergencyData 为空')
      return
    }

    const markerOptions = {
      heightOffset: options.heightOffset ?? DEFAULT_HEIGHT_OFFSET
    }

    console.log('[useMapMarkers] 开始添加应急资源标记（养护站）...', emergencyData)

    const entities = []

    // 添加养护站标记
    if (Array.isArray(emergencyData.stations)) {
      for (const station of emergencyData.stations) {
        if (!station.latitude || !station.longitude) {
          console.warn('[useMapMarkers] 养护站缺少坐标信息:', station)
          continue
        }

        const result = await resolveCartesianFromDegrees(
          viewer,
          station.longitude,
          station.latitude,
          markerOptions.heightOffset,
          false
        )

        // 根据养护站名称选择图标
        const stationIcon = station.stationName === '忠县公路交通应急物资储备中心'
          ? emergencyCenterIcon
          : emergencyBaseIcon

        const entity = viewer.entities.add({
          position: result.position,
          billboard: {
            image: stationIcon,
            width: 48,
            height: 48,
            verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
            heightReference: resolveBillboardHeightReference(result.samplingSucceeded),
            disableDepthTestDistance: Number.POSITIVE_INFINITY
          },
          properties: {
            type: 'station',
            stationId: station.stationId,
            name: station.stationName || '养护站',
            distance: station.distance || 0
          }
        })
        entities.push(entity)
      }
    }

    emergencyResourceEntities.value = entities
    console.log(`[useMapMarkers] 添加养护站标记 ${entities.length} 个`)

    // 强制渲染场景，确保 CLAMP_TO_GROUND 立即生效
    if (entities.length > 0) {
      viewer.scene.requestRender()
    }
  }


  /**
* 触发实体像素级跳动动画
* @param {Cesium.Viewer} viewer
* @param {number} duration 动画持续时间（秒）
* @param {number} pixelJumpHeight 像素跳动高度
*/
  const triggerJumpAnimation = (viewer, duration = 5, pixelJumpHeight = 30, disasterData) => {
    console.log(`[useMapMarkers] 触发像素跳动动画，持续时间 ${duration} 秒，像素高度 ${pixelJumpHeight}`)
    if (!viewer) {
      console.warn('[useMapMarkers] triggerJumpAnimation: viewer 为空')
      return
    }
    const currentDistance = disasterData.forcePreset.value.searchRadius;

    console.log('currentDistance', currentDistance)

    const allEntities = [
      ...markerEntities.value,
      ...emergencyResourceEntities.value,
      ...reserveCenterEntities.value
    ].filter(e => e.billboard && e.properties?.distance?.getValue() <= currentDistance)

    console.log('allEntities', allEntities)

    // 存储原始像素偏移量
    const entitiesData = allEntities.map(entity => ({
      entity,
      originalOffset: entity.billboard.pixelOffset
        ? new Cesium.Cartesian2(
          entity.billboard.pixelOffset.x,
          entity.billboard.pixelOffset.y
        )
        : new Cesium.Cartesian2(0, 0)
    }))

    // 动画参数
    const startTime = Date.now()
    const jumpDuration = 800 // 单次跳动周期（毫秒）
    let animationActive = true

    // 定义动画函数
    const animate = () => {
      if (!animationActive) return

      const elapsed = Date.now() - startTime
      const progress = (elapsed % jumpDuration) / jumpDuration

      // 使用正弦波计算当前像素偏移
      const currentOffset = Math.sin(progress * Math.PI * 2) * pixelJumpHeight

      // 应用像素偏移到所有实体
      entitiesData.forEach(({ entity, originalOffset }) => {
        try {
          entity.billboard.pixelOffset = new Cesium.Cartesian2(
            originalOffset.x,
            originalOffset.y - currentOffset // Y轴负方向为上移
          )
        } catch (error) {
          console.warn('[useMapMarkers] 更新实体像素偏移失败:', error)
        }
      })

      // 继续动画直到持续时间结束
      if (elapsed < duration * 1000) {
        requestAnimationFrame(animate)
      } else {
        // 恢复原始像素偏移
        entitiesData.forEach(({ entity, originalOffset }) => {
          entity.billboard.pixelOffset = originalOffset
        })
        animationActive = false
        console.log('[useMapMarkers] 像素跳动动画结束')
      }
    }

    // 启动动画
    animate()

    // 提供手动停止方法
    return () => {
      if (animationActive) {
        animationActive = false
        entitiesData.forEach(({ entity, originalOffset }) => {
          entity.billboard.pixelOffset = originalOffset
        })
        console.log('[useMapMarkers] 像素跳动动画已手动停止')
      }
    }
  }




  return {
    collapseAreaEntities,
    markerEntities,
    emergencyResourceEntities,
    reserveCenterEntities,
    collapseBoundaryEntity,
    collapseBoundaryLeftEntity,
    initializeMarkers,
    clearMarkers,
    setMarkersSplitDirection,
    hideMarkers,
    showMarkers,
    drawCollapseArea,
    drawCollapseBoundary,
    drawCollapseBoundaryLeft,
    clearCollapseBoundary,
    showCollapseBoundary,
    hideCollapseBoundary,
    addFixedMarkers,
    addRandomMarkers,
    addEmergencyResourceMarkers,
    clearEmergencyResourceMarkers,
    addReserveCenterMarkers,
    clearReserveCenterMarkers,
    getCollapseCenter: calculateCollapseCenter, // 提前获取中心点，不依赖标记初始化
    triggerJumpAnimation,
  }
}

export default useMapMarkers
