import { createVNode, render } from 'vue'
// import component from
export default class Bubble {
  constructor (viewer) {
    this.viewer = viewer
    this.bubbleNode = null
    this.props = null
  }

  init (props, type) {
    const component = import(`./bubbleComponents/${type}Bubble.vue`)
    if (this.bubbleNode) {
      this.windowClose()
    }
    component.then(res => {
      const instance = res.default
      this.position = props.position._value
      const app = createVNode(instance, {
        info: props.props
      })
      // this.bubbleNode = app.el
      this.bubbleNode = document.createElement('div')
      render(app, this.bubbleNode)
      // this.bubbleNode = app.el
      // this.viewer.cesiumWidget.container.appendChild(this.bubbleNode)
      document.body.appendChild(this.bubbleNode)
      this.addPostRender()
    })
    // this.position = props.position._value
    // const app = createVNode(component, {
    //   info: props.props
    // })
    // debugger
    // this.bubbleNode = document.createElement('div')
    // render(app, this.bubbleNode)
    // document.body.appendChild(this.bubbleNode)
    // this.addPostRender()
  }

  addPostRender () {
    this.viewer.scene.postRender.addEventListener(this.postRender, this)
  }

  postRender () {
    if (!this.bubbleNode || !this.bubbleNode.style) return
    this.bubbleNode.style.position = 'absolute'
    const canvasHeight = this.viewer.scene.canvas.height
    const windowPosition = new Cesium.Cartesian2()
    Cesium.SceneTransforms.wgs84ToWindowCoordinates(
      this.viewer.scene,
      this.position,
      windowPosition
    )
    this.bubbleNode.style.bottom =
      canvasHeight - windowPosition.y + 60 + 'px'
    const elWidth = this.bubbleNode.offsetWidth
    this.bubbleNode.style.left = windowPosition.x - elWidth / 2 + 110 + 'px'

    const camerPosition = this.viewer.camera.position
    let height = this.viewer.scene.globe.ellipsoid.cartesianToCartographic(camerPosition).height
    height += this.viewer.scene.globe.ellipsoid.maximumRadius
    if ((!(Cesium.Cartesian3.distance(camerPosition, this.position) > height)) && this.viewer.camera.positionCartographic.height < 50000000) {
      this.bubbleNode.style.display = 'block'
    } else {
      this.bubbleNode.style.display = 'none'
    }
  }

  windowClose () {
    if (!this.bubbleNode) return
    document.body.removeChild(this.bubbleNode)
    this.bubbleNode = null
    this.viewer.scene.postRender.removeEventListener(this.postRender, this)
  }
}
