FlowChart.jsx 39.2 KB
Newer Older
1
/* eslint-disable global-require */
2
import React, { useState, useEffect, useRef } from 'react';
3
import { Button, Modal, notification, Spin, Tooltip, message } from 'antd';
邓超's avatar
邓超 committed
4
import lodash from 'lodash';
5 6 7 8 9 10 11
import {
  SaveNodeChange,
  GetFlowNode,
  FlowNodeSave,
  DeleteFlowNode,
  DeleteFlowNodes,
} from '@/services/workflow/workflow';
12

13
import { ExclamationCircleOutlined, TrophyOutlined } from '@ant-design/icons';
皮倩雯's avatar
皮倩雯 committed
14
import { Prompt } from 'react-router-dom';
15 16 17
import * as go from 'gojs';
import styles from '../workflow.less';
import NodeModal from './flowChartComponents/NodeModal';
18
import LineModal from './flowChartComponents/LineModal';
邓超's avatar
邓超 committed
19
// import imgUrl from '@/assets/images/icons/closeBlue.png';
20 21 22
import nodeEnd from '@/assets/images/workFlow/nodeEnd.svg';
import nodeGeneral from '@/assets/images/workFlow/nodeGeneral.svg';
import nodeStart from '@/assets/images/workFlow/nodeStart.svg';
23
// import cc from '@/assets/images/workFlow/cc.png';
24 25 26
import gatewayCondition from '@/assets/images/workFlow/gatewayCondition.svg';
import gatewayParallel from '@/assets/images/workFlow/gatewayParallel.svg';
import gatewayJoin from '@/assets/images/workFlow/gatewayJoin.svg';
27 28
const { confirm } = Modal;
let diagram = null;
29 30
let myPaletteNode = null;
let myPaletteGateway = null;
31
let myPaletteSubprocess = null;
32
let myOverview = null;
33
const FlowChart = props => {
34
  const { flowData, flowID, chartLoading, leaveCallBack, msg, treeVisible } = props;
35
  const [visible, setVisible] = useState(false);
36
  const [lineVisible, setLineVisible] = useState(false);
37
  const [editMsg, setEditMsg] = useState({}); // 编辑节点的信息
38
  const [lineMsg, setLineMsg] = useState({});
39
  const [modalType, setModalType] = useState(''); // 存入弹窗是编辑还是新增
邓超's avatar
邓超 committed
40
  const [LineKey, setLineKey] = useState(''); //  存入编辑线id
41 42 43 44 45 46
  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
47
  const [initFlowData, setInitFlowData] = useState({}); // 初始数据,用来比对是否有修改流程图
48 49 50 51
  const [currentFlowData, setCurrentFlowData] = useState({
    Nodes: [],
    Lines: [],
  }); // 组件内得流程图数据
皮倩雯's avatar
皮倩雯 committed
52
  const [showLeaveTip, setShowLeaveTip] = useState(false); // 离开路由是否又提醒
53
  const [buttonLoading, setButtonLoading] = useState(); // 发布按钮保存loading
54
  const [flag, setFlag] = useState(0);
55
  const currentNode = useRef();
邓超's avatar
邓超 committed
56
  const afterNodes = useRef(new Map([])); // 当前节点后所有节点
57
  const limitFinshNodes = useRef([new Set([])]);
58
  const objGo = go.GraphObject.make;
59 60 61 62 63 64
  useEffect(() => {
    if (treeVisible) {
      setVisible(false);
    }
  }, [treeVisible]);

65 66 67 68 69 70 71 72 73 74 75
  // 监听删除,给删除数组里添加删除id
  useEffect(() => {
    if (deleteLine) {
      setDeleteLines([...DeleteLines, deleteLine]);
    }
  }, [deleteLine]);
  useEffect(() => {
    if (deleteNode) {
      setDeleteNodes([...DeleteNodes, deleteNode]);
    }
  }, [deleteNode]);
皮倩雯's avatar
皮倩雯 committed
76
  // 初始化
77 78 79
  useEffect(() => {
    // 初始化流程图
    init();
80 81
    initPalette();
    myOverview = objGo(go.Overview, 'myOverviewDiv', { observed: diagram });
82 83
    // 监听节点或线的删除事件
    diagram.addDiagramListener('SelectionDeleted', e => {
84 85
      let delNodes = [];
      let delLinks = [];
86
      e.subject.each(n => {
87 88 89 90 91 92 93
        if (n.data.LineId) {
          delLinks.push(n.data.LineId);
        }
        if (n.data.ActivityId) {
          delNodes.push(n.data.ActivityId);
        }

94 95 96 97 98 99
        // 如果删除得节点不是新增得就给id放入到删除节点数组中
        if (n.data.NodeId && !AddNodes.some(item => item === n.data.NodeId)) {
          setTimeout(() => {
            setDeleteNode(n.data.NodeId);
          }, 0);
        }
邓超's avatar
邓超 committed
100
        if (n.data.LineKey) {
101
          setTimeout(() => {
102
            setDeleteLine(n.data.LineId);
103 104 105
          }, 0);
        }
      });
106 107 108
      if (delNodes.length === 0) {
        return;
      }
109 110
      DeleteFlowNodes({ ActivityIds: delNodes, LineIds: delLinks }).then(res => {
        if (res.code === 0) {
邓超's avatar
邓超 committed
111
          message.success('删除成功 ');
112 113 114 115 116
        } else {
          message.error(res.msg);
        }
      });
      console.log(delNodes, delLinks, 'fffff');
117 118 119 120
    });
    // 监听节点或线的删除前事件
    diagram.commandHandler.canDeleteSelection = () =>
      // 用例获取选中的节点或线
121
      diagram.selection.all(e => {
122
        // 判断是否存在不允许删除的节点或线
123
        showDeleteConfirm(e.data);
124 125
        return false;
      });
126 127 128 129 130 131
    // 监听线,连接线的时候加上text属性
    diagram.addDiagramListener('LinkDrawn', e => {
      // e.subject.data.text = '';
      e.subject.data.lineDetail = JSON.stringify(e.subject.data);
      console.log(e, e.subject.data, 'fasdfasdgds');
      diagram.model.updateTargetBindings(e.subject.data);
132
      leaveCallBack(true);
133
    });
134
    // 监听节点拖拽到画布事件
135
    diagram.addDiagramListener('externalobjectsdropped', e => {
136
      afterNodes.current = new Map([]);
137 138 139 140
      const list = JSON.parse(diagram.model.toJson()).nodeDataArray;
      console.log(list, 'list');
      let newNum;
      let newKey;
141

142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
      if (list.length > 0) {
        // eslint-disable-next-line prefer-spread
        newNum = Math.max.apply(Math, list.map(item => item.SerialNo)) + 1;
        // eslint-disable-next-line prefer-spread
        newKey = Math.max.apply(Math, list.map(item => item.key)) + 1;
      } else {
        newKey = 1;
        newNum = 1;
      }
      console.log(e);
      e.subject.each(n => {
        // 得到从Palette拖过来的节点
        console.log(n.data.key);
        let nodeData = diagram.model.findNodeDataForKey(n.data.key);
        nodeData.NodeName = `${n.data.NodeName}${newKey}`;
157
        nodeData.NodeAliasName = nodeData.NodeName;
158 159 160 161
        nodeData.SerialNo = newNum;
        // nodeData.key = newKey;
        nodeData.NodeId = newKey;
        nodeData.nodeDetail = JSON.stringify(nodeData);
162
        console.log(nodeData);
163 164
        diagram.model.updateTargetBindings(nodeData);
        diagram.model.setDataProperty(nodeData, 'key', newKey);
165 166 167 168 169 170

        currentNode.current = nodeData;
        setNodeKey(nodeData.key);
        setEditMsg(nodeData);
        setModalType('edit');
        setVisible(true);
171 172
      });
      setAddNodes([...AddNodes, newKey]);
173

174 175
      leaveTip();
    });
邓超's avatar
邓超 committed
176 177 178
    // diagram.addDiagramListener('SelectionDeleted', e => {

    // });
179 180 181
  }, []);
  useEffect(() => {
    if (flowData) {
182
      console.log(flowData, 'msgmsgmsg');
183 184 185 186 187 188
      // 每次切换时清空删除得id数组跟新增得id数组
      setDeleteNodes([]);
      setDeleteLines([]);
      setAddNodes([]);
      setDeleteNode('');
      setDeleteLine('');
189
      setEditMsg({});
190 191 192
      let dataList = lodash.cloneDeep(flowData);
      console.log(dataList, 'dataList');

193
      setCurrentFlowData(dataList);
皮倩雯's avatar
皮倩雯 committed
194
      setShowLeaveTip(false);
195
      setVisible(false);
196 197 198 199
    }
  }, [flowData]);
  // 存入在树形流程中选择得流程数据
  useEffect(() => {
邓超's avatar
邓超 committed
200 201
    let nodeDataArray = [];
    let linkDataArray = [];
202

邓超's avatar
邓超 committed
203
    // 处理老数据,让老数据可以正常展示
204
    limitFinshNodes.current = new Set([]);
邓超's avatar
邓超 committed
205
    nodeDataArray = currentFlowData.Nodes.map((item, index) => {
206 207 208 209 210
      if (item.FlowTimerList.length > 0) {
        item.FlowTimerList.forEach(ele => {
          limitFinshNodes.current.add(ele.EndNode);
        });
      }
邓超's avatar
邓超 committed
211 212 213
      let obj;
      obj = item;
      obj.key = item.NodeId;
214 215 216
      if (!obj.NodeAliasName) {
        obj.NodeAliasName = obj.NodeName;
      }
邓超's avatar
邓超 committed
217
      obj.nodeDetail = JSON.stringify(obj);
218 219 220 221
      obj.CarbonCopyPeopleList = obj.CarbonCopyPeopleList.map(ele => ({
        label: ele.userName,
        value: ele.userID,
      }));
邓超's avatar
邓超 committed
222 223 224 225 226
      if (obj.points === '') {
        if (obj.NodeType === '1') {
          obj.points = `${(index * 200).toString()}" 100"`;
        } else {
          obj.points = `${(index * 200).toString()}" -22"`;
皮倩雯's avatar
皮倩雯 committed
227
        }
邓超's avatar
邓超 committed
228 229 230 231 232 233 234 235 236 237
      }
      return obj;
    });
    linkDataArray = currentFlowData.Lines.map(item => {
      let obj;
      obj = item;
      obj.LineKey = item.LineId;
      obj.lineDetail = JSON.stringify(obj);
      return obj;
    });
238

皮倩雯's avatar
皮倩雯 committed
239 240 241 242 243
    // 保存初始数据
    setInitFlowData(
      JSON.parse(
        JSON.stringify({
          Nodes: nodeDataArray,
邓超's avatar
邓超 committed
244
          Lines: linkDataArray,
皮倩雯's avatar
皮倩雯 committed
245 246 247
        }),
      ),
    );
248 249 250 251
    diagram.model = go.Model.fromJson({
      linkFromPortIdProperty: 'fromPort', // 所需信息:
      linkToPortIdProperty: 'toPort', // 标识数据属性名称
      nodeDataArray,
邓超's avatar
邓超 committed
252
      linkDataArray,
253
    });
254 255 256 257 258 259 260 261 262
    // 初次选中
    if (nodeDataArray?.length > 0) {
      currentNode.current = diagram.model.findNodeDataForKey(nodeDataArray[0].NodeId);
      setNodeKey(currentNode.current.key);
      setEditMsg(currentNode.current);
      setModalType('edit');
      setVisible(true);
    }

邓超's avatar
邓超 committed
263 264
    // 修改复制后节点内容
    diagram.model.copyNodeDataFunction = (obj, model) => {
265
      let copyObj = lodash.cloneDeep(obj);
266 267 268 269 270
      console.log(copyObj, 'copyObj');
      copyObj.FlowTimerList.forEach(item => {
        item.key = item.ID;
        delete item.ID;
      });
邓超's avatar
邓超 committed
271
      delete copyObj.ActivityId;
272
      delete copyObj.FlowNodeExtendId;
邓超's avatar
邓超 committed
273 274 275 276 277 278 279 280
      return copyObj;
    };
    // 修改复制后线内容
    diagram.model.copyLinkDataFunction = (obj, model) => {
      let copyObj = lodash.cloneDeep(obj);
      delete copyObj.LineId;
      return copyObj;
    };
281

邓超's avatar
邓超 committed
282
    diagram.model.linkKeyProperty = 'LineKey';
283 284 285 286 287 288

    diagram.model.makeUniqueLinkKeyFunction = (model, data) => {
      let i = model.linkDataArray.length * 2 + 2;
      while (model.findLinkDataForKey(i) !== null) i += 2;
      return i;
    };
289 290
  }, [currentFlowData]);
  // 删除提醒
291
  const showDeleteConfirm = val => {
292 293 294 295 296 297 298 299
    confirm({
      title: '确定要删除所选中的节点吗?',
      icon: <ExclamationCircleOutlined />,
      content: '',
      okText: '是',
      okType: 'danger',
      cancelText: '否',
      onOk() {
300
        delNode(val);
301 302 303 304 305
      },
      onCancel() {},
    });
  };
  // 删除节点
306
  const delNode = val => {
皮倩雯's avatar
皮倩雯 committed
307
    setShowLeaveTip(true);
308
    // leaveCallBack(true);
309
    diagram.commandHandler.deleteSelection();
310 311 312 313 314 315 316 317 318 319 320 321 322
    // if (val.LineId) {
    //   diagram.commandHandler.deleteSelection();
    //   return;
    // }

    // DeleteFlowNode({ activityId: val.ActivityId }).then(res => {
    //   if (res.code === 0) {
    //     message.success('删除成功');
    //     diagram.commandHandler.deleteSelection();
    //   } else {
    //     message.error(res.msg);
    //   }
    // });
323
  };
324

325 326 327 328 329 330 331 332 333 334 335 336 337
  const animateFadeDown = e => {
    let diagrams = e.diagram;
    let animation = new go.Animation();
    animation.isViewportUnconstrained = true; // 所以图表定位规则让动画在屏幕外开始
    animation.easing = go.Animation.EaseOutExpo;
    animation.duration = 900;
    // 淡入“向下”,换句话说,从上方淡入
    animation.add(diagrams, 'position', diagrams.position.copy().offset(0, 200), diagrams.position);
    animation.add(diagrams, 'opacity', 0, 1);
    animation.start();
  };
  // 初始化拖拽面板
  const initPalette = () => {
338 339 340 341 342 343 344
    const defaultField = {
      aheadHandle: 1,
      NodeHandling: 1,
      RuleList: [],
      roleList: [],
      CarbonCopyPeopleList: [],
      ExtendPageList: [],
345 346
      FlowTimerList: [],
      TurnOnCc: 0,
347 348 349 350 351 352 353
      NodeAliasName: '',
      Handover: '移交选择人',
      TableName: '',
      Fields: '',
      WebPage: '',
      FeedbackName: '',
      Transferable: 0,
354
      EventsInformation: 0,
355 356 357 358 359 360 361
      IsSendMessage: 1,
      IsSave: 0,
      AutoClose: '否',
      HalfwayClose: 0,
      RollbackNode: '(上一节点)',
      Rollbackable: false,
    };
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
    myPaletteNode = objGo(go.Palette, 'myPaletteNode', {
      // 代替默认动画,使用自定义淡入淡出
      'animationManager.initialAnimationStyle': go.AnimationManager.None,
      InitialAnimationStarting: animateFadeDown, // 相反,使用此功能制作动画
      // nodeTemplateMap: diagram.nodeTemplateMap, // 分享 myDiagram 使用的模板
      scale: '1',
      nodeSelectionAdornmentTemplate: objGo(
        go.Adornment,
        'Auto',
        objGo(go.Shape, 'Rectangle', { fill: 'white', stroke: null }),
      ), // 去掉节点点击时的边框颜色
      model: new go.GraphLinksModel([
        // 指定调色板的内容
        {
          category: 'nodeStart',
          NodeName: '开始节点',
          NodeType: '1',
          SerialNo: 0,
380
          ...defaultField,
381 382 383 384 385 386
        },
        {
          category: 'nodeGeneral',
          NodeName: '普通节点',
          NodeType: '0',
          SerialNo: 0,
387
          ...defaultField,
388 389 390 391 392 393
        },
        {
          category: 'nodeEnd',
          NodeName: '结束节点',
          NodeType: '2',
          SerialNo: 0,
394
          ...defaultField,
395 396 397 398 399 400 401 402 403 404
        },
      ]),
    });
    myPaletteNode.nodeTemplate = objGo(
      go.Node,
      'Auto',
      new go.Binding('location', 'points', go.Point.parse).makeTwoWay(go.Point.stringify),
      // 节点样式配置
      objGo(
        go.Panel,
405
        { width: 108, height: 42 },
406 407
        objGo(
          go.Picture,
408
          { width: 108, height: 42 },
409 410 411
          new go.Binding('source', 'NodeType', v => {
            switch (v) {
              case '1':
412
                return require('../../../../../assets/images/workFlow/icon1.svg');
413
              case '2':
414
                return require('../../../../../assets/images/workFlow/icon3.svg');
415
              case '0':
416
                return require('../../../../../assets/images/workFlow/icon2.svg');
邓超's avatar
邓超 committed
417

418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
              default:
                return null;
            }
          }),
        ),
      ),
    );
    myPaletteGateway = objGo(go.Palette, 'myPaletteGateway', {
      // 代替默认动画,使用自定义淡入淡出
      'animationManager.initialAnimationStyle': go.AnimationManager.None,
      InitialAnimationStarting: animateFadeDown, // 相反,使用此功能制作动画
      // nodeTemplateMap: diagram.nodeTemplateMap, // 分享 myDiagram 使用的模板
      scale: '1',
      nodeSelectionAdornmentTemplate: objGo(
        go.Adornment,
        'Auto',
        objGo(go.Shape, 'Rectangle', { fill: 'white', stroke: null }),
      ), // 去掉节点点击时的边框颜色
      model: new go.GraphLinksModel([
        // 指定调色板的内容
        {
          category: 'gatewayCondition',
          NodeName: '条件网关',
          NodeType: '20',
          SerialNo: 0,
443
          ...defaultField,
444 445 446 447 448 449
        },
        {
          category: 'gatewayParallel',
          NodeName: '并行网关',
          NodeType: '22',
          SerialNo: 0,
450
          ...defaultField,
451 452 453 454 455 456
        },
        {
          category: 'gatewayJoin',
          NodeName: '汇合网关',
          NodeType: '21',
          SerialNo: 0,
457
          ...defaultField,
458 459 460 461 462 463 464 465 466 467
        },
      ]),
    });
    myPaletteGateway.nodeTemplate = objGo(
      go.Node,
      'Auto',
      new go.Binding('location', 'points', go.Point.parse).makeTwoWay(go.Point.stringify),
      // 节点样式配置
      objGo(
        go.Panel,
468
        { width: 108, height: 42 },
469 470
        objGo(
          go.Picture,
471
          { width: 108, height: 42 },
472 473 474
          new go.Binding('source', 'NodeType', v => {
            switch (v) {
              case '20':
475
                return require('../../../../../assets/images/workFlow/gateWayicon1.svg');
476
              case '21':
477
                return require('../../../../../assets/images/workFlow/gateWayicon3.svg');
478
              case '22':
479
                return require('../../../../../assets/images/workFlow/gateWayicon2.svg');
480 481 482 483 484 485 486
              default:
                return null;
            }
          }),
        ),
      ),
    );
487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
    myPaletteSubprocess = objGo(go.Palette, 'myPaletteSubprocess', {
      // 代替默认动画,使用自定义淡入淡出
      'animationManager.initialAnimationStyle': go.AnimationManager.None,
      InitialAnimationStarting: animateFadeDown, // 相反,使用此功能制作动画
      // nodeTemplateMap: diagram.nodeTemplateMap, // 分享 myDiagram 使用的模板
      scale: '1',
      nodeSelectionAdornmentTemplate: objGo(
        go.Adornment,
        'Auto',
        objGo(go.Shape, 'Rectangle', { fill: 'white', stroke: null }),
      ), // 去掉节点点击时的边框颜色
      model: new go.GraphLinksModel([
        // 指定调色板的内容
        {
          category: 'gatewayCondition',
          NodeName: '子流程',
          NodeType: '30',
          SerialNo: 0,
505
          ...defaultField,
506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531
        },
      ]),
    });
    myPaletteSubprocess.nodeTemplate = objGo(
      go.Node,
      'Auto',
      new go.Binding('location', 'points', go.Point.parse).makeTwoWay(go.Point.stringify),
      // 节点样式配置
      objGo(
        go.Panel,
        { width: 108, height: 42 },
        objGo(
          go.Picture,
          { width: 108, height: 42 },
          new go.Binding('source', 'NodeType', v => {
            switch (v) {
              case '30':
                return require('../../../../../assets/images/workFlow/subprocessicon.svg');

              default:
                return null;
            }
          }),
        ),
      ),
    );
532
  };
533 534 535 536 537 538
  // 流程图初始化
  const init = () => {
    diagram = objGo(go.Diagram, 'myDiagramDiv', {
      'undoManager.isEnabled': true,
      allowDragOut: false,
      'dragSelectingTool.isEnabled': false, // 禁止多选
539
      // 'grid.visible': true,
540
      scrollMode: go.Diagram.InfiniteScroll, // 无限滚动
邓超's avatar
邓超 committed
541
      allowCopy: true, // 禁止复制
542
      allowDrop: true,
543 544 545 546 547
      // nodeSelectionAdornmentTemplate: objGo(
      //   go.Adornment,
      //   'Auto',
      //   objGo(go.Shape, 'Rectangle', { fill: 'white', stroke: null }),
      // ), // 去掉节点点击时的边框颜色
548
      scale: '0.8',
549
    });
550 551
    diagram.grid.gridCellSize = new go.Size(10, 10);
    diagram.toolManager.draggingTool.isGridSnapEnabled = true;
552

553 554 555 556
    // 节点配置
    diagram.nodeTemplate = objGo(
      go.Node,
      'Auto',
557
      new go.Binding('location', 'points', go.Point.parse).makeTwoWay(go.Point.stringify),
558 559 560
      // 节点样式配置
      objGo(
        go.Panel,
561 562
        nodeBoxStyle('width'),
        nodeBoxStyle('height'),
563
        objGo(
564 565
          go.Picture,
          new go.Binding('source', 'NodeType', v => {
邓超's avatar
邓超 committed
566 567
            switch (v) {
              case '1':
568
                return nodeStart;
邓超's avatar
邓超 committed
569
              case '2':
570
                return nodeEnd;
邓超's avatar
邓超 committed
571
              case '0':
572 573 574
                return nodeGeneral;
              // case '4':
              //   return cc;
575
              case '20':
576
                return gatewayCondition;
577
              case '21':
578
                return gatewayJoin;
579
              case '22':
580
                return gatewayParallel;
581 582
              case '30':
                return require('../../../../../assets/images/workFlow/nodesubprocess.svg');
邓超's avatar
邓超 committed
583 584
              default:
                return null;
585 586
            }
          }),
587 588
          nodeBoxStyle('width'),
          nodeBoxStyle('height'),
589
        ),
590 591 592 593 594 595 596 597
        objGo(
          go.Panel,
          'Horizontal',
          nodeBoxStyle('height'),
          { alignment: go.Spot.Center },
          objGo(
            go.Panel,
            'Vertical', // 节点文案
598

599 600 601 602 603 604 605
            nodeBoxStyle('width'),
            objGo(
              go.TextBlock,
              {
                maxSize: new go.Size(120, NaN),
                maxLines: 1,
                alignment: go.Spot.Center,
606
                margin: new go.Margin(0, 15, 0, 15),
607
                overflow: go.TextBlock.OverflowEllipsis,
608
                font: 'normal 12pt Microsoft YaHei',
609
              },
610 611 612
              new go.Binding('visible', 'NodeType', v => {
                if (v.NodeType === '20' || v.NodeType === '21' || v.NodeType === '22') {
                  return false;
613
                }
614
                return true;
615
              }),
616
              new go.Binding('text', 'NodeAliasName'),
617 618 619 620
              nodeBoxStyle('stroke', 'nodeStyle'),
            ),
            objGo(
              go.TextBlock,
621

622 623 624 625
              {
                alignment: go.Spot.Center,
                maxLines: 2,
                overflow: go.TextBlock.OverflowEllipsis,
626
                font: 'normal 12pt Microsoft YaHei',
627
              },
628 629
              new go.Binding('spacingAbove', 'roleList', v => (v?.length > 0 ? 5 : 0)),
              new go.Binding('height', 'roleList', v => (v?.length > 0 ? 30 : 0)),
630 631 632 633 634
              new go.Binding('margin', 'roleList', v =>
                v?.length > 0 ? new go.Margin(10, 10, 0, 10) : 0,
              ),
              new go.Binding('text', 'nodeDetail', v => {
                const obj = JSON.parse(v);
邓超's avatar
邓超 committed
635

636 637 638 639 640 641 642 643 644 645 646 647
                if (obj.NodeType === '20' || obj.NodeType === '21' || obj.NodeType === '22') {
                  return '';
                }
                if (obj.roleList?.length === 0) {
                  return '';
                }
                return obj.roleList.map(item => item.roleName).join(',');
              }),
              nodeBoxStyle('stroke', 'roleStyle'),
            ),
          ),
        ),
648
      ),
649

650
      // 我们的小命名端口,每侧一个:
651 652 653 654
      makePort('T', go.Spot.Top),
      makePort('L', go.Spot.Left),
      makePort('R', go.Spot.Right),
      makePort('B', go.Spot.Bottom),
655
      {
656
        // 节点之间线得连接
邓超's avatar
邓超 committed
657
        linkValidation(fromnode, fromport, tonode, toport, thisLink) {
658
          // 并行网关不让连接汇合网关
659 660 661
          if (fromnode.data.NodeType === '22' && tonode.data.NodeType === '21') {
            return false;
          }
662 663 664 665 666 667 668 669
          // 条件网关不让连接条件网关
          if (fromnode.data.NodeType === '20' && tonode.data.NodeType === '20') {
            return false;
          }
          // 汇合网关不让连条件网关
          if (fromnode.data.NodeType === '21' && tonode.data.NodeType === '20') {
            return false;
          }
邓超's avatar
邓超 committed
670 671
          return true;
        },
672 673 674 675 676 677 678
        // 处理鼠标进入/离开事件以显示/隐藏端口
        mouseEnter(e, node) {
          showSmallPorts(node, true);
        },
        mouseLeave(e, node) {
          showSmallPorts(node, false);
        },
679 680 681
        click(e, node) {
          handlerDC(e, node);
        },
682 683 684
        // 处理双击
        doubleClick(e, node) {
          // 双击事件
685 686 687 688
          // handlerDC(e, node); // 双击执行的方法
        },
        selectionChanged: node => {
          // console.log(node.data, 'nodenodenode');
689
        },
690 691 692 693 694 695 696 697 698 699 700 701 702
        toolTip: objGo(
          'ToolTip',
          objGo(
            go.TextBlock,
            { margin: 4 },
            new go.Binding('text', 'nodeDetail', v => {
              const obj = JSON.parse(v);
              return `节点名称:${obj.NodeName}\n${
                obj.roleList.length > 0 ? '承办:' : ''
              }${obj.roleList.map(item => item.roleName).join(',')}`;
            }),
          ),
        ),
703 704 705 706 707 708 709 710 711 712
      },
    );
    // 链接设置
    diagram.linkTemplate = objGo(
      go.Link,
      {
        routing: go.Link.Orthogonal,
        curve: go.Link.JumpOver,
        corner: 5,
        toShortLength: 4,
713 714 715 716 717
        selectionAdornmentTemplate: objGo(
          go.Adornment,
          objGo(go.Shape, { isPanelMain: true, stroke: '#faad14', strokeWidth: 2 }), // 修改线颜色和大小
          objGo(go.Shape, { toArrow: 'Standard', fill: '#faad14', stroke: '#faad14' }), // 修改线箭头的颜色和大小
        ),
718 719 720 721
      },
      new go.Binding('points').makeTwoWay(),
      objGo(
        go.Shape, // 链接路径形状
722 723 724 725 726
        {
          isPanelMain: true,
          strokeWidth: 2,
        },

727 728
        new go.Binding('stroke', 'from', v => lineStyle(v, 'stroke')),
        new go.Binding('strokeDashArray', 'from', v => lineStyle(v, 'strokeDashArray')),
729 730 731
      ),
      objGo(
        go.Shape, // 箭头
732
        { toArrow: 'Standard' },
733 734
        new go.Binding('stroke', 'from', v => lineStyle(v, 'stroke')),
        new go.Binding('fill', 'from', v => lineStyle(v, 'stroke')),
735
      ),
736 737 738 739 740 741 742 743 744 745 746 747 748
      objGo(
        go.Panel,
        'Auto',
        objGo(
          go.Shape, // 标签背景,在边缘变得透明
          // { fill: 'transparent' },
          new go.Binding('fill', 'lineDetail', v => lineTextStyle(v)),
          new go.Binding('stroke', 'lineDetail', v => lineTextStyle(v)),
        ),
        objGo(
          go.TextBlock,
          {
            textAlign: 'center',
749
            font: '10pt helvetica, arial, Microsoft YaHei',
750 751 752 753 754 755 756
            stroke: '#555555',
            margin: 4,
          },
          new go.Binding('text', 'lineDetail', v => lineText(v)),
        ),
      ),

757 758 759 760 761 762
      // {
      //   // 处理双击
      //   doubleClick(e, node) {
      //     addLineMsg(e, node);
      //   },
      // },
763 764 765 766 767 768 769 770 771
    );
    // 初始化流程的节点数组
    diagram.model = objGo(go.GraphLinksModel, {
      linkFromPortIdProperty: 'fromPort', // 所需信息:
      linkToPortIdProperty: 'toPort', // 标识数据属性名称
      nodeDataArray: currentFlowData.Nodes,
      linkDataArray: currentFlowData.Lines,
    });
  };
772

邓超's avatar
邓超 committed
773
  // 线的样式
774
  const lineStyle = (v, styleName) => {
775
    const linemsg = diagram.model.findNodeDataForKey(v);
776 777
    switch (styleName) {
      case 'strokeDashArray':
778
        if (linemsg.NodeType === '20') {
779 780 781 782 783 784 785 786 787
          return [6, 3];
        }
        return null;
      case 'stroke':
        return '#1685FF';
      default:
        return null;
    }
  };
邓超's avatar
邓超 committed
788
  // 线上文案样式
789 790 791 792 793 794 795 796 797 798 799 800 801
  const lineTextStyle = v => {
    let obj = JSON.parse(v);

    let nodeData = diagram.model.findNodeDataForKey(obj.from);
    if (nodeData.NodeType === '20' || nodeData.NodeType === '21') {
      // if(nodeData.)
      if (nodeData.RuleList.some(ele => ele.NextNodeId === obj.to)) {
        return '#EFF8FA';
      }
      return 'transparent';
    }
    return 'transparent';
  };
邓超's avatar
邓超 committed
802
  // 线上的文案
803 804 805 806
  const lineText = v => {
    let obj = JSON.parse(v);
    let nodeData = diagram.model.findNodeDataForKey(obj.from);
    if (nodeData.NodeType === '20' || nodeData.NodeType === '21') {
807
      return nodeData.RuleList.find(ele => ele.NextNodeId === obj.to).RuleName;
808 809 810
    }
    return '';
  };
811 812 813 814 815 816 817 818 819 820
  // 是否显示端口
  const showSmallPorts = (node, show) => {
    node.ports.each(port => {
      if (port.portId !== '') {
        // 不要更改默认端口,这是大形状
        port.fill = show ? 'rgba(5,135,224,.3)' : null;
      }
    });
  };
  // 创建节点端口
821
  const makePort = (name, spot) =>
邓超's avatar
邓超 committed
822
    // 端口基本上只是一个小的透明 方块
823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839
    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, // 声明链接可以在此端口连接的位置
        cursor: 'pointer', // 显示不同的光标以指示潜在的链接点
      },
      new go.Binding('fromLinkable', 'NodeType', v => v !== '2'), // 是否允许用户绘制的链接到这里
      new go.Binding('toLinkable', 'NodeType', v => v !== '1'), // 声明用户是否可以从这里绘制链接
    );
