<template>
  <div class="workflow">
    <TeleportContainer/>
    <el-button style="position: absolute; top: 0;left: 0; z-index: 2" type="primary" @click="getJsonData">保存配置</el-button>
    <div class="workflow-chart">
      <workflowChart :data="state.workflowData" ref="ref_workflow" @init="graph => state.graph = graph"/>
    </div>
    <workflowPanel v-model:show="state.showPanel" :node="state.currentNode"/>
  </div>
</template>

<script setup lang="ts">
import {getCurrentInstance, onMounted, provide, reactive, ref} from "vue";
import workflowChart from './chart/index.vue'
import workflowPanel from './chart/panel-index.vue'
import { getTeleport } from '@antv/x6-vue-shape'
import {data1, data2} from './mockJson'
import {WorkflowFunc} from "@/views/workflow/types";
const TeleportContainer = getTeleport()

const emits = defineEmits([])
const props = defineProps({})
const {proxy}: any = getCurrentInstance()
const state: any = reactive({
  workflowData: null,
  showPanel: false,
  currentNode: null,
  graph: null
})
const ref_workflow = ref()
provide('workflowFunc', <WorkflowFunc>{
  nodeClick: (node) => {
    state.currentNode = node
    state.showPanel = true
  },
  layoutPort: (nodeId: string, portId: string) => {
    const dom = document.getElementById(portId)
    if (dom) {
      const node = state.graph.getCellById(nodeId)
      node.portProp(portId, ['args', 'dy'], dom.offsetTop + 17)
    }
  }
})

const getJsonData = () => {
  const data = ref_workflow.value.toJSON()
  console.log(data)
  const res: any = {
    nodes: [],
    edges: []
  }
  data.cells.forEach((cell: any) => {
    if (cell.shape === 'workflow-node') {
      const node: any = {
        id: cell.id,
        x: cell.position.x,
        y: cell.position.y,
        data: cell.data
      }
      res.nodes.push(node)
    } else if (cell.shape === 'edge') {
      const edge: any = {
        target: cell.target.cell,
        source: cell.source.cell,
      }
      if (!cell.source.port.includes('end')) {
        edge.port = cell.source.port
      }
      res.edges.push(edge)
    }
  })
  console.log(res)
}
const initData = () => {
  state.workflowData = data1
}
onMounted(() => {
  initData()
})
</script>

<style lang="scss" scoped>
.workflow {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  .workflow-chart {
    width: 100%;
    height: 100%;
    z-index: 1;
  }
}
</style>