FlowChart.jsx 13.1 KB
Newer Older
1 2 3 4 5
import React, { useState, useEffect } from 'react';
import { Button, Modal, notification, Spin } from 'antd';
import { SaveNodeChange, GetFlowNode } from '@/services/platform/workflow';

import { ExclamationCircleOutlined } from '@ant-design/icons';
皮倩雯's avatar
皮倩雯 committed
6
import { Prompt } from 'react-router-dom';
7 8 9 10 11 12 13
import * as go from 'gojs';
import styles from '../workflow.less';
import NodeModal from './flowChartComponents/NodeModal';
import imgUrl from '@/assets/images/icons/closeBlue.png';
const { confirm } = Modal;
let diagram = null;
const FlowChart = props => {
皮倩雯's avatar
皮倩雯 committed
14
  const { flowData, flowID, chartLoading, leaveCallBack } = props;
15 16 17 18 19 20 21 22 23
  const [visible, setVisible] = useState(false);
  const [editMsg, setEditMsg] = useState({}); // 编辑节点的信息
  const [modalType, setModalType] = useState(''); // 存入弹窗是编辑还是新增
  const [nodeKey, setNodeKey] = useState(''); // 存入编辑节点的key
  const [DeleteNodes, setDeleteNodes] = useState([]); // 删除节点数组
  const [DeleteLines, setDeleteLines] = useState([]); // 删除线数组
  const [deleteLine, setDeleteLine] = useState(); // 删除的线id
  const [deleteNode, setDeleteNode] = useState(); // 删除的节点id
  const [AddNodes, setAddNodes] = useState([]); // 新增数组
皮倩雯's avatar
皮倩雯 committed
24
  const [initFlowData, setInitFlowData] = useState({}); // 初始数据,用来比对是否有修改流程图
25 26 27 28
  const [currentFlowData, setCurrentFlowData] = useState({
    Nodes: [],
    Lines: [],
  }); // 组件内得流程图数据
皮倩雯's avatar
皮倩雯 committed
29
  const [showLeaveTip, setShowLeaveTip] = useState(false); // 离开路由是否又提醒
30 31 32 33 34 35 36 37 38 39 40 41
  const objGo = go.GraphObject.make;
  // 监听删除,给删除数组里添加删除id
  useEffect(() => {
    if (deleteLine) {
      setDeleteLines([...DeleteLines, deleteLine]);
    }
  }, [deleteLine]);
  useEffect(() => {
    if (deleteNode) {
      setDeleteNodes([...DeleteNodes, deleteNode]);
    }
  }, [deleteNode]);
皮倩雯's avatar
皮倩雯 committed
42
  // 初始化
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
  useEffect(() => {
    // 初始化流程图
    init();
    // 监听节点或线的删除事件
    diagram.addDiagramListener('SelectionDeleted', e => {
      e.subject.each(n => {
        // 如果删除得节点不是新增得就给id放入到删除节点数组中
        if (n.data.NodeId && !AddNodes.some(item => item === n.data.NodeId)) {
          setTimeout(() => {
            setDeleteNode(n.data.NodeId);
          }, 0);
        }
        if (n.data.LineId) {
          setTimeout(() => {
            setDeleteLine(n.data.LineId);
          }, 0);
        }
      });
    });
    // 监听节点或线的删除前事件
    diagram.commandHandler.canDeleteSelection = () =>
      // 用例获取选中的节点或线
      diagram.selection.all(() => {
        // 判断是否存在不允许删除的节点或线
        showDeleteConfirm();
        return false;
      });
  }, []);
  useEffect(() => {
    if (flowData) {
      // 每次切换时清空删除得id数组跟新增得id数组
      setDeleteNodes([]);
      setDeleteLines([]);
      setAddNodes([]);
      setDeleteNode('');
      setDeleteLine('');
      setCurrentFlowData(JSON.parse(JSON.stringify(flowData)));
皮倩雯's avatar
皮倩雯 committed
80
      setShowLeaveTip(false);
81 82 83 84 85 86 87 88
    }
  }, [flowData]);
  // 存入在树形流程中选择得流程数据
  useEffect(() => {
    let nodeDataArray;
    if (currentFlowData.Nodes.length === 0) {
      nodeDataArray = [];
    } else {
皮倩雯's avatar
皮倩雯 committed
89 90
      // 处理老数据,让老数据可以正常展示
      nodeDataArray = currentFlowData.Nodes.map((item, index) => {
91 92 93
        let obj;
        obj = item;
        obj.key = item.NodeId;
皮倩雯's avatar
皮倩雯 committed
94 95 96 97 98 99 100
        if (obj.points === '') {
          if (obj.NodeType === '1') {
            obj.points = `${(index * 200).toString()}" 100"`;
          } else {
            obj.points = `${(index * 200).toString()}" -22"`;
          }
        }
101 102 103
        return obj;
      });
    }
皮倩雯's avatar
皮倩雯 committed
104 105 106 107 108 109 110 111 112
    // 保存初始数据
    setInitFlowData(
      JSON.parse(
        JSON.stringify({
          Nodes: nodeDataArray,
          Lines: currentFlowData.Lines,
        }),
      ),
    );
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
    diagram.model = go.Model.fromJson({
      linkFromPortIdProperty: 'fromPort', // 所需信息:
      linkToPortIdProperty: 'toPort', // 标识数据属性名称
      nodeDataArray,
      linkDataArray: currentFlowData.Lines,
    });
  }, [currentFlowData]);
  // 删除提醒
  const showDeleteConfirm = () => {
    confirm({
      title: '确定要删除所选中的节点吗?',
      icon: <ExclamationCircleOutlined />,
      content: '',
      okText: '是',
      okType: 'danger',
      cancelText: '否',
      onOk() {
        delNode();
      },
      onCancel() {},
    });
  };
  // 删除节点
  const delNode = () => {
皮倩雯's avatar
皮倩雯 committed
137 138
    setShowLeaveTip(true);
    leaveCallBack(true);
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
    diagram.commandHandler.deleteSelection();
  };
  // 流程图初始化
  const init = () => {
    diagram = objGo(go.Diagram, 'myDiagramDiv', {
      'undoManager.isEnabled': true,
      allowDragOut: false,
      'dragSelectingTool.isEnabled': false, // 禁止多选
      allowCopy: false, // 禁止复制
      nodeSelectionAdornmentTemplate: objGo(
        go.Adornment,
        'Auto',
        objGo(go.Shape, 'Rectangle', { fill: 'white', stroke: null }),
      ), // 去掉节点点击时的边框颜色
    });
    // 节点配置
    diagram.nodeTemplate = objGo(
      go.Node,
      'Auto',
      new go.Binding('location', 'points', go.Point.parse).makeTwoWay(
        go.Point.stringify,
      ),
      // 节点样式配置
      objGo(
        go.Panel,
        objGo(
          go.Shape,
          new go.Binding('width', 'NodeType', v => (v === '0' ? 135 : 105)),
          new go.Binding('height', 'NodeType', v => (v === '0' ? 75 : 105)),
          new go.Binding('figure', 'NodeType', v =>
            v === '0' ? 'RoundedRectangle' : 'Ellipse',
          ),
          new go.Binding('strokeWidth', 'NodeType', v => (v === '0' ? 1 : 15)),
          new go.Binding('stroke', 'NodeType', v =>
            v === '0' ? '#0587E0' : '#D7EFFF',
          ),
          new go.Binding('fill', 'NodeType', v => {
            if (v === '0') {
              return '#DCF2FE';
            }
            if (v === '1') {
              return '#077BD6';
            }
            if (v === '2') {
              return '#077BD6';
            }
            return '';
          }),
        ),
      ),
      // 节点文案
      objGo(
        go.TextBlock,
        { maxSize: new go.Size(130, NaN), wrap: go.TextBlock.WrapFit },
        new go.Binding('text', 'NodeName'),
        new go.Binding('stroke', 'NodeType', v =>
          v === '0' ? '#077BD6' : '#fff',
        ),
      ),
      objGo(
        go.Picture,
        {
          source: imgUrl, // 图片路径
          desiredSize: new go.Size(12, 12),
          alignment: go.Spot.TopRight, // 对齐主要形状上的端口
          alignmentFocus: go.Spot.TopRight, // 就在形状里面
          click() {
            // 删除节点
            showDeleteConfirm();
          },
        },
        new go.Binding('margin', 'NodeType', v => (v === '0' ? 5 : 17)),
      ),
      // 我们的小命名端口,每侧一个:
      makePort('T', go.Spot.Top, true, true),
      makePort('L', go.Spot.Left, true, true),
      makePort('R', go.Spot.Right, true, true),
      makePort('B', go.Spot.Bottom, true, true),
      {
        // 处理鼠标进入/离开事件以显示/隐藏端口
        mouseEnter(e, node) {
          showSmallPorts(node, true);
        },
        mouseLeave(e, node) {
          showSmallPorts(node, false);
        },
        // 处理双击
        doubleClick(e, node) {
          // 双击事件
          handlerDC(e, node); // 双击执行的方法
        },
      },
    );
    // 链接设置
    diagram.linkTemplate = objGo(
      go.Link,
      {
        routing: go.Link.Orthogonal,
        curve: go.Link.JumpOver,
        corner: 5,
        toShortLength: 4,
      },
      new go.Binding('points').makeTwoWay(),
      objGo(
        go.Shape, // 链接路径形状
        { isPanelMain: true, strokeWidth: 2, stroke: '#1685FF' },
      ),
      objGo(
        go.Shape, // 箭头
        { toArrow: 'Standard', stroke: '#1685FF', fill: '#1685FF' },
      ),
    );
    // 初始化流程的节点数组
    diagram.model = objGo(go.GraphLinksModel, {
      linkFromPortIdProperty: 'fromPort', // 所需信息:
      linkToPortIdProperty: 'toPort', // 标识数据属性名称
      nodeDataArray: currentFlowData.Nodes,
      linkDataArray: currentFlowData.Lines,
    });
  };
  // 是否显示端口
  const showSmallPorts = (node, show) => {
    node.ports.each(port => {
      if (port.portId !== '') {
        // 不要更改默认端口,这是大形状
        port.fill = show ? 'rgba(5,135,224,.3)' : null;
      }
    });
  };
  // 创建节点端口
  const makePort = (name, spot, output, input) =>
    // 端口基本上只是一个小的透明方块
    objGo(go.Shape, 'Circle', {
      fill: null, // 默认情况下不可见; 由 showSmallPorts 设置为半透明灰色,定义如下
      stroke: null,
      desiredSize: new go.Size(8, 8),
      alignment: spot, // 对齐主要形状上的端口
      alignmentFocus: spot, // 就在形状里面
      portId: name, // 将此对象声明为“端口”
      fromSpot: spot,
      toSpot: spot, // 声明链接可以在此端口连接的位置
      fromLinkable: output, // 是否允许用户绘制的链接到这里
      toLinkable: input, // 声明用户是否可以从这里绘制链接
      cursor: 'pointer', // 显示不同的光标以指示潜在的链接点
    });
  // 双击节点
  const handlerDC = (e, node) => {
    setNodeKey(node.part.data.key);
    setEditMsg(node.part.data);
    setModalType('edit');
    setVisible(true);
  };
  // 新增节点
  const addNode = () => {
    setModalType('add');
    setVisible(true);
  };
  // 节点配置回调
  const nodeCallBack = obj => {
    if (modalType === 'add') {
      // 新增节点
      let { nodes } = diagram;
      let keyArr = [];
      // 遍历输出节点对象
      nodes.each(node => {
        keyArr = [...keyArr, Number(node.data.key)];
      });
      // 新增得key比最大得key值+1
      let newKey;
      if (keyArr.length === 0) {
        newKey = 1;
      } else {
        newKey = keyArr.reduce((num1, num2) => (num1 > num2 ? num1 : num2)) + 1;
      }
      diagram.model.addNodeData({
        key: newKey,
        NodeId: newKey,
        ...obj,
      });
      setAddNodes([...AddNodes, newKey]);
    }
    if (modalType === 'edit') {
      // 编辑节点
      let nodeData = diagram.model.findNodeDataForKey(nodeKey);
      const { NodeName, NodeType, roleList } = obj;
      nodeData.NodeName = NodeName;
      nodeData.NodeType = NodeType;
      nodeData.NodeId = nodeKey;
      nodeData.roleList = roleList;
      diagram.model.updateTargetBindings(nodeData);
    }
皮倩雯's avatar
皮倩雯 committed
330 331 332 333 334 335 336 337 338 339 340 341 342 343 344
    // 关闭时进行数据比对看数据是否改变
    let diagramObj = JSON.parse(diagram.model.toJson());
    let stageJson = {
      Nodes: diagramObj.nodeDataArray,
      Lines: diagramObj.linkDataArray,
    };
    if (
      JSON.stringify(stageJson.Nodes) === JSON.stringify(initFlowData.Nodes)
    ) {
      setShowLeaveTip(false);
      leaveCallBack(false);
    } else {
      leaveCallBack(true);
      setShowLeaveTip(true);
    }
345 346 347 348 349 350
    setVisible(false);
  };
  // 获取保存后的流程数据
  const getFlowData = () => {
    GetFlowNode({ flowID }).then(res => {
      if (res.code === 0) {
皮倩雯's avatar
皮倩雯 committed
351 352 353
        // 保存后离开不用提醒要修改数据了
        setShowLeaveTip(false);
        leaveCallBack(false);
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
        setCurrentFlowData(res.data);
      } else {
        notification.error({
          title: '提示',
          duration: 3,
          description: res.msg,
        });
      }
    });
  };
  // 保存流程
  const saveFlow = () => {
    let diagramObj = JSON.parse(diagram.model.toJson());
    SaveNodeChange({
      FlowId: flowID,
      DeleteNodes,
      DeleteLines,
      Lines: diagramObj.linkDataArray,
      Nodes: diagramObj.nodeDataArray,
    })
      .then(res => {
        if (res.code === 0) {
          getFlowData();
          notification.success({
            message: '提示',
            duration: 3,
            description: '保存成功',
          });
        } else {
          notification.error({
            message: '提示',
            duration: 8,
            description: res.msg,
          });
        }
      })
      .catch(() => {
        notification.error({
          message: '提示',
          duration: 3,
          description: '网络异常请稍后重试',
        });
      });
  };
  return (
    <>
皮倩雯's avatar
皮倩雯 committed
400 401 402 403
      <Prompt
        message="编辑的内容还未保存,确定要离开该页面吗?"
        when={showLeaveTip}
      />
404 405
      <div className={styles.buttonList}>
        <Button onClick={() => addNode()}>添加节点</Button>
皮倩雯's avatar
皮倩雯 committed
406 407 408
        <Button type="primary" onClick={() => saveFlow()}>
          保存
        </Button>
409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
      </div>
      <Spin spinning={chartLoading}>
        <div
          id="myDiagramDiv"
          className={styles.myDiagramDiv}
          style={{ backgroundColor: '#EFF8FA' }}
        />
      </Spin>

      <NodeModal
        visible={visible}
        editMsg={editMsg}
        modalType={modalType}
        handleCancel={() => setVisible(false)}
        onSubumit={obj => nodeCallBack(obj)}
      />
    </>
  );
};

export default FlowChart;