邓超's avatar
邓超 committed
840
  //  节点盒子样式
841 842 843 844 845 846
  const nodeBoxStyle = (atr, classname) => {
    switch (atr) {
      case 'width':
        return new go.Binding('width', 'NodeType', v => {
          switch (v) {
            case '1':
847
              return 140;
848
            case '2':
849
              return 140;
850
            case '0':
851
              return 220;
852
            case '4':
853
              return 220;
854
            case '20':
855
              return 60;
856
            case '21':
857
              return 60;
858
            case '22':
859 860 861
              return 60;
            case '30':
              return 220;
862 863 864 865 866 867 868 869
            default:
              return null;
          }
        });
      case 'height':
        return new go.Binding('height', 'NodeType', v => {
          switch (v) {
            case '1':
870
              return 140;
871
            case '2':
872
              return 140;
873
            case '0':
874
              return 120;
875
            case '4':
876
              return 120;
877
            case '20':
878
              return 60;
879
            case '21':
880
              return 60;
881
            case '22':
882 883 884
              return 60;
            case '30':
              return 120;
885 886 887 888 889 890 891 892 893 894 895 896 897
            default:
              return null;
          }
        });
      case 'stroke':
        return new go.Binding('stroke', 'NodeType', v => {
          switch (v) {
            case '1':
              return classname === 'roleStyle' ? '#BCBCBC' : '#1685FF';
            case '2':
              return classname === 'roleStyle' ? '#BCBCBC' : '#51C21A';
            case '0':
              return classname === 'roleStyle' ? '#BCBCBC' : '#1685FF';
898 899
            case '30':
              return classname === 'roleStyle' ? '#BCBCBC' : '#9850F6';
900 901 902 903 904 905 906 907
            default:
              return null;
          }
        });
      default:
        return null;
    }
  };
