<template>
  <vc-viewer :shouldAnimate="true" :showCredit="false" :infoBox="false" @ready="onViewerReady">
    <vc-layer-imagery>
      <vc-provider-imagery-singletile :url="earth" />
    </vc-layer-imagery>

    <vc-entity :show="show" :position="position">
      <vc-graphics-billboard :image="pin" :verticalOrigin="1" />
    </vc-entity>
  </vc-viewer>
</template>


<script lang="ts" setup>
import { reactive, computed } from 'vue'
import { getPosition } from '../api/util'
import pin from '../assets/pin.png'
import earth from '../assets/earth.jpg'

const position = reactive({ lng: NaN, lat: NaN })
const show 		 = computed(() => {
  const { lng, lat } = position

  if (isNaN(lng) || lng > 180 || lng < -180) return false
  if (isNaN(lat) || lat > 90  || lat < -90 ) return false

  return true
})

// 设置地球自转动画效果
const onViewerReady = ({ Cesium, viewer }) => {
  const { JulianDate, Cartesian3 } = Cesium
  const { clock, scene }           = viewer

  let prev = clock.currentTime
  clock.onTick.addEventListener(() => {
    const current = clock.currentTime

    const interval = JulianDate.toDate(current) - JulianDate.toDate(prev)
    prev = current
    
    scene.camera.rotate(
      Cartesian3.UNIT_Z,
      (Math.PI / (24 * 60 * 60)) * interval * 1,
    );
  })
}


const update = (nmea) => {
  const newPosition = getPosition(nmea)
  if (!newPosition) return
  
  Object.assign(position, newPosition)
}

defineExpose({ update })
</script>