<template>
  <div class="widget-ComPopup" :class="`widget-ComPopup-${id}`" :ref="`widget-ComPopup-${id}`">
    <slot />
  </div>
</template>

<script lang="ts">
import { Vue, Component, Prop, Watch } from 'vue-property-decorator'
const Cesium = (window as any).Cesium
//公共弹窗载体
@Component({ name: 'ComPopup' })
export default class ComPopup extends Vue {
  @Prop({ type: String }) id!: string
  @Prop({ type: String, required: true }) mapContainerId!: string
  viewer
  _renderCallback = null
  isExist = null
  mounted() {
    this.viewer = (window as any).viewer
  }
  get boxTarget() {
    return this.$refs[`widget-ComPopup-${this.id}`] as any
  }
  //初始化
  initBox() {
    this.isExist = document.querySelector('#' + this.mapContainerId).appendChild(this.boxTarget)
  }
  //设置位置
  setPosition(position) {
    if (!this.isExist) this.initBox()
    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-ComPopup-${this.id}`)) {
      document.querySelector(`.widget-ComPopup-${this.id}`).remove()
      this.isExist = null
    }
  }
}
</script>

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