export class Tooltip {
  static pluginName = 'Tooltip'
  __clickOver = false;

  constructor({ lf }) {
    this.lf = lf;
    this.bindEvent();
  }

  render(_, toolOverlay) {
    this.__toolOverlay = toolOverlay;
  }

  bindEvent() {
    this.lf.on('node:click', ({ data }) => {
      setTimeout(() => {
        this._activeData = data;
        this.createTootip();
        this.showTooltip();
        this.__clickOver = true;
      }, 100)
    })

    document.addEventListener('click', this.onClickOutside.bind(this))
  }

  onClickOutside(event) {
    if (this.__clickOver && !this.__tooltipDOM?.contains(event.target)) {
      this.__clickOver = false;
      this.__tooltipDOM?.remove();
    }
  }

  createTootip() {
    this.__tooltipDOM = document.createElement('div');
  }

  showTooltip() {
    const { properties } = this._activeData;
    if (!properties.time || !properties.name) return;

    const [x, y] = this.getTootipPosition();
    this.__tooltipDOM.className = 'lf__tooltip';

    this.__tooltipDOM.innerHTML = `
     <div class="tooltip__arrow"></div>
     <p>审批人 : ${properties.name}</p>
     <p>时间 : ${properties.time}</p>
    `

    this.__tooltipDOM.style.position = 'absolute';
    this.__tooltipDOM.style.top = `${y}px`;
    this.__tooltipDOM.style.left = `${x + 10}px`;
    this.__toolOverlay.appendChild(this.__tooltipDOM);
  }

  getTootipPosition() {
    const data = this._activeData;
    const Model = this.lf?.graphModel.getElement(data.id);

    let x, y;

    if (Model?.BaseType === 'node') {
      x = data.x + Model.width / 2;
      y = data.y - Model.height + 5;
    }

    return this.lf?.graphModel.transformModel.CanvasPointToHtmlPoint([x, y])
  }
}