908 909 910 911 912 913 914 915 916 917 918
  const findAfterNode = startNode => {
    // let nodeList = new Map([]);
    startNode.findNodesOutOf().each(node => {
      if (!afterNodes.current.has(node.data.NodeName)) {
        if (['1', '0', '2'].includes(node.data.NodeType)) {
          afterNodes.current.set(node.data.NodeName, node.data.TableName);
        }
        findAfterNode(node);
      }
    });
  };
919 920
  // 双击节点
  const handlerDC = (e, node) => {
921
    currentNode.current = node.data;
922 923 924 925 926

    // 找到节点后得除去网关跟子流程的所有节点
    afterNodes.current = new Map([]);
    findAfterNode(node);
    console.log(Object.fromEntries(afterNodes.current));
927 928
    setModalType('edit');
    setVisible(true);
929 930
    setNodeKey(node.part.data.key);
    setEditMsg(node.part.data);
931
  };
932 933
  // 双击线
  const addLineMsg = (e, node) => {
邓超's avatar
邓超 committed
934
    setLineKey(node.part.data.LineKey);
935 936 937
    setLineMsg(node.part.data);
    setLineVisible(true);
  };
938

939 940
  const copyNode = e => {
    diagram.commandHandler.canSelectAll();
941 942
  };
  // 节点配置回调
