import * as THREE from "three";
import convertTool from "@/utils";

let labels = []

class Label2D {
  constructor(o = {}) {
    this.position = o.position
    this.elem = window.$(o.innerHTML || '<div ><a></a></div>');

    window.$(o.domElement).append(this.elem)
    this.pos2d = new THREE.Vector3

    this.elem.css({ position: 'absolute', 'z-index': 999 })
    this.clickFun = o.clickFun;
    this.clickFun && this.elem.on('click', this.clickFun.bind(this))


    this.visible = true
    this.camera = o.camera
    this.domElement = o.domElement
    this.modelobj = o.modelobj

    this.shelterByModel = o.shelterByModel

    labels.push(this)

    this.init()

  }

  init() {
    this.update()
  }



  update() {
    if (!this.position || !this.visible) return

    var p = convertTool.getPos2d(this.position, this.camera, this.domElement);

    if (!p || !p.trueSide) {
      this.elem.css('display', 'none'); return;
    }

    //判断label是否被模型遮挡，遮挡则消失(如果是漫游模式最好提前计算visiblePanos)


    if (this.shelterByModel && convertTool.ifShelter(this.position, p.vector, this.camera, this.modelobj,this.domElement)) {
      this.elem.css('display', 'none'); return;
    }

    this.elem.css({
      left: p.pos.x + 'px',
      top: p.pos.y + 'px'
    })


    this.elem.css('display', 'block');
    this.pos2d = p.vector;

  }

  setVisible(visi, reason, level = 0, type) {
    convertTool.updateVisible(this, reason, visi, level, type)

    if (!this.visible) {
      this.elem.css('display', 'none');
    } else {
      this.update()
    }
  }


  setPos(pos) {
    this.position = pos;
    this.update()
  }

  dispose() {
    this.elem.remove();
    this._listeners = {}
    this.dispatchEvent({ type: 'dispose' })
    let index = labels.indexOf(this)
    index > -1 && labels.splice(index, 1)
  }


}


export default Label2D
