<template>
  <div class="flow">
    <div class="content">
      <!--左侧工具栏-->
      <div id="stencil" />
      <!-- 流程图 -->
      <div class="panel">
        <!--工具栏-->
        <div class="toolbar">
          <ToolBar v-if="isReady" />
        </div>
        <!--画板-->
        <div id="container" />
      </div>
      <!--右侧工具栏-->
      <div class="config">
        <ConfigPanel v-if="isReady" />
      </div>
    </div>
    <SubFlowDialog ref="dialogRef"></SubFlowDialog>
  </div>
</template>
<script setup lang="ts">
import { $, getContainerSize } from '@/utils'
import FlowGraph from '../graph'
import ContextMenu from '@imengyu/vue3-context-menu'
import SubFlowDialog from './components/subFlow.vue'

import { Graph } from '@antv/x6'
let isReady = ref(false)
let destroyFn = ref<Function>(() => {})
onMounted(() => {
  destroyFn.value = initGraph()
})

onUnmounted(() => {
  destroyFn.value()
})

const graph = ref<Graph>()

const initGraph = () => {
  graph.value = FlowGraph.init(
    $('#container'),
    $('#container').getBoundingClientRect().width,
    $('#container').getBoundingClientRect().height
  )
  graph.value?.on('node:contextmenu', ({ e, x, y, cell, view }) => {
    const cells = graph.value?.getSelectedCells() || []
    if (!cells.length) {
      return
    }
    handleContextmenu(e, cell)
  })
  isReady.value = true
  const resizeFn = () => {
    const { width, height } = getContainerSize($('.panel'))
    graph.value?.resize(width, height - 38)
  }
  resizeFn()
  window.addEventListener('resize', resizeFn)
  return () => {
    window.removeEventListener('resize', resizeFn)
    graph.value?.dispose()
  }
}

// 右键菜单
const handleContextmenu = (e: { pageX: any; pageY: any }, cell) => {
  const cells = graph.value?.getSelectedCells() || []
  ContextMenu.showContextMenu({
    x: e.pageX,
    y: e.pageY,
    items: [
      {
        label: '编辑子流程',
        onClick: () => {
          if (cell) {
            openDialog('编辑子流程', null)
          }
        }
      },
      {
        label: '删除节点',
        onClick: () => {
          if (cells.length) {
            graph.value?.removeCells(cells)
          }
        }
      },
      {
        label: '置顶',
        onClick: () => {
          if (cells.length) {
            cells.forEach(item => item.toFront({ deep: true }))
          }
        }
      },
      {
        label: '置底',
        onClick: () => {
          if (cells.length) {
            cells.forEach(item => item.toBack({ deep: true }))
          }
        }
      }
    ]
  })
}

// 打开 dialog
const dialogRef = ref<InstanceType<typeof SubFlowDialog> | null>(null)
const openDialog = (title: string, row) => {
  const params = {
    title,
    row: { ...row },
    isView: title === '查看'
  }
  dialogRef.value?.acceptParams(params)
}
</script>
<style lang="scss" scoped>
@use './index.scss';
</style>