943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990
  // const nodeCallBack = obj => {
  //   let nameIsRepeat;
  //   let { nodes } = diagram;
  //   let keyArr = [];
  //   // 遍历输出节点对象
  //   nodes.each(node => {
  //     keyArr = [...keyArr, Number(node.data.key)];
  //     if (obj.NodeName === node.data.NodeName) {
  //       nameIsRepeat = true;
  //       if (modalType === 'edit' && obj.NodeName === editMsg.NodeName) {
  //         nameIsRepeat = false;
  //       }
  //     }
  //   });
  //   if (nameIsRepeat) {
  //     notification.error({
  //       message: '提示',
  //       duration: 3,
  //       description: '节点名称不能重复',
  //     });
  //     return;
  //   }
  //   // 编辑节点
  //   let nodeData = diagram.model.findNodeDataForKey(nodeKey);
  //   const {
  //     NodeName,
  //     NodeType,
  //     roleList,
  //     SerialNo,
  //     aheadHandle,
  //     NodeHandling,
  //     nodeDetail,
  //     RuleList,
  //     CarbonCopyPeopleList,
  //     SubFlowInfo,
  //   } = obj;
  //   nodeData.NodeName = NodeName;
  //   nodeData.NodeType = NodeType;
  //   nodeData.NodeId = nodeKey;
  //   nodeData.roleList = roleList;
  //   nodeData.SerialNo = SerialNo;
  //   nodeData.aheadHandle = aheadHandle;
  //   nodeData.NodeHandling = NodeHandling;
  //   nodeData.nodeDetail = nodeDetail;
  //   nodeData.RuleList = RuleList;
  //   nodeData.CarbonCopyPeopleList = CarbonCopyPeopleList;
  //   nodeData.SubFlowInfo = SubFlowInfo;
  //   diagram.model.updateTargetBindings(nodeData);
