小强

导航

基于jsplumb开发厂区设备分布图

随着IT信息技术的发展,工业化和信息化结合的场景越来越多。下面是某公司通过信息化系统动态维护设备开发的案例。

整体效果

设备管理 

可以从左侧把需要的设备拖拽到右边的画布,双击可以维护设备的信息以及点位。2个设备之间可以添加连线。

 相关代码

$("#flowBox").droppable({
    scope: 'ss',
    drop: function (event, ui) {
        var $chart = $(ui.draggable[0]);
        var node = {};
        node.id = "node" + Math.random().toString(36).substr(3, 10);
        node.name = $chart.attr("data-name");
        node.data_id = $chart.attr("id");
        node.data_code = $chart.attr("data-code");
        node.data_type = $chart.attr("data-type");
        node.type = 'chart';
        node.groupId = null;
        node.width = 150;
        node.height = 130;
        node.left = miniview_position.left * miniview_percent + (ui.position.left - 100);
        node.top =  miniview_position.top * miniview_percent + (ui.position.top - 50);
        node.EndpointList = getEndpointList(node);

        addNode(node);
    }
})

 function drawNode(node) {
    if(node.type == 'chart'){
        var nodeDiv = ['<div data_name="'+node.name+'" onmouseup="changeNodeSite(this)" onclick="onclickNode(this)" ondblclick="ondblclickNode(this)" id="' + node.id + '" class="nodeBox" style="left:' + node.left + 'px;top:' + node.top + 'px;width:' + node.width + 'px;height:' + node.height + 'px">',
            '<div class="nodeBox-img ' + node.data_type + '"></div>',
            '<div class="nodeBox-text" >' + node.name + '</div>',
        '</div>'].join('');
        $("#flowBox").append(nodeDiv);
        // 拖拽改变大小
        $("#"+node.id).resizable({
            autoHide: true ,
            minHeight: 50,
            minWidth:50,
            aspectRatio:15/13,
            containment: "parent",
            resize: function (event, ui) {
                changeNodeSize(node.id,ui.size.width,ui.size.height)
                //拖拽时点位跟着变动
                jsPlumb.repaint(ui.helper);
                jsPlumb.repaintEverything();
            }
        })
        jsPlumb.draggable(node.id);
        if(node.groupId !=null){
            var el = eval('(' + node.id + ')');
            var groupNode = dataNodeList.filter(function (itemNode) {
                return itemNode.id == node.groupId;
            })[0];
            $("#"+node.id).css('left',(groupNode.left + node.left)+"px");
            $("#"+node.id).css('top',(groupNode.top + node.top)+"px");
            jsPlumb.addToGroup(node.groupId, el);
        }
    }
    if(node.EndpointList !=null &&  node.EndpointList.length >0){
        for (var i = 0; i < node.EndpointList.length; i++) {
         jsPlumb.addEndpoint(node.id, {uuid:node.EndpointList[i].id,anchors:locationToAnchors(node.EndpointList[i].location,node)}, GetEndpointOptions(node.EndpointList[i]));
       }
    }
}

设备组管理

多个设备可以拉进一个设备组中一起管理,组㐓展开折叠。

 jsPlumb通过事件控制组元素的新增和删除

//添加到组
jsPlumb.bind("group:addMember",function(evt) {
   var nodeId = evt.el.id;
   var groupId = evt.group.id;
   var pos = evt.pos;

   for (var i = 0; i < dataNodeList.length; i++) {
        if (dataNodeList[i].id == nodeId) {
            dataNodeList[i].groupId = groupId;
            dataNodeList[i].left = pos.left;
            dataNodeList[i].top = pos.top;
            break;
        }
    }
});
//从组中删除
jsPlumb.bind("group:removeMember",function(evt) {
    console.log(1)
   var nodeId = evt.el.id;
   var groupId = evt.group.id;
   var pos = evt.pos;

   for (var i = 0; i < dataNodeList.length; i++) {
        if (dataNodeList[i].id == nodeId) {
            dataNodeList[i].groupId = null;
            dataNodeList[i].left = pos.left;
            dataNodeList[i].top = pos.top;
            break;
        }
    }
});

其他功能

