import { ref } from 'vue'
// 注册事件并绑定
const useGraphHandle = (emits) => {
  const handleAutoResize = (graph, containerDom) => {
    if (typeof window !== 'undefined')
      window.onresize = () => {
        console.log('onresize')
        if (!graph || graph.get('destroyed')) return
        if (!containerDom || !containerDom.scrollWidth || !containerDom.scrollHeight) return
        graph.changeSize(containerDom.scrollWidth, containerDom.scrollHeight)
      }
  }

  const selectedNode = ref(null)

  // 处理选中节点
  const handleSelectedNode = (targetNode, graph) => {
    // 如果已经有选中的节点，则取消选中状态
    if (selectedNode.value && selectedNode.value !== targetNode) {
      graph.updateItem(
        selectedNode.value,
        {
          selected: false
        },
        false
      )
    }
    // 更新状态
    graph.updateItem(
      targetNode,
      {
        selected: true
      },
      false
    )
    // 记录选中的节点
    selectedNode.value = targetNode
  }

  // 主内容区域点击事件
  const handleContentNodeClick = (graph) => {
    graph.on('contentNode:click', (evt) => {
      handleSelectedNode(evt.item, graph)
      emits('onEdit', evt.item, graph)
    })
  }

  // 提示区域（选项区）点击事件
  const handleTipsNodeClick = (graph) => {
    graph.on('tipsNode:click', (evt) => {
      const pNode = evt.item.get('parent')
      handleSelectedNode(pNode, graph)
      emits('onEdit', pNode, graph)
    })
  }

  // 初始化绑定事件
  const initHandle = (graph, containerDom) => {
    handleAutoResize(graph, containerDom)
    handleContentNodeClick(graph)
    handleTipsNodeClick(graph)
  }

  return {
    initHandle
  }
}

export default useGraphHandle