991

992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012
  //   // 给线上添加文字
  //   let diagramObj = JSON.parse(diagram.model.toJson());
  //   console.log(diagramObj.linkDataArray, 'diagramObj.linkDataArray');
  //   diagramObj.linkDataArray.forEach(item => {
  //     let node = diagram.model.findLinkDataForKey(item.LineKey);
  //     node.text = item.RuleName;
  //     diagram.model.updateTargetBindings(node);
  //   });
  //   // 关闭时进行数据比对看数据是否改变
  //   leaveTip();
  //   // setVisible(false);
  // };
  const nodeCallBack = () => {
    FlowNodeSave({
      flowID,
      ...currentNode.current,
      CarbonCopyPeopleList: currentNode.current.CarbonCopyPeopleList.map(item =>
        Number(item.value),
      ),
    }).then(res => {
      if (res.code === 0) {
1013
        diagram.model.setDataProperty(currentNode.current, 'FlowTimerList', res.data.FlowTimerList);
1014 1015 1016 1017 1018 1019 1020 1021 1022 1023
        diagram.model.setDataProperty(currentNode.current, 'ActivityId', res.data.ActivityId);
        diagram.model.setDataProperty(
          currentNode.current,
          'FlowNodeExtendId',
          res.data.FlowNodeExtendId,
        );
        message.success('保存成功');
      } else {
        message.error(res.msg);
      }
1024
    });
邓超's avatar
邓超 committed
1025
  };
