import * as Cesium from 'cesium'

export const getLngLatDistance = (
  lat1: number,
  lng1: number,
  lat2: number,
  lng2: number,
) => {
  const radLat1 = (lat1 * Math.PI) / 180.0
  const radLat2 = (lat2 * Math.PI) / 180.0
  const a = radLat1 - radLat2
  const b = (lng1 * Math.PI) / 180.0 - (lng2 * Math.PI) / 180.0
  let s =
    2 *
    Math.asin(
      Math.sqrt(
        Math.pow(Math.sin(a / 2), 2) +
          Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2),
      ),
    )
  s = s * 6378.137 // EARTH_RADIUS;
  s = Math.round(s * 10000) / 10000
  return s * 1000
}

// 获取限polyline长度
export const getPolylineLength = (entity: any) => {
  let length = 0

  // 获取Polyline的所有顶点位置
  const positions = entity.polyline.positions.getValue()

  for (let i = 0; i < positions.length - 1; ++i) {
    const startPosition = positions[i]
    const endPosition = positions[i + 1]

    // 使用Cesium提供的distanceBetween函数计算两个顶点之间的距离
    const distance = Cesium.Cartesian3.distance(startPosition, endPosition)

    // 将每个顶点之间的距离相加得到总长度
    length += distance
  }

  return length
}

// 创建三角广告牌
export const createTriangleMarker = (title: string | number, color: string) => {
  // 创建canvas绘制广告牌
  const billboard = document.createElement('canvas')
  billboard.width = 30
  billboard.height = 30
  const ctx: HTMLCanvasElement | any = billboard.getContext('2d')
  ctx.beginPath()
  ctx.moveTo(0, 0)
  ctx.lineTo(30, 0)
  ctx.lineTo(15, 22)
  ctx.fillStyle = color
  ctx.fill()
  ctx.font = '18px serif'
  ctx.fillStyle = '#ffffff'
  ctx.fillText(title, 10, 15)
  ctx.closePath()
  return billboard
}