其中还有放大缩小整个画布、导入导出,返回上一步等其他功能。下面附上所有的JavaScript代码,感兴趣的同学可以学习参考一下。

 var miniview_position ={ top: 0, left: 0 };
    var miniview_percent = 8;
    var workflowInfo = {};
    var dataNodeList = [];
    var dataLineList = [];
    var loadEasyFlowFinish = true;
    var jsplumbSetting = {
        // 动态锚点、位置自适应
        //Anchors: ['Top', 'TopCenter', 'TopRight', 'TopLeft', 'Right', 'RightMiddle', 'Bottom', 'BottomCenter', 'BottomRight', 'BottomLeft', 'Left', 'LeftMiddle'],
        Container: 'flowBox',
        // 连线的样式 StateMachine、Flowchart
        Connector: 'Flowchart',
        // 鼠标不能拖动删除线
        ConnectionsDetachable: false,
        // 删除线的时候节点不删除
        DeleteEndpointsOnDetach: false,
        // 连线的端点
        Endpoint: [ "Dot", { radius:2.5 } ],
        // 线端点的样式
        //EndpointStyle: { fill: 'rgba(255,0,5,1)', outlineWidth: 1},
        LogEnabled: true,//是否打开jsPlumb的内部日志记录
        // 绘制线
        PaintStyle: { stroke: 'black', strokeWidth: 3 },
        // 绘制箭头
        //Overlays: [['Arrow', {width: 12, length: 12, location: 1}]],
        RenderMode: "svg",
    };
    // jsplumb连接参数
    var jsplumbConnectOptions = {
        isSource: true,
        isTarget: true,
        // 动态锚点、提供了4个方向 Continuous、AutoDefault
        anchor: "Continuous"
    };
    var jsplumbSourceOptions = {
        /*"span"表示标签,".className"表示类,"#id"表示元素id*/
        filter: ".flow-node-drag",
        filterExclude: false,
        anchor: "Continuous",
        allowLoopback: false
    };
    var jsplumbTargetOptions = {
        /*"span"表示标签,".className"表示类,"#id"表示元素id*/
        filter: ".flow-node-drag",
        filterExclude: false,
        anchor: "Continuous",
        allowLoopback: false
    };

    
    function BtnAddGroup() {
        var node = {};
        node.id = "Group"+ Math.random().toString(36).substr(3, 10);
        node.name = '组';
        node.type = 'group';
        node.groupId = node.id;
        node.width = 300;
        node.height = 300;
        node.left = miniview_position.left * miniview_percent + (0);
        node.top =  miniview_position.top * miniview_percent + (0);
        addNode(node);
    }
    var jsPlumbZoom = 1;
    function BtnWorkflowSmall() {
        jsPlumbZoom -= 0.05;
        setZoom(jsPlumbZoom);
    }
    function BtnWorkflowBig() {
        jsPlumbZoom += 0.05;
        setZoom(jsPlumbZoom);
    }
    window.setZoom = function(zoom, instance, transformOrigin, el) {
      transformOrigin = transformOrigin || [ 0, 0 ];
      instance = instance || jsPlumb;
      el = el || instance.getContainer();
      var p = [ "webkit", "moz", "ms", "o" ],
          s = "scale(" + zoom + ")",
          oString = (transformOrigin[0] * 100) + "% " + (transformOrigin[1] * 100) + "%";

      for (var i = 0; i < p.length; i++) {
        el.style[p[i] + "Transform"] = s;
        el.style[p[i] + "TransformOrigin"] = oString;
      }

      el.style["transform"] = s;
      el.style["transformOrigin"] = oString;

      instance.setZoom(zoom);    
    };
    /*修改*/
    function BtnALLCancelSelection(){
         $(".nodeBox").each(function(){
            if($(this).hasClass('active')){
                $(this).removeClass('active');
                jsPlumb.removeFromDragSelection($(this));
            }
         })

    }
    $(function () {
        $("#flow-btns").children().draggable({
            helper: 'clone',
            scope: 'ss'
        })
        /*修改*/
        $("#flowBox").droppable({
            scope: 'ss',
            drop: function (event, ui) {
                var $chart = $(ui.draggable[0]);
                var node = {};
                node.id = "node" + Math.random().toString(36).substr(3, 10);
                node.name = $chart.attr("data-name");
                node.data_id = $chart.attr("id");
                node.data_code = $chart.attr("data-code");
                node.data_type = $chart.attr("data-type");
                node.type = 'chart';
                node.groupId = null;
                node.width = 150;
                node.height = 130;
                node.left = miniview_position.left * miniview_percent + (ui.position.left - 100);
                node.top =  miniview_position.top * miniview_percent + (ui.position.top - 50);
                node.EndpointList = getEndpointList(node);

                addNode(node);
            }
        })

        jsPlumb.ready(main);

        function main() {
            jsPlumb.importDefaults(jsplumbSetting);
            jsPlumb.setContainer('flowBox');
            jsPlumb.setSuspendDrawing(false, true);

            if (!!GetQuery('id')) {
                loadEasyFlowFinish =false;
                var id = GetQuery('id');

                getAjax("/WorkflowModule/Design/GetWorkflowInfo?id=" + id, {}, function (rs) {
                    var rs = eval("(" + rs + ")");
                    if (rs.status == "ok") {
                        workflowInfo = rs.data;
                        dataNodeList = rs.data.WrokflowNodeList;
                        dataLineList = rs.data.WrokflowLinesList;
                        loadEasyFlow();
                    }
                });
                jsPlumbEvent();
            }

        }
        setInterval(function(){
            HistoryData();
        },1000);
    })
    function jsPlumbEvent(){
        // 单点击了连接线,
        jsPlumb.bind('click', function (conn, originalEvent) {
            if(conn.id.substr(0,3)=='con'){
                 lineClick(conn, originalEvent);
            }
        });
        // 连线
        jsPlumb.bind("connection", function (evt) {
            var sourceId = evt.source.id;
            var targetId = evt.target.id;
            var sourceEndpointId = undefined;
            var targetEndpointId = undefined;
            var sourceNodeList = dataNodeList.filter(function (items) {
                if (items.id == sourceId) {
                    return true;
                }
                return false;
            });
            var targetNodeList = dataNodeList.filter(function (items) {
                if (items.id == targetId) {
                    return true;
                }
                return false;
            });
            if(sourceNodeList.length != 0){
                sourceEndpointId = evt.sourceEndpoint._jsPlumb.uuid;
            }
            if(targetNodeList.length != 0){
                targetEndpointId = evt.targetEndpoint._jsPlumb.uuid;
            }
            if (loadEasyFlowFinish) {
                dataLineList.push({ sourceId: sourceId, targetId: targetId,sourceEndpointId:sourceEndpointId,targetEndpointId:targetEndpointId });
            }
        });
        // 删除连线回调
        jsPlumb.bind("connectionDetached", function (evt) {
            var sourceEndpointId = evt.sourceEndpoint._jsPlumb.uuid;
            var targetEndpointId = evt.targetEndpoint._jsPlumb.uuid;
            deleteLine(sourceEndpointId, targetEndpointId);
        })
        //添加到组
        jsPlumb.bind("group:addMember",function(evt) {
           var nodeId = evt.el.id;
           var groupId = evt.group.id;
           var pos = evt.pos;

           for (var i = 0; i < dataNodeList.length; i++) {
                if (dataNodeList[i].id == nodeId) {
                    dataNodeList[i].groupId = groupId;
                    dataNodeList[i].left = pos.left;
                    dataNodeList[i].top = pos.top;
                    break;
                }
            }
        });
        //从组中删除
        jsPlumb.bind("group:removeMember",function(evt) {
            console.log(1)
           var nodeId = evt.el.id;
           var groupId = evt.group.id;
           var pos = evt.pos;

           for (var i = 0; i < dataNodeList.length; i++) {
                if (dataNodeList[i].id == nodeId) {
                    dataNodeList[i].groupId = null;
                    dataNodeList[i].left = pos.left;
                    dataNodeList[i].top = pos.top;
                    break;
                }
            }
        });
    }
    //单点击了连接线
    function lineClick(conn, originalEvent){
        var _layer = Getlayer();
        _layer.open({
            btn: ['保存', '删除'], //按钮
            yes: function (index, layero) {
                var lineText = parent.$("#layui-layer" + index).find("#lineText").val();
                conn.setLabel({
                    label: lineText,
                    cssClass: 'labelClass'
                });
                for (var i = 0; i < dataLineList.length; i++) {
                    if (dataLineList[i].conn_id == conn.id) {
                        dataLineList[i].labelName = lineText;
                        dataLineList[i].labelCss = 'labelClass';
                        break;
                    }
                };
                _layer.close(index);
            }, btn2: function (index, layero) {
                jsPlumb.deleteConnection(conn)
                _layer.close(index);
            },
            type: 1,
            title: '连线信息',
            area: ['420px', '310px'], //宽高
            content: '<textarea style="width:100%;height:200px;" id="lineText"  rows="10"></textarea>'
        });

    }
    // 删除线
    function deleteLine(sourceEndpointId,targetEndpointId) {
        dataLineList = dataLineList.filter(function (line) {
            if (line.sourceEndpointId == sourceEndpointId && line.targetEndpointId == targetEndpointId) {
                return false
            }
            return true
        })
    }
    /*修改*/
    //加载流程图
    function loadEasyFlow() {

        $("#flowBox").empty();
        //不在组里节点初始化
        var  dataNodeList1 = dataNodeList.filter(function (node) {
            return node.groupId == null || node.type == 'group';
        })
        for (var i = 0; i < dataNodeList1.length; i++) {
            var node = dataNodeList1[i];
            drawNode(node);
        }
         //不在组里节点初始化
        var  dataNodeList2 = dataNodeList.filter(function (node) {
            return node.groupId != null && node.type != 'group';
        })
        for (var i = 0; i < dataNodeList2.length; i++) {
            var node = dataNodeList2[i];
            drawNode(node);
        }
        loadLineList(dataLineList);
        //折叠的组折叠
        for (var i = 0; i < dataNodeList.length; i++) {
            if (dataNodeList[i].isCollapse == true && dataNodeList[i].type == 'group') {
               jsPlumb.collapseGroup(dataNodeList[i].id);
            }
        }
        jsPlumb.repaint($("#flowBox"));
        jsPlumb.repaintEverything();
        setInterval(function () {
            loadEasyFlowFinish = true;
        }, 500);
   }
   /*修改*/
   function  loadLineList(_dataLineList){
        // 初始化连线
        for (var i = 0; i < _dataLineList.length; i++) {
            var line = _dataLineList[i];
            var sourceEndpoint = null;
            if(line.sourceEndpointId != undefined){
                var sourceEndpoints = jsPlumb.getEndpoints(line.sourceId);
                var sourceEndpoint = sourceEndpoints.filter(function (itemEndpoint) {
                    return itemEndpoint._jsPlumb.uuid == line.sourceEndpointId
                })[0];
            }else{
                sourceEndpoint = line.sourceId;
            }
            var targetEndpoint = null;
            if(line.targetEndpointId != undefined){
                var targetEndpoints = jsPlumb.getEndpoints(line.targetId);
                var targetEndpoint = targetEndpoints.filter(function (itemEndpoint) {
                    return itemEndpoint._jsPlumb.uuid == line.targetEndpointId
                })[0];
            }else{
                targetEndpoint = line.targetId;
            }
            // console.log(sourceEndpoint);
            // console.log(targetEndpoint);
            var curline = jsPlumb.connect({
                source: sourceEndpoint,
                target: targetEndpoint
            }, jsplumbConnectOptions);
            if(curline !=undefined){
                _dataLineList[i].conn_id = curline.id;
                if (line.labelName != "") {
                    curline.setLabel({
                        label: line.labelName,
                        cssClass: line.labelCss
                    })
                }
            }
        }
   }
   function changeNodeSite(e) {
        var data = {};
        data.nodeId = $(e).attr("id");
        var position =$(e).position();
        data.left = position.left;
        data.top = position.top;
        for (var i = 0; i < dataNodeList.length; i++) {
            var node = dataNodeList[i];
            if (node.id == data.nodeId) {
                node.left = data.left;
                node.top = data.top;
            }
        }
    }
    function onmouseoverNode(e) {
        $(e).find(".flow-node-operate").show();
    }
    function onmouseoutNode(e) {
        $(e).find(".flow-node-operate").hide();
    }
    var currentNode = null;
    function onclickNode(e){
        currentNode = e;  
        if($(currentNode).hasClass('active')){
            $(currentNode).removeClass('active');
            jsPlumb.removeFromDragSelection($(currentNode));
        }
        $("#hide_input").focus();
        event.preventDefault(); // 阻止默认行为
        event.stopPropagation(); // 阻止事件冒泡
    }
    function hide_input_onkeydown(e) {
        var event = window.event;
        //删除
        if(event.keyCode==8 || event.keyCode==46){  //8--backspace;46--delete
            deleteNode(currentNode);
        }
        //选中  
        if(event.keyCode==13 && !$(currentNode).hasClass('nodeBox_group')){  //13--回车
            if($(currentNode).hasClass('active')){
                $(currentNode).removeClass('active');
                jsPlumb.removeFromDragSelection($(currentNode));
            }else{
                $(currentNode).addClass('active');
                jsPlumb.addToDragSelection($(currentNode), {
                    containment: 'parent'
                });
            }
        }
    }
    function ondblclickNode(e){
        var nodeId = $(e).attr("id");
        var _layer = Getlayer();
        _layer.open({
            btn: ['确认', '折叠','展开'], //按钮
            yes: function (index, layero) {
                var data = {};
                data.name = parent.$("#layui-layer" + index).find("#nodeInfoName").val();
                data.EndpointList = $nodeInfoTable.bootstrapTable('getData')
                var node ={};
                for (var i = 0; i < dataNodeList.length; i++) {
                    if (dataNodeList[i].id == nodeId) {
                        dataNodeList[i].name = data.name;
                        dataNodeList[i].EndpointList = data.EndpointList;
                        node = dataNodeList[i];
                        break;
                    }
                }
               var tmp_dataLineList = dataLineList.filter(function (items) {
                    if (items.targetId == nodeId || items.sourceId == nodeId) {
                        return true;
                    }
                    return false;
               });
               jsPlumb.removeAllEndpoints(nodeId); 
               for (var i = 0; i < data.EndpointList.length; i++) {
                 jsPlumb.addEndpoint(node.id, {uuid:data.EndpointList[i].id,anchors:locationToAnchors(data.EndpointList[i].location,node)}, GetEndpointOptions(data.EndpointList[i]));
               }
               loadLineList(tmp_dataLineList);

               _layer.close(index);
            }, btn2: function (index, layero) {
                var node ={};
                for (var i = 0; i < dataNodeList.length; i++) {
                    if (dataNodeList[i].id == nodeId) {
                        dataNodeList[i].isCollapse = true;
                        node = dataNodeList[i];
                        break;
                    }
                }
                if(node.type=='group'){
                    jsPlumb.collapseGroup(node.id);
                }
                _layer.close(index);
            }, btn3: function (index, layero) {
                var node ={};
                for (var i = 0; i < dataNodeList.length; i++) {
                    if (dataNodeList[i].id == nodeId) {
                        dataNodeList[i].isCollapse = false;
                        node = dataNodeList[i];
                        break;
                    }
                }
                if(node.type=='group'){
                    jsPlumb.expandGroup(node.id);
                }
                _layer.close(index);
            },
            type: 1,
            title: '设备信息',
            area: ['650px', '540px'],
            shadeClose: true, //开启遮罩关闭
            content: nodeInfoView(),
            success: function (layero, index) {
                var data = {};
                for (var i = 0; i < dataNodeList.length; i++) {
                    if (dataNodeList[i].id == nodeId) {
                        data = dataNodeList[i]
                        break;
                    }
                }
                parent.$("#layui-layer" + index).find("#nodeInfoName").val(data.name);
                $nodeInfoTable = parent.$("#layui-layer" + index).find("#nodeInfoTable");
                parent.$("#layui-layer" + index).find("#btn_nodeInfo_add").click(function(){btn_nodeInfo_add()});
                parent.$("#layui-layer" + index).find("#btn_nodeInfo_delete").click(function(){btn_nodeInfo_delete()});
                nodeInfoSetData(data);
            }
        });
        event.preventDefault(); // 阻止默认行为
        event.stopPropagation(); // 阻止事件冒泡
    }
    function nodeInfoSetData(data) {
        //SetWebControls(data);
        if(data.EndpointList ==undefined){data.EndpointList=[]}
        nodeInfoConditionTable(data.EndpointList);
    }
    var $nodeInfoTable = null
    function nodeInfoConditionTable(data) {
        $nodeInfoTable.bootstrapTable({
            data: data,
            //toolbar: '#nodeInfoToolbar',    //工具按钮用哪个容器
            striped: false,      //是否显示行间隔色
            cache: false,      //是否使用缓存,默认为true,所以一般情况下需要设置一下这个属性(*)
            pagination: false,     //是否显示分页(*)
            search: false,      //是否显示表格搜索,此搜索是客户端搜索,不会进服务端,所以,个人感觉意义不大
            strictSearch: false,
            showColumns: false,     //是否显示所有的列
            showRefresh: false,     //是否显示刷新按钮
            minimumCountColumns: 2,    //最少允许的列数
            clickToSelect: true,    //是否启用点击选中行
            height: 320,      //行高,如果没有设置height属性,表格自动根据记录条数觉得表格高度
            uniqueId: "id",      //每一行的唯一标识,一般为主键列
            showToggle: false,     //是否显示详细视图和列表视图的切换按钮
            cardView: false,     //是否显示详细视图
            detailView: false,     //是否显示父子表
            iconSize: 'outline',
            editable:true, //editable需要设置为 true
            columns: [{
                field: '',
                checkbox: true,
                align: 'center',
                valign: 'middle'
            }, {
                field: 'location',
                title: '位置',
                width:200,
                editable:{
                  type:"select",
                  options:{
                      items:[
                      "上左","上中","上右","上右","上右","右上","右中","右下","下右","下中","下左","左上","左中","左下"
                      ]
                  }
                }
            }, {
                field: 'color',
                title: '颜色',
                width:200,
                editable:{
                  type:"select",
                  options:{
                      items:[
                      "红","蓝","绿","灰"
                      ]
                  }
                }
            }, {
                field: 'name',
                title: '名称',
                width:200,
                editable:true
            }]
        });
    }
    function btn_nodeInfo_add() {
        var Data = $nodeInfoTable.bootstrapTable('getData');
        var length = Data.length;
        $nodeInfoTable.bootstrapTable('insertRow', { index: length, row: {id:Math.random().toString(36).substr(3, 10)} });
    }
    function btn_nodeInfo_delete() {
        var _layer = Getlayer();
        var Selections = $nodeInfoTable.bootstrapTable('getSelections');
        if (Selections.length > 1) {
            _layer.msg("只能选择一个编辑!");
        } else if (Selections.length == 0) {
            _layer.msg("请选择一个编辑项!");
        } else {
            _layer.confirm('确定删除该节点吗?', {
                btn: ['确认', '取消'] //按钮
            }, function (index) {
                var arry = [];
                arry.push(Selections[0].id);
                $nodeInfoTable.bootstrapTable('remove', { field: 'id', values: arry }); 
                _layer.close(index);
            }, function () {

            });
        }
    }
    function nodeInfoView(){
        var view ='<form id="nodeInfoForm">'+
        '<table class="FormTable" style="width: 100%;margin-bottom: 18px;" cellspacing="0" cellpadding="5" border="0">'+
                '<tbody>'+
                    '<tr>'+
                        '<td class="FormTable-label">'+
                            '名称'+
                        '</td>'+
                        '<td>'+
                            '<input id="nodeInfoName" name="nodeInfoName" type="text" class="form-control" />'+
                        '</td>'+
                    '</tr>'+
                '</tbody>'+
        '</table>'+
        '<div class="tooltip-demo">'+
            '<div class="btn-group" id="" role="group">'+
                '<div class="layui-btn" id="btn_nodeInfo_add">新增</div>'+
                '<div class="layui-btn" id="btn_nodeInfo_delete">删除</div>'+
            '</div>'+
            '<table id="nodeInfoTable">'+
            '</table>'+
        '</div>'+
        '</form>';
        return view;
    }
    function deleteNode(e) {
        var _layer = Getlayer();
        _layer.confirm('确定删除该节点吗?', {
            btn: ['确认', '取消'] //按钮
        }, function (index) {
            var nodeId = $(e).attr("id");
            var node = dataNodeList.filter(function (items) {
                if (items.id == nodeId) {
                    return true;
                }
                return false
            })[0];

            dataNodeList = dataNodeList.filter(function (items) {
                if (items.id == nodeId || (node.type == 'group' && node.groupId == items.groupId)) {
                    // 伪删除,将节点隐藏,否则会导致位置错位
                    items.show = false;
                    // $("#" + items.id).hide();
                    // setInterval(function () {
                    //     jsPlumb.removeAllEndpoints(items.id);
                    // }, 50);
                    jsPlumb.remove($("#"+items.id));
                    return false;
                }
                return true
            });
            _layer.close(index);

        }, function () {

        });
    }
    function drawNode(node) {
        if(node.type == 'group'){
            var nodeDiv = ['<div id="' + node.id + '" onmouseup="changeNodeSite(this)" onclick="onclickNode(this)" ondblclick="ondblclickNode(this)" class="nodeBox nodeBox_group"  style="left:' + node.left + 'px;top:' +  node.top + 'px;width:' + node.width + 'px;height:' + node.height + 'px"></div>'].join('');
            $("#flowBox").append(nodeDiv);
            jsPlumb.addGroup({
              el:eval('(' + node.id + ')'),
              id: node.groupId,
              constraint: false,//如果为true,则无法将子元素拖出组容器。
              dropOverride: false,//如果为true,则已拖放到其他组中的子元素将不受“prune”、“revert”或“orphan”施加的控制。
              revert:false,//如果将子元素拖到外部,子元素将恢复到容器。
              orphan: true,//如果为true,移出组元素则把该元素从组中删除
              //prune: true,//如果为true,则从组容器外部删除的子元素将从组中删除,也将从DOM中删除。
              //ghost:true,//是否留副本
              droppable: true,
              draggable: false //是否可以移动
            });

            // 拖拽改变大小
            $("#"+node.id).resizable({
                autoHide: true ,
                minHeight: 150,
                minWidth:150,
                containment: "parent",
                resize: function (event, ui) {
                    changeNodeSize(node.id,ui.size.width,ui.size.height);
                    //拖拽时点位跟着变动
                    jsPlumb.repaint(ui.helper);
                    jsPlumb.repaintEverything();
                }
            })
            jsPlumb.draggable(node.id);
        }
        if(node.type == 'chart'){
            var nodeDiv = ['<div data_name="'+node.name+'" onmouseup="changeNodeSite(this)" onclick="onclickNode(this)" ondblclick="ondblclickNode(this)" id="' + node.id + '" class="nodeBox" style="left:' + node.left + 'px;top:' + node.top + 'px;width:' + node.width + 'px;height:' + node.height + 'px">',
                '<div class="nodeBox-img ' + node.data_type + '"></div>',
                '<div class="nodeBox-text" >' + node.name + '</div>',
            '</div>'].join('');
            $("#flowBox").append(nodeDiv);
            // 拖拽改变大小
            $("#"+node.id).resizable({
                autoHide: true ,
                minHeight: 50,
                minWidth:50,
                aspectRatio:15/13,
                containment: "parent",
                resize: function (event, ui) {
                    changeNodeSize(node.id,ui.size.width,ui.size.height)
                    //拖拽时点位跟着变动
                    jsPlumb.repaint(ui.helper);
                    jsPlumb.repaintEverything();
                }
            })
            jsPlumb.draggable(node.id);
            if(node.groupId !=null){
                var el = eval('(' + node.id + ')');
                var groupNode = dataNodeList.filter(function (itemNode) {
                    return itemNode.id == node.groupId;
                })[0];
                $("#"+node.id).css('left',(groupNode.left + node.left)+"px");
                $("#"+node.id).css('top',(groupNode.top + node.top)+"px");
                jsPlumb.addToGroup(node.groupId, el);
            }
        }
        if(node.type == 'turnPoint'){
            var nodeDiv = ['<div id="' + node.id + '" onmouseup="changeNodeSite(this)" onclick="onclickNode(this)" class="nodeBox nodeBox_turnPoint"  style="left:' + node.left + 'px;top:' +  node.top + 'px;width:' + node.width + 'px;height:' + node.height + 'px;background-color:' + GetColorRgbByName(node.color) + '"></div>'].join('');
            $("#flowBox").append(nodeDiv);

            // 设置源点,可以拖出线连接其他节点
            jsPlumb.makeSource(node.id, jsplumbSourceOptions);
            // 设置目标点,其他源点拖出的线可以连接该节点
            jsPlumb.makeTarget(node.id, jsplumbTargetOptions);

            jsPlumb.draggable(node.id, {
                containment: 'parent'
            });
        }
        if(node.EndpointList !=null &&  node.EndpointList.length >0){
            for (var i = 0; i < node.EndpointList.length; i++) {
             jsPlumb.addEndpoint(node.id, {uuid:node.EndpointList[i].id,anchors:locationToAnchors(node.EndpointList[i].location,node)}, GetEndpointOptions(node.EndpointList[i]));
           }
        }
    }
    function changeNodeSize(nodeId,width,height) {
        for (var i = 0; i < dataNodeList.length; i++) {
            var node = dataNodeList[i];
            if (node.id == nodeId) {
                node.width = width;
                node.height = height;
            }
        }
    }

    function addNode(node) {
        dataNodeList.push(node);     
        drawNode(node);
    }
    function BtnSave() {
        var _layer = Getlayer();
        var postData = {};
        postData = workflowInfo;
        postData.WrokflowNodeList = dataNodeList;
        postData.WrokflowLinesList = dataLineList;
        getAjax("Save", "data=" + JSON.stringify(postData), function (rs) {
            var rs = eval("(" + rs + ")");
            if (rs.status == "ok") {
                _layer.msg("保存成功");
            } else {
                _layer.msg("保存失败");
            }
        });
    }
    function BtnWorkflowExport() {
        var data = {}
        data.workflowInfo = workflowInfo;
        data.dataNodeList = dataNodeList;
        data.dataLineList = dataLineList;
        var _layer = Getlayer();
        _layer.open({
            type: 1,
            title: '流程信息',
            area: ['420px', '280px'], //宽高
            content: '<textarea style="width:100%;height:200px;" id="workflowInfoText" name="workflowInfoText" rows="10">' + JSON.stringify(data) + '</textarea>'
        });
    }
    var HistoryDataList = [];
    //记录历史操作
    function HistoryData(){
        var data = {}
        data.workflowInfo = workflowInfo;
        data.dataNodeList = dataNodeList;
        data.dataLineList = dataLineList;
        var realTimeData = JSON.stringify(data);
        if(HistoryDataList.length ==0){
            HistoryDataList.push(realTimeData);
        }else{
            if(HistoryDataList.slice(-1)[0] != realTimeData){
                if(HistoryDataList.length>=4){
                    HistoryDataList.shift();
                }
                HistoryDataList.push(realTimeData);
            }
        }
    }
    //返回上一步
    function BtnGoBack() {
        HistoryDataList.pop();
        var data = eval("(" + HistoryDataList.pop() + ")");
        if(data != undefined){
            jsPlumb.reset();
            jsPlumbEvent();
            workflowInfo = data.workflowInfo;
            dataNodeList = data.dataNodeList;
            dataLineList = data.dataLineList;
            loadEasyFlowFinish = false;    
            loadEasyFlow(); 
        }
    }
    function BtnWorkflowImport() {
        var _layer = Getlayer();
        _layer.open({
            btn: ['保存', '取消'], //按钮
            yes: function (index, layero) {
                var workflowInfoText = parent.$("#layui-layer" + index).find("#workflowInfoText").val();
                var data = eval("(" + workflowInfoText + ")");

                //重置ID
                if (!!GetQuery('id')) {
                    data.workflowInfo.id = GetQuery('id');
                } else {
                    data.workflowInfo.id = "";
                }
               
                jsPlumb.reset();
                jsPlumbEvent();
                workflowInfo = data.workflowInfo;
                dataNodeList = data.dataNodeList;
                dataLineList = data.dataLineList;
                loadEasyFlowFinish = false;    
                loadEasyFlow(); 
                _layer.close(index);
            }, btn2: function (index, layero) {
                _layer.close(index);
            },
            type: 1,
            title: '流程信息',
            shadeClose: true, //开启遮罩关闭
            area: ['420px', '310px'], //宽高
            content: '<textarea style="width:100%;height:200px;" id="workflowInfoText" name="workflowInfoText" rows="10"></textarea>'
        })
    }
    $(".moveBlock").draggable({
        containment: "parent",
        drag: function (event, ui) {
            miniview_position = ui.position;
            var top = $("#flowBox").css("top");
            $("#flowBox").css({ top: '-' + ui.position.top * miniview_percent + "px" });
            var left = $("#flowBox").css("left");
            $("#flowBox").css({ left: '-' + ui.position.left * miniview_percent + "px" });
        }
    })
    /*修改*/
    //新增转折点
    function BtnAddTurnPoint(){
        var _layer = Getlayer();
        _layer.open({
            btn: ['确认', '取消'], //按钮
            yes: function (index, layero) {
                var color = parent.$("#layui-layer" + index).find("#color").val();
                var node = {};
                node.id = "TurnPoint"+ Math.random().toString(36).substr(3, 10);
                node.name = '转折点';
                node.type = 'turnPoint';
                node.groupId = null;
                node.color = color;
                node.width = 10;
                node.height = 10;
                node.left = miniview_position.left * miniview_percent + (10);
                node.top =  miniview_position.top * miniview_percent + (10);
                dataNodeList.push(node);    

                drawNode(node);
                _layer.close(index);
            }, btn2: function (index, layero) {
                _layer.close(index);
            },
            type: 1,
            title: '转折点',
            area: ['320px', '180px'], //宽高 
            shadeClose: true, //开启遮罩关闭
            content: TurnPointView(),
            success: function (layero, index) {

            }
        });
    }
    /*修改*/
    function TurnPointView(){
         var view ='<form id="turnPointForm">'+
        '<table class="FormTable" style="width: 100%;" cellspacing="0" cellpadding="5" border="0">'+
                '<tbody>'+
                    '<tr>'+
                        '<td>'+
                            '<select id="color" name="color" class="form-control" >'+
                                '<option value="红">红</option>'+
                                '<option value="蓝">蓝</option>'+
                                '<option value="绿">绿</option>'+
                                '<option value="灰">灰</option>'+
                            '</select>'
                        '</td>'+
                    '</tr>'+
                '</tbody>'+
        '</table>'+
        '</form>';
        return view;
    }

posted on 2022-03-01 20:55  搬砖狗-小强  阅读(217)  评论(0编辑  收藏  举报