1026
  // 关闭时进行数据比对看数据是否改变
邓超's avatar
邓超 committed
1027
  const leaveTip = () => {
皮倩雯's avatar
皮倩雯 committed
1028 1029 1030 1031 1032
    let diagramObj = JSON.parse(diagram.model.toJson());
    let stageJson = {
      Nodes: diagramObj.nodeDataArray,
      Lines: diagramObj.linkDataArray,
    };
1033
    if (JSON.stringify(stageJson.Nodes) === JSON.stringify(initFlowData.Nodes)) {
皮倩雯's avatar
皮倩雯 committed
1034 1035 1036 1037 1038 1039
      setShowLeaveTip(false);
      leaveCallBack(false);
    } else {
      leaveCallBack(true);
      setShowLeaveTip(true);
    }
1040
  };
1041 1042
  // 线配置回调函数
  const lineCallBack = obj => {
邓超's avatar
邓超 committed
1043
    let node = diagram.model.findLinkDataForKey(LineKey);
1044 1045
    node.text = obj.text;
    diagram.model.updateTargetBindings(node);
1046

1047
    // 关闭时进行数据比对看数据是否改变
1048
    leaveTip();
1049 1050
    setLineVisible(false);
  };
1051 1052 1053 1054
  // 获取保存后的流程数据
  const getFlowData = () => {
    GetFlowNode({ flowID }).then(res => {
      if (res.code === 0) {
皮倩雯's avatar
皮倩雯 committed
1055 1056 1057
        // 保存后离开不用提醒要修改数据了
        setShowLeaveTip(false);
        leaveCallBack(false);
1058

1059
        setCurrentFlowData(JSON.parse(JSON.stringify(res.data)));
1060 1061 1062 1063 1064 1065 1066 1067 1068
      } else {
        notification.error({
          title: '提示',
          duration: 3,
          description: res.msg,
        });
      }
    });
  };
