import {ToolsView} from "@antv/x6";
import {createApp} from "vue";
import contextMenuTool from './context-menu-tool.vue'

let app: any = null
let timer: any = null;
const ID = 'graph-dropdown'
if (!document.getElementById(ID)) {
  const dom = document.createElement('div')
  dom.id = ID
  document.body.appendChild(dom)
}
class ContextMenuTool extends ToolsView.ToolItem {
  toggleContextMenu(visible, pos = {x: 0, y: 0}) {
    const dom = document.getElementById(ID)
    if (app) {
      // 清空上次内容
      app.unmount();
      if (dom) {
        dom.innerHTML = '';
      }
      app = null
    }
    document.removeEventListener('mousedown', this.onMouseDown)

    if (visible && pos) {
      console.log(this.options)
      app = createApp(contextMenuTool, {
        data: this.options.data,
        onClose: this.onMouseDown
      })
      // 减去本身元素的宽高
      if (dom) {
        dom.style = `left: ${pos.x}px;top: ${pos.y}px;position: absolute;z-index: 100;`
      }
      app.mount(`#${ID}`)
      document.addEventListener('mousedown', this.onMouseDown)
    }
  }


  onMouseDown = (e, bool = false) => {
    if (bool || !e.target.getAttribute('context-menu-tools')) {
      timer = window.setTimeout(() => {
        this.toggleContextMenu(false)
      },200)
    }
  }

  onContextMenu({ e }) {
    if (timer) {
      clearTimeout(timer)
      timer = 0
    }
    this.toggleContextMenu(true, { x: e.pageX, y: e.pageY })
  }

  delegateEvents() {
    this.cellView.on('cell:contextmenu', this.onContextMenu, this)
    return super.delegateEvents()
  }

  onRemove() {
    this.cellView.off('cell:contextmenu', this.onContextMenu, this)
  }
}

ContextMenuTool.config({
  tagName: 'div',
  isSVGElement: false,
  data: {},
})

export {
  ContextMenuTool
}
