<!--
 * @Descripttion: 
 * @version: 
 * @Author: xieqy
 * @Date: 2022-08-12 10:32:52
 * @LastEditors: xieqy
 * @LastEditTime: 2022-08-15 17:42:46
-->
<template>
  <div class="widget-ComMapBox" :class="`widget-ComMapBox-${id}`" :ref="`widget-ComMapBox-${id}`">
    <slot />
  </div>
</template>

<script lang="ts">
import { Vue, Component, Prop, Watch } from 'vue-property-decorator'
const Cesium = (window as any).Cesium
//公共弹窗载体
@Component({ name: 'ComMapBox' })
export default class ComMapBox extends Vue {
  @Prop({ type: String }) id!: string
  viewer
  _renderCallback = null
  isExist = null
  mounted() {
    this.viewer = (window as any).viewer
    // this.initBox()
  }
  get boxTarget() {
    return this.$refs[`widget-ComMapBox-${this.id}`] as any
  }
  get mapContainerId() {
    return this.$store.state.bigScreen.mapContainerId
  }
  //初始化
  initBox() {
    // this.remove()
    this.isExist = document.querySelector('#' + this.mapContainerId).appendChild(this.boxTarget)
  }
  //设置位置
  setPosition(position) {
    if (!this.isExist) this.initBox()
    //Cesium和网页元素是两个不相干的东西，它们的唯一纽带就是Canvas，因为Canvas也是网页元素，
    //所以同步div和Canvas的坐标位置即可实现弹窗钉在地图上，而且这个同步是要实时的，这就需要不断的刷新，
    //我们使用Cesium的preRender事件来实现。
    //cartesianToCanvasCoordinates将地图笛卡尔坐标转换为画布坐标，然后设置div的top和left样式，即完成了坐标位置实时同步工作。
    this._renderCallback = this.viewer.scene.postRender.addEventListener((e) => {
      let canvasHeight = this.viewer.scene.canvas.clientHeight //canvas实际高度
      let windowPosition = new Cesium.Cartesian2()
      Cesium.SceneTransforms.wgs84ToWindowCoordinates(this.viewer.scene, position, windowPosition)
      this.boxTarget.style.bottom = canvasHeight - windowPosition.y + 14 + 5 + 'px'
      let left = this.boxTarget.clientWidth / 2
      this.boxTarget.style.left = windowPosition.x - left + 'px'
    })
  }
  //移除
  remove() {
    if (this._renderCallback) {
      this._renderCallback()
      this._renderCallback = null
    }
    if (document.querySelector(`.widget-ComMapBox-${this.id}`)) {
      document.querySelector(`.widget-ComMapBox-${this.id}`).remove()
      this.isExist = null
    }
  }
}
</script>

<style lang='scss' scoped>
.widget-ComMapBox {
  font-family: Source Han Sans CN;
  position: absolute;
}
</style>