1069 1070 1071 1072 1073 1074 1075 1076 1077 1078
  const isRepeat = (arr, key) => {
    let obj = {};
    for (let i = 0; i < arr.length; i++) {
      if (obj[arr[i][key]]) {
        return false;
      }
      obj[arr[i][key]] = arr[i];
    }
    return obj;
  };
1079 1080 1081 1082 1083 1084
  // 节点数据改边
  const nodeChage = (key, value) => {
    console.log(key, value);
    let obj = JSON.parse(JSON.stringify(currentNode.current));
    obj[key] = value;
    const nodeDetail = JSON.stringify(obj);
1085

1086 1087 1088 1089
    diagram.model.setDataProperty(currentNode.current, key, value);
    if (key === 'roleList') {
      diagram.model.setDataProperty(currentNode.current, 'nodeDetail', nodeDetail);
    }
1090 1091 1092 1093 1094 1095
    if (key === 'FlowTimerList') {
      const list = value.map(item => item.EndNode);
      limitFinshNodes.current = new Set(list);
      setFlag(flag + 1);
      // limitFinshNodes;
    }
1096 1097 1098
    if (key === 'TableName') {
      setFlag(flag + 1);
    }
1099

1100
    diagram.rebuildParts();
1101
    leaveCallBack(true);
1102
  };
