import * as Cesium from 'cesium'
import { ref } from 'vue'
import { DISASTER_CENTER, RANGE_CIRCLE_STYLE } from '../constants'

export function useRangeCircle() {
  const rangeCircleEntities = ref([]) // 改为数组存储所有范围圈实体
  const radiusLineEntities = ref([]) // 存储所有半径线实体
  const labelEntities = ref([]) // 存储所有标签实体

  const createOrUpdateRangeCircle = (
    viewer,
    radiusKm,
    options = {}
  ) => {
    if (!viewer) {
      console.warn('[useRangeCircle] viewer 为空')
      return
    }

    const {
      centerLon = DISASTER_CENTER.lon,
      centerLat = DISASTER_CENTER.lat,
      style = RANGE_CIRCLE_STYLE,
    } = options

    const radiusMeters = radiusKm * 1000

    // 检查是否已存在相同半径的范围圈
    const existingCircleIndex = rangeCircleEntities.value.findIndex(entity => {
      if (!entity) return false
      const existingRadiusKm = entity.ellipse.semiMajorAxis / 1000
      return existingRadiusKm === radiusKm
    })

    // 如果已存在相同半径的范围圈，则不需要重复创建
    if (existingCircleIndex !== -1) {
      showRangeCircle();
      console.log(`[useRangeCircle] 已存在相同半径的范围圈 (${radiusKm}km)，无需重复创建`)
      return
    }

    // 创建中心点坐标
    const centerCartesian = Cesium.Cartesian3.fromDegrees(centerLon, centerLat)

    // 计算半径线终点（正东方向）
    const ellipsoid = Cesium.Ellipsoid.WGS84
    const surfaceNormal = ellipsoid.geodeticSurfaceNormal(centerCartesian, new Cesium.Cartesian3())
    const tangent = Cesium.Cartesian3.cross(surfaceNormal, Cesium.Cartesian3.UNIT_Z, new Cesium.Cartesian3())
    Cesium.Cartesian3.normalize(tangent, tangent)
    Cesium.Cartesian3.multiplyByScalar(tangent, radiusMeters, tangent)
    const radiusEndCartesian = Cesium.Cartesian3.add(centerCartesian, tangent, new Cesium.Cartesian3())

    // 计算标签位置（3/4处，并向下偏移）
    const labelPositionCartesian = new Cesium.Cartesian3()
    Cesium.Cartesian3.lerp(centerCartesian, radiusEndCartesian, 0.75, labelPositionCartesian)
    // 计算向下偏移的方向（垂直于半径线方向）
    const offsetDirection = Cesium.Cartesian3.cross(Cesium.Cartesian3.UNIT_Z, tangent, new Cesium.Cartesian3())
    Cesium.Cartesian3.normalize(offsetDirection, offsetDirection)
    Cesium.Cartesian3.multiplyByScalar(offsetDirection, - radiusMeters * 0.2, offsetDirection) // 向下偏移 20%
    Cesium.Cartesian3.add(labelPositionCartesian, offsetDirection, labelPositionCartesian)

    let fillColor
    let fillAlpha
    let outlineColor
    if (radiusKm === 30) {
      fillColor = '#3E9EF0' // 蓝色，30km范围圈
      fillAlpha = 0.4
      outlineColor = '#49CDD2'
    } else if (radiusKm === 50) {
      fillColor = '#10FF67' // 绿色，50km范围圈
      fillAlpha = 0.2
      outlineColor = '#51BCAF'
    } else {
      fillColor = style.fillColor // 默认颜色
      fillAlpha = style.fillAlpha
      outlineColor = style.outlineColor
    }

    // 创建范围圈实体并添加到数组
    const circleEntity = viewer.entities.add({
      position: centerCartesian,
      ellipse: {
        semiMinorAxis: radiusMeters,
        semiMajorAxis: radiusMeters,
        material: Cesium.Color.fromCssColorString(fillColor).withAlpha(fillAlpha),
        outline: true,
        outlineColor: Cesium.Color.fromCssColorString(outlineColor),
        outlineWidth: 1,
        // height: 1, 
        heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
      },
      allowPicking: false
    })
    rangeCircleEntities.value.push(circleEntity)


    // 创建半径线实体并添加到数组
    const lineEntity = viewer.entities.add({
      polyline: {
        positions: [centerCartesian, radiusEndCartesian],
        width: 2,
        material: Cesium.Color.fromCssColorString(outlineColor),
      },
      allowPicking: false
    })
    radiusLineEntities.value.push(lineEntity)

    // 创建标签实体并添加到数组
    const currentLabelEntity = viewer.entities.add({
      position: labelPositionCartesian,
      label: {
        text: `${radiusKm} km`,
        font: 'bold 16px sans-serif',
        fillColor: Cesium.Color.WHITE,
        outlineColor: Cesium.Color.BLACK,
        outlineWidth: 2,
        style: Cesium.LabelStyle.FILL_AND_OUTLINE,
        verticalOrigin: Cesium.VerticalOrigin.BOTTOM, // 调整垂直原点为底部
        horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
        pixelOffset: new Cesium.Cartesian2(0, 10), // 增加像素偏移，确保标签不在半径线上
        backgroundColor: Cesium.Color.fromCssColorString('#333').withAlpha(0.7),
        backgroundPadding: new Cesium.Cartesian2(8, 6),
        showBackground: true,
      },
      allowPicking: false
    })
    labelEntities.value.push(currentLabelEntity)

    console.log(`[useRangeCircle] 已创建范围圈: ${radiusKm}km`)
  }

  // 其他函数也需要相应修改为操作数组
  const showRangeCircle = () => {
    rangeCircleEntities.value.forEach(entity => entity.show = true)
    radiusLineEntities.value.forEach(entity => entity.show = true)
    labelEntities.value.forEach(entity => entity.show = true)
  }

  const hideRangeCircle = () => {
    rangeCircleEntities.value.forEach(entity => entity.show = false)
    radiusLineEntities.value.forEach(entity => entity.show = false)
    labelEntities.value.forEach(entity => entity.show = false)
  }

  const clearRangeCircle = (viewer) => {
    if (!viewer) return

    // 清除所有实体
    rangeCircleEntities.value.forEach(entity => viewer.entities.remove(entity))
    radiusLineEntities.value.forEach(entity => viewer.entities.remove(entity))
    labelEntities.value.forEach(entity => viewer.entities.remove(entity))

    // 清空数组
    rangeCircleEntities.value = []
    radiusLineEntities.value = []
    labelEntities.value = []

    console.log('[useRangeCircle] 所有范围圈已清除')
  }

  return {
    rangeCircleEntities, // 返回数组
    createOrUpdateRangeCircle,
    showRangeCircle,
    hideRangeCircle,
    clearRangeCircle,
  }
}

