<template>
  <el-dialog v-model="visible" title="组织机构结构图" width="80%">
    <div style="height: calc(100vh - 200px)">
      <RelationGraph ref="relationGraphRef" :options="graphOptions" />
    </div>
  </el-dialog>
</template>

<script setup>
import { useVModel } from "@vueuse/core";
import RelationGraph from "relation-graph/vue3";
import { nextTick, ref, watchEffect } from "vue";

const props = defineProps({
  visible: {
    type: Boolean,
    required: true,
    default: false,
  },
  treeData: {
    type: Array,
    required: true,
    default: () => [],
  },
});
const emits = defineEmits(["update:visible"]);
const visible = useVModel(props, "visible", emits);
const relationGraphRef = ref(null);
const graphOptions = ref({
  disableDragNode: "false",
  layouts: [
    {
      label: "中心",
      layoutName: "tree",
      layoutClassName: "seeks-layout-center",
      defaultJunctionPoint: "border",
      defaultNodeShape: 0,
      defaultLineShape: 1,
      min_per_width: 40,
      max_per_width: 70,
      min_per_height: 200,
    },
  ],
  buttonloading: false,
  defaultLineMarker: {
    markerWidth: 12,
    markerHeight: 12,
    refX: 6,
    refY: 6,
    data: "M2,2 L10,6 L2,10 L6,6 L2,2",
  },
  defaultNodeShape: 1,
  defaultLineShape: 2,
  defaultJunctionPoint: "tb",
  defaultNodeBorderWidth: 0,
  backgroundColor: "#08163b",
  defaultLineColor: "rgba(0, 186, 189, 1)",
  defaultNodeColor: "rgba(0, 206, 209, 1)",
  defaultNodeHeight: 150,
  defaultNodeWidth: 60,
});
const fnRecursion = (data) => {
  let arr = [];
  for (let i = 0; i < data.length; i++) {
    if (data[i].nodes && data[i].nodes.length > 0) {
      arr.push(data[i]);
      arr = arr.concat(fnRecursion(data[i].nodes));
    } else {
      arr.push(data[i]);
    }
  }
  return arr;
};
const fnSeeksGraph = async () => {
  await nextTick();
  const treeData = fnRecursion(props.treeData);
  const __graph_json_data = {
    rootId: props.treeData[0].name,
    nodes: [],
    links: [],
  };
  for (let i = 0; i < treeData.length; i++) {
    if (i === 0) {
      __graph_json_data.nodes.push({
        id: treeData[i].name,
        text: treeData[i].name,
        width: 150,
        height: 60,
      });
    } else {
      __graph_json_data.nodes.push({
        id: treeData[i].name,
        text: treeData[i].name,
      });
    }
    for (let j = 0; j < treeData.length; j++) {
      if (treeData[i].id === treeData[j].pId) {
        __graph_json_data.links.push({
          from: treeData[i].name,
          to: treeData[j].name,
        });
      }
    }
  }
  relationGraphRef.value.setJsonData(__graph_json_data, () => {});
};
watchEffect(() => {
  if (visible.value) fnSeeksGraph();
});
</script>

<style scoped lang="scss"></style>