1103 1104 1105
  // 保存流程
  const saveFlow = () => {
    let diagramObj = JSON.parse(diagram.model.toJson());
邓超's avatar
邓超 committed
1106
    // let list = isRepeat(diagramObj.nodeDataArray, 'SerialNo');
1107

邓超's avatar
邓超 committed
1108 1109 1110 1111 1112 1113 1114 1115
    // if (!list) {
    //   notification.error({
    //     message: '提示',
    //     duration: 3,
    //     description: '请检查序号是否重复',
    //   });
    //   return;
    // }
1116 1117
    let list = new Set([]);
    console.log(list, '11111');
1118
    diagramObj.nodeDataArray.forEach(item => {
1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140
      if ((item.NodeType === '20' || item.NodeType === '21') && item.RuleList) {
        item.RuleList.forEach(ele => {
          if (!ele.RuleName) {
            list.add(item.NodeName);

            return;
          }
          if (!ele.NextNodeId && ele.NextNodeId !== 0) {
            list.add(item.NodeName);

            return;
          }
          if (!ele.RuleContent) {
            list.add(item.NodeName);
          }
        });
      }
      const newListLength = new Set(item.RuleList.map(ele => ele.NextNodeId)).size;
      if (item.RuleList.length > newListLength) {
        list.add(item.NodeName);
        return;
      }
1141 1142
      item.CarbonCopyPeopleList = item.CarbonCopyPeopleList.map(ele => Number(ele.value));
    });
1143 1144 1145 1146 1147 1148 1149 1150
    console.log(list, '222');
    if ([...list].length > 0) {
      list.forEach(item => {
        message.error(`请检查${item}规则配置`);
      });
      return;
    }
    setButtonLoading(true);
1151 1152
    SaveNodeChange({
      FlowId: flowID,
1153
      // DeleteNodes,
1154 1155 1156 1157 1158
      DeleteLines,
      Lines: diagramObj.linkDataArray,
      Nodes: diagramObj.nodeDataArray,
    })
      .then(res => {
1159
        setButtonLoading(false);
1160
        if (res.code === 0) {
1161 1162 1163 1164 1165
          setDeleteNodes([]);
          setDeleteLines([]);
          setAddNodes([]);
          setDeleteNode('');
          setDeleteLine('');
1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180
          getFlowData();
          notification.success({
            message: '提示',
            duration: 3,
            description: '保存成功',
          });
        } else {
          notification.error({
            message: '提示',
            duration: 8,
            description: res.msg,
          });
        }
      })
      .catch(() => {
1181
        setButtonLoading(false);
1182 1183 1184 1185 1186 1187 1188
        notification.error({
          message: '提示',
          duration: 3,
          description: '网络异常请稍后重试',
        });
      });
  };
1189

1190 1191
  return (
    <>
1192
      <Prompt message="编辑的内容还未保存,确定要离开该页面吗?" when={showLeaveTip} />
1193
      <div className={styles.control}>
邓超's avatar
邓超 committed
1194
        <div className={styles.nodeList}>
1195 1196 1197
          <div id="myPaletteNode" className={styles.myPaletteDiv} />
          {/* <div className={styles.lineBox} /> */}
          <div id="myPaletteGateway" className={styles.myPaletteDiv} />
1198
          <div id="myPaletteSubprocess" className={styles.myPaletteSubprocess} />
邓超's avatar
邓超 committed
1199
        </div>
1200
        <div className={styles.buttonList}>
1201
          {/* <Button
1202 1203 1204 1205 1206 1207 1208 1209
            type="link"
            onClick={() => {
              window.open(
                'https://www.yuque.com/docs/share/da224db9-b8d1-49d2-838f-a23fcd15f0da?#%20%E3%80%8A%E6%B5%81%E7%A8%8B%E8%AE%BE%E8%AE%A1%E3%80%8B',
              );
            }}
          >
            说明文档
1210
          </Button> */}
1211 1212 1213
          {/* <Button type="link" onClick={() => copyNode()}>
            复制
          </Button> */}
1214
          <Button type="primary" onClick={() => saveFlow()} loading={buttonLoading}>
1215 1216 1217
            发布
          </Button>
        </div>
1218
      </div>
1219
      <div className={styles.chartBox}>
1220
        <div id="myOverviewDiv" className={styles.myOverviewDiv} />
1221
        <div className={styles.flowName}>{flowData.flowName}</div>
1222 1223 1224 1225 1226 1227 1228
        <Spin spinning={chartLoading}>
          <div
            id="myDiagramDiv"
            className={styles.myDiagramDiv}
            style={{ backgroundColor: '#EFF8FA' }}
          />
        </Spin>
1229 1230 1231 1232 1233
        <NodeModal
          flowID={flowID}
          visible={visible}
          editMsg={editMsg}
          modalType={modalType}
1234
          nodeChage={nodeChage}
1235
          currentNode={currentNode.current}
1236
          limitFinshNodes={[...limitFinshNodes.current]}
1237
          afterNodes={Object.fromEntries(afterNodes.current)}
1238
          handleCancel={() => setVisible(false)}
1239
          onSubumit={obj => nodeCallBack(obj)}
1240 1241
          flowData={diagram ? JSON.parse(diagram.model.toJson()) : {}}
        />
1242
      </div>
1243

1244
      <LineModal
1245 1246 1247 1248
        visible={lineVisible}
        lineMsg={lineMsg}
        handleCancel={() => setLineVisible(false)}
        onSubumit={obj => lineCallBack(obj)}
1249
      />
1250 1251 1252 1253 1254
    </>
  );
};

export default FlowChart;