//全局Ajax事件
$.ajaxSetup({
    dataType: 'JSON',
    cache: false,       //禁止IE9缓存
    dataFilter: function (data, type) {
        var result = JSON.parse(data);
        if (!result.isSuccess) alert(result.message);
        return data;
    }
});
$(document).ajaxError(function (event, xhr, settings, error) {
    alert('请求失败，请重试。');
});
$(document).ajaxStart(function () {
    layer.load(2, {shade: [0.3, '#3333333']});
});
$(document).ajaxStop(function () {
    layer.closeAll('loading');
});

//-----------------------------------------------------------------------------

var getUrlParams = function (name) {
    var url = window.location.search.substring(1);
    var variables = url.split('&');
    for (var i = 0; i < variables.length; i++) {
        var params = variables[i].split('=');
        if (params[0] == name) {
            return params[1];
        }
    }
};
var processId = undefined;                                 //流程id
var designId = getUrlParams('designId');             //设计标识
if (designId == undefined) {
    processId = getUrlParams('processId');
    if (processId != undefined) {
        $.ajax({
            type: 'GET',
            url: processEngineServer + '/api/design/process/' + processId,
            success: function (data) {
                if (!data.isSuccess) return;
                if (data.data == null) return;
                $('#name').val(data.data.name);
                $('#description').val(data.data.description);
            }
        });
    }
    if (processId == undefined) processId = jsPlumbUtil.uuid(); //没有processId时新建
    //console.log(processId);
    //加载流程图到设计空间
    $.ajax({
        async: false,
        type: 'POST',
        url: processEngineServer + '/api/design/load/process',
        data: {processId: processId},
        success: function (data) {
            if (!data.isSuccess) {
                alert('加载流程失败。');
                $('body').fadeOut(200);
                return;
            }
            designId = data.data;
            console.log('designId:' + designId);
        }
    });
}
var diagramId = getUrlParams('diagramId');      //图标识
if (processId == undefined) {
    //隐藏名称、描述文本框和保存按钮
    $('#nameContainer').hide();
    $('#descriptionContainer').hide();
    $('#extend').hide();
    $('#verify').hide();
    $('#save').hide();
    //$('#import').hide();
    //$('#export').hide();
}

jsPlumb.ready(function () {
    var connectionSubmit = false;         //连线提交标记，初次加载页面时connection时不提交到服务端
    //画布
    var canvas = document.getElementById('canvas');
    //jsPlumb实例
    var instance = jsPlumb.getInstance({
        ConnectionsDetachable: false,   //不允许拖动Endpoint
        //Endpoint: 'Blank',
        Endpoint: ['Dot', {radius: 7}],
        //Endpoint: ['Rectangle', { width: 15, height: 15 }],
        EndpointStyle: {'fill': '#cccccc', outlineStroke: 'black', outlineWidth: 1},
        Connector: ['Flowchart', {cornerRadius: 5}],
        PaintStyle: {stroke: 'gray', strokeWidth: 2},
        HoverPaintStyle: {stroke: '#ff0000', strokeWidth: 2},
        ConnectionOverlays: [['Arrow', {location: 1, id: 'arrow', width: 10, length: 10, foldback: 0.8}]],
        Container: 'canvas'
    });

    //切换连线类型
    $('#lineType').change(function () {
        var lineType = $('#lineType').val();
        console.log(lineType);
        var connector = undefined;
        if (lineType == '1') {
            connector = ['Flowchart', {cornerRadius: 5}];
        } else if (lineType == '2') {
            connector = ['StateMachine'];
        } else if (lineType == '3') {
            connector = ['Straight'];
        }
        if (connector == undefined)
            return;
        instance.importDefaults({Connector: connector});
        //重绘所有连线
        var connections = instance.getAllConnections();
        $.each(connections, function (index, conn) {
            //console.log(conn);
            conn.setConnector(connector);
            conn.addOverlay(['Arrow', {location: 1, id: 'arrow', width: 10, length: 10, foldback: 0.8}]);
        });
    });

    //-------------------------------------------------------------------------

    //拖动图例
    $('#legendContainer').children().draggable({
        helper: 'clone',
        scroll: false,
        grid: [10, 10]
    });
    //拖动图例到画布创建元素
    $('#canvas').droppable({
        drop: function (event, ui) {
            //第一次添加到画布时以legend的起始left/top计算，都取整后能正好对齐，否则会有偏移
            //printLayer(this);
            var left = parseInt(ui.offset.left - $(this).offset().left);
            var top = parseInt(ui.offset.top - $(this).offset().top);
            var activityType = ui.draggable[0].id;
            var id = jsPlumbUtil.uuid();
            //添加元素时调用服务端创建
            var el = undefined;
            switch (activityType) {
                case 'legendStart':
                    el = appendElementStart(id, left, top);
                    break;
                case 'legendTask':
                    el = appendElementTask(id, '未命名', left, top);
                    break;
                case 'legendDecision':
                    el = appendElementDecision(id, '未命名', left, top);
                    break;
                case 'legendConcurrency':
                    el = appendElementConcurrency(id, '未命名', left, top);
                    break;
                case 'legendReplication':
                    el = appendElementReplication(id, '未命名', left, top);
                    break;
                case 'legendEnd':
                    el = appendElementEnd(id, left, top);
                    break;
            }
            if (el != undefined) createActivity(el);
        }
    });
    //设置元素，添加拖动/缩放支持、设置连线source/target属性
    var setElement = function (el, activityType, id, sourceMaxConnections, targetMaxConnections, allowLoopback,
                               resizable, left, top, width, height) {
        el.id = id;
        el.style.left = left + 'px';
        el.style.top = top + 'px';
        if (width != undefined && width != '') el.style.width = parseInt(width) + 'px';
        if (height != undefined && height != '') el.style.height = parseInt(height) + 'px';
        el.className = 'element activity_' + activityType;
        el.setAttribute('activityType', activityType);
        instance.getContainer().appendChild(el);
        //设置元素可以连线，maxConnections=-1表示无限制，0表示不接收拉出连线/接收连线
        if (sourceMaxConnections != 0) {
            instance.makeSource(el, {
                filter: '.ctl_ep',
                //anchor: 'AutoDefault',
                anchor: 'Continuous',
                maxConnections: sourceMaxConnections,
                onMaxConnections: function (info, e) {
                    alert('最多只能有(' + info.maxConnections + ') 个后续流程活动。');
                }
            });
        }
        if (targetMaxConnections != 0) {
            instance.makeTarget(el, {
                //anchor: 'AutoDefault',        //只会显示在四个边中间位置
                anchor: 'Continuous',
                allowLoopback: allowLoopback,   //是否允许连接到自已
                maxConnections: targetMaxConnections,
                onMaxConnections: function (info, e) {
                    alert('最多只能有 (' + info.maxConnections + ') 个前置流程活动。');
                }
            });
        }
        //拖动支持
        instance.draggable(el, {
            //containment: 'parent',            //此配置会使超出画布显示区域（位于滚动条中）的元素一旦移动就跳回画布显示区域中
            grid: [10, 5],
            filter: '.ui-resizable-handle',     //拖动时过滤调整大小控制元素
            stop: function (event, ui) {
                saveLayout(el);
            }
        });
        //缩放支持
        if (resizable) {
            $(el).resizable({
                grid: [20, 10],
                autoHide: true,
                containment: 'parent',      //缩放时不超出父元素
                resize: function (event, ui) {
                    //printLayer(el);
                    $(el).children('.position_info').show();
                    var minWidth = parseInt($(el).css('min-width'));
                    var minHeight = parseInt($(el).css('min-height'));
                    var width = $(el).width();
                    var height = $(el).height();
                    if (width < minWidth) width = minWidth; else width = width + 4;
                    if (height < minHeight) height = minHeight; else height = height + 4;
                    $(el).children('.position_info').text(width + ' * ' + height);
                    instance.repaintEverything();
                    //instance.repaint(el.id);
                    instance.revalidate(el.id); //resize后重新计算endpoints位置
                },
                stop: function (event, ui) {
                    //printLayer(el);
                    $(el).children('.position_info').hide();
                    //resize后长宽会少2像素
                    //console.log(ui.size);   //当有min-*设置时，此信息为释放鼠标的位置，与元素尺寸不一致
                    var minWidth = parseInt($(el).css('min-width'));
                    var minHeight = parseInt($(el).css('min-height'));
                    var width = $(el).width();
                    var height = $(el).height();
                    if (width > minWidth) $(el).css('width', (width + 4) + 'px');
                    if (height > minHeight) $(el).css('height', (height + 4) + 'px');
                    saveLayout(el);
                }
            });
        }
    };
    var appendElementStart = function (id, left, top) {
        var el = document.createElement('div');
        el.innerHTML = '<div class="title">开始</div><div class="control_container">' +
            '<div class="ctl_ep fa fa-arrow-right"></div>' +
            '<div class="ctl_sel fa fa-check"></div><div class="ctl_del fa fa-remove"></div></div>';
        setElement(el, 'start', id, 1, 0, false
            , false, left, top);
        return el;
    };
    var appendElementTask = function (id, name, left, top, width, height) {
        var el = document.createElement('div');
        el.innerHTML = '<div class="position_info"></div><div class="title">处理</div><div class="name">' + name + '</div>' +
            '<div class="control_container"><div class="ctl_ep fa fa-arrow-right"></div><div class="ctl_edit fa fa-cog"></div>' +
            '<div class="ctl_sel fa fa-check"></div><div class="ctl_del fa fa-remove"></div></div>';
        setElement(el, 'task', id, -1, -1, true
            , true, left, top, width, height);
        return el;
    };
    var appendElementDecision = function (id, name, left, top, width, height) {
        var el = document.createElement('div');
        el.innerHTML = '<div class="position_info"></div><div class="title">判定</div><div class="name">' + name + '</div>' +
            '<div class="control_container"><div class="ctl_ep fa fa-arrow-right"></div><div class="ctl_edit fa fa-cog"></div>' +
            '<div class="ctl_sel fa fa-check"></div><div class="ctl_del fa fa-remove"></div></div>';
        setElement(el, 'decision', id, -1, -1, false
            , true, left, top, width, height);
        return el;
    };
    var appendElementConcurrency = function (id, name, left, top, width, height) {
        var el = document.createElement('div');
        el.innerHTML = '<div class="position_info"></div><div class="title">并行</div><div class="name">' + name + '</div>' +
            '<div class="control_container"><div class="ctl_ep fa fa-arrow-right"></div><div class="ctl_edit fa fa-cog"></div>' +
            '<div class="ctl_sel fa fa-check"></div><div class="ctl_del fa fa-remove"></div></div>' +
            '<div class="concurrency_subprocesses"></div><div class="concurrency_subprocess_new fa fa-plus" title="添加子流程"></div>';
        setElement(el, 'concurrency', id, 1, -1, false
            , true, left, top, width, height);
        return el;
    };
    var appendElementReplication = function (id, name, left, top, width, height) {
        var el = document.createElement('div');
        el.innerHTML = '<div class="position_info"></div><div class="title">重复</div><div class="name">' + name + '</div>' +
            '<div class="control_container"><div class="ctl_ep fa fa-arrow-right"></div><div class="ctl_edit fa fa-cog"></div>' +
            '<div class="ctl_sel fa fa-check"></div><div class="ctl_del fa fa-remove"></div></div>' +
            '<div class="replication_subprocess"><a href="design.html?designId=' + designId + '&diagramId=' + id + '" target="_blank" title="子流程设计"><i class="fa fa-edit"></i></a></div>';
        setElement(el, 'replication', id, 1, -1, false
            , true, left, top, width, height);
        return el;
    };
    var appendElementEnd = function (id, left, top/*, hasCc*/) {
        var el = document.createElement('div');
        el.innerHTML = //'<div class="title' + (hasCc ? ' highlight' : '') + '">结束</div>'
            '<div class="title">结束</div>'
            //+ '<div class="control_container">' + (diagramId == undefined ? '<div class="ctl_edit fas fa-cog"></div>' : '') //只能根流程可以配置抄送
            + '<div class="control_container">'
            + '<div class="ctl_sel fa fa-check"></div><div class="ctl_del fa fa-remove"></div></div>';
        setElement(el, 'end', id, 0, -1, false,
            false, left, top);
        return el;
    };
    //删除元素
    jsPlumb.on(canvas, 'click', '.ctl_del', function (e) {
        var el = $(this).closest('.element');
        var activityId = el.attr('id');
        var activityType = el.attr('activityType');
        var msg = '确认删除此活动？';
        if (activityType == 'start') msg = '确认删除开始活动？';
        else if (activityType == 'activity-end') msg = '确认删除结束活动？';
        else if ($.trim(el.children('.name').text())) msg = '确认删除“' + $.trim(el.children('.name').text()) + '”活动？';
        if (confirm(msg)) {
            $.ajax({
                type: 'POST',
                url: processEngineServer + '/api/design/activity/remove',
                data: {designId: designId, diagramId: diagramId, activityId: activityId},
                success: function (data) {
                    if (data.isSuccess) instance.remove(el);
                }
            });
        }
    });
    //创建活动
    var createActivity = function (el) {
        var left = el.offsetLeft;
        var top = el.offsetTop;
        var width = $(el).outerWidth();
        var height = $(el).outerHeight();
        var activityType = $(el).attr('activityType');
        var activityId = el.id;
        var name = $(el).children('.name').text();
        var data = {
            designId: designId,
            diagramId: diagramId,
            activityType: activityType,
            activityId: activityId,
            name: name,
            left: left,
            top: top,
            width: width,
            height: height
        };
        console.log(data);
        $.ajax({
            type: 'POST',
            url: processEngineServer + '/api/design/activity/create',
            data: data,
            success: function (data) {
                if (!data.isSuccess) instance.remove(id);
            },
            error: function () {
                instance.remove(id);
            }
        });
    };
    //打印布局信息，调试用
    var printLayer = function (el) {
        console.log(
            'element:offsetLeft=' + el.offsetLeft + ',offsetTop=' + el.offsetTop + ','
            + 'offsetWidth=' + el.offsetWidth + ',offsetHeight=' + el.offsetHeight + ';'
            + 'jquery:offset=' + JSON.stringify($(el).offset()) + ','
            + 'position=' + JSON.stringify($(el).position()) + ','
            + 'scrollLeft=' + $(el).scrollLeft() + ',scrollTop=' + $(el).scrollTop() + ','
            + 'width=' + $(el).width() + ',height=' + $(el).height() + ','
            + 'outerWidth=' + $(el).outerWidth() + ',outerHeight=' + $(el).outerHeight() + ','
            + 'innerWidth=' + $(el).innerWidth() + ',innerHeight=' + $(el).innerHeight() + ','
            + 'css(width)=' + $(el).css('width') + ',css(height)=' + $(el).css('height') + ';'
        );
    };
    //保存布局信息
    var saveLayout = function (el) {
        //element加上样式box-sizing: border-box;后需使用outerWidth()和outerHeight()，否则使用width()和height()
        var left = el.offsetLeft;
        var top = el.offsetTop;
        var width = $(el).outerWidth();
        var height = $(el).outerHeight();
        var activityId = el.id;
        var data = {
            designId: designId,
            diagramId: diagramId,
            activityId: activityId,
            left: left,
            top: top,
            width: width,
            height: height
        };
        //printLayer(el);
        //console.log(data);
        $.ajax({
            type: 'POST',
            url: processEngineServer + '/api/design/layout',
            data: data
        });
    };
    //扩展数据及组件管理
    $('#extend').click(function () {
        $.ajax({
            type: 'GET',
            url: processEngineServer + '/api/design/extend',
            data: {designId: designId},
            success: function (data) {
                //console.log(data);
                if (!data.isSuccess) return;
                $('#extendEnabled').prop('checked', data.data.extendEnabled);
                $('#extendName').val(data.data.extendName);
                $('#extendControls').empty();
                $('#extendControls').append('<tr><th>流程活动</th><th>扩展组件名</th></tr>');
                $.each(data.data.extendControls, function (c, item) {
                    $('#extendControls').append('<tr><td style="display:none;">' + item.activityId
                        + '</td><td style="text-align: right;">' + item.activityName
                        + '</td><td><input type="text" value="' + item.controlName + '" /></td></tr>');
                });
                $('#dialogExtend').dialog({
                    width: 500,
                    modal: true,
                    title: '扩展数据及组件管理',
                    buttons: [{
                        text: '确定',
                        click: function () {
                            var extendEnabled = $('#extendEnabled').prop('checked');
                            var extendName = $.trim($('#extendName').val());
                            var extendControls = $.map($('#extendControls tr'), function (item, index) {
                                if (index > 0) {
                                    return {
                                        activityId: $(item).find('td').first().text(),
                                        controlName: $(item).find('input').first().val()
                                    };
                                }
                            });
                            $.ajax({
                                type: 'POST',
                                url: processEngineServer + '/api/design/extend',
                                data: JSON.stringify({
                                    designId: designId,
                                    extendEnabled: extendEnabled,
                                    extendName: extendName,
                                    extendControls: extendControls
                                }),
                                contentType: 'application/json',
                                success: function (data) {
                                    if (data.isSuccess) {
                                        $('#dialogExtend').dialog('close');
                                    }
                                }
                            });
                        }
                    }]
                });
            }
        });
    });
    //验证流程
    $('#verify').click(function () {
        $.ajax({
            type: 'POST',
            url: processEngineServer + '/api/design/verify',
            data: {designId: designId},
            success: function (data) {
                alert(data.data);
            }
        });
    });
    //保存流程
    $('#save').click(function () {
        $('#canvas .element').each(function (i, el) {
            saveLayout(el); //保存每个元素位置
        });
        $.ajax({
            type: 'POST',
            url: processEngineServer + '/api/design/save',
            data: {
                processId: processId,
                designId: designId,
                name: $('#name').val(),
                description: $('#description').val()
            },
            success: function (data) {
                if (data.isSuccess) alert('保存成功。');
            }
        });
    });
    //导入
    $('#import').click(function () {
        $('#dialogImport').dialog({
            width: 500,
            modal: true,
            title: '导入',
            buttons: [{
                text: '确定',
                click: function () {
                    var importXml = $.trim($('#importXml').val());
                    $.ajax({
                        type: 'POST',
                        url: processEngineServer + '/api/design/import',
                        data: {
                            designId: designId,
                            importXml: importXml
                        },
                        success: function (data) {
                            if (data.isSuccess) {
                                connectionSubmit = false;
                                //清空现有图上的元素
                                instance.deleteEveryConnection();
                                instance.deleteEveryEndpoint();
                                jsPlumb.empty(canvas);
                                connectionSubmit = false
                                loadDesign();
                                $('#dialogImport').dialog('close');
                            }
                        }
                    });
                }
            }]
        });
    });

    //-------------------------------------------------------------------------

    //添加并行子流程元素
    var appendElementConcurrencySubprocess = function (activityId, subprocessId, subprocessName) {
        $('#' + activityId).children('.concurrency_subprocesses').append(
            '<div class="concurrency_subprocess" id="' + subprocessId + '">' +
            '<div class="concurrency_subprocess_name"><a href="design.html?designId=' + designId + '&diagramId=' + subprocessId + '" title="' + subprocessName + '" target="_blank">' + subprocessName + '</a></div>' +
            '<div class="concurrency_subprocess_delete fa fa-trash-o"></div><div class="concurrency_subprocess_edit fa fa-edit"></div></div>'
        );
    };
    //删除并行子流程
    jsPlumb.on(canvas, 'click', '.concurrency_subprocess_delete', function (e) {
        var activityId = $(this).closest('.element').attr('id');
        var subprocessId = $(this).parent().attr('id');
        if (confirm('是否删除此子流程？')) {
            $.ajax({
                type: 'POST',
                url: processEngineServer + '/api/design/concurrency/subprocess/remove',
                data: {designId: designId, diagramId: diagramId, activityId: activityId, subprocessId: subprocessId},
                success: function (data) {
                    if (data.isSuccess) $('#' + subprocessId).remove();
                }
            });
        }
    });
    //添加并行子流程
    jsPlumb.on(canvas, 'click', '.concurrency_subprocess_new', function (e) {
        var el = $(this).closest('.element');
        var activityId = el.attr('id');
        $('#subprocessName').val('');       //新建子流程时清空名称
        $('#dialogConcurrencySubprocess').dialog({
            modal: true,
            width: 500,
            title: '添加并行子流程',
            buttons: [{
                text: '确定',
                click: function () {
                    var subprocessName = $.trim($('#subprocessName').val());
                    var subprocessId = jsPlumbUtil.uuid();
                    $.ajax({
                        type: 'POST',
                        url: processEngineServer + '/api/design/concurrency/subprocess/create',
                        data: {
                            designId: designId,
                            diagramId: diagramId,
                            activityId: activityId,
                            subprocessId: subprocessId,
                            subprocessName: subprocessName
                        },
                        success: function (data) {
                            if (data.isSuccess) {
                                appendElementConcurrencySubprocess(activityId, subprocessId, subprocessName);
                                $('#dialogConcurrencySubprocess').dialog('close');
                            }
                        }
                    });
                }
            }]
        });
    });
    //编辑并行子流程
    jsPlumb.on(canvas, 'click', '.concurrency_subprocess_edit', function (e) {
        var el = $(this).closest('.element');
        var activityId = el.attr('id');
        if (el.attr('activityType') != 'concurrency') return;
        var subprocess = $(this).closest('.concurrency_subprocess');
        var subprocessId = subprocess.attr('id');
        var subprocessNameAnchor = subprocess.children('.concurrency_subprocess_name').children('a');
        $('#subprocessName').val(subprocessNameAnchor.text());
        $('#dialogConcurrencySubprocess').dialog({
            modal: true,
            width: 500,
            title: '编辑并行子流程',
            buttons: [{
                text: '确定',
                click: function () {
                    var subprocessName = $.trim($('#subprocessName').val());
                    $.ajax({
                        type: 'POST',
                        url: processEngineServer + '/api/design/concurrency/subprocess/modify',
                        data: {
                            designId: designId,
                            diagramId: diagramId,
                            activityId: activityId,
                            subprocessId: subprocessId,
                            subprocessName: subprocessName
                        },
                        success: function (data) {
                            if (data.isSuccess) {
                                subprocessNameAnchor.text(subprocessName);
                                subprocessNameAnchor.prop('title', subprocessName);
                                $('#dialogConcurrencySubprocess').dialog('close');
                            }
                        }
                    });
                }
            }]
        });
    });

    //-------------------------------------------------------------------------

    //全选
    $('#selectAll').click(function () {
        $('#canvas .element').each(function (index) {
            if (!$(this).hasClass('element_selected')) {
                $(this).addClass('element_selected');
                instance.addToDragSelection($(this));
            }
        });
    });
    //点击空白处取消选中
    $('#canvas').on('click', function (e) {
        if ($(e.target).closest('.element').length == 0) {
            $('#canvas .element').each(function (index) {
                if ($(this).hasClass('element_selected'))
                    $(this).removeClass('element_selected');
            });
            instance.clearDragSelection();
        }
    });
    //选中元素
    $('#canvas').on('click', '.ctl_sel', function (e) {
        var target = $(e.target).closest('.element');
        if (target.hasClass('element_selected')) {
            target.removeClass('element_selected');
            instance.removeFromDragSelection(target);
        } else {
            target.addClass('element_selected');
            instance.addToDragSelection(target);
        }
    });
    //鼠标事件，元素控制图标显示/隐藏
    $('#canvas').on('mouseenter', '.element', function () {
        $(this).children('.control_container').show();
    });
    $('#canvas').on('mouseleave', '.element', function () {
        $(this).children('.control_container').hide();
    });

    var zindex = 1;
    //点击元素使其置顶
    jsPlumb.on(canvas, "click", ".element", function (e) {
        $(this).css("z-index", ++zindex);
    });
    //点击连线使其置顶
    jsPlumb.on(canvas, "click", ".jtk-overlay", function (e) {
        $(this).css("z-index", ++zindex);
    });

    //-------------------------------------------------------------------------

    //连接元素
    instance.bind('connection', function (info) {
        //console.log(info);
        var conn = info.connection;
        if (instance.select({source: conn.sourceId, target: conn.targetId}).length > 1) {
            alert('不能重复连接。');
            instance.deleteConnection(conn);
            return;
        }
        var activityType = $(info.source).attr('activityType');
        var name = '';
        //设置判定条件连接事件
        if (activityType == 'decision') {
            name = '未命名条件';
            //info.connection.getOverlay('label').setLabel(info.connection.id);
            //var count = instance.getConnections({source: info.sourceId}).length;
            conn.addOverlay([
                'Label', {
                    //label: count + '.' + name,
                    label: name,
                    id: 'label',
                    cssClass: 'connection_label',
                    events: {
                        click: function (params) {
                            //$console(params);
                            var sourceId = $(params).attr('sourceId');
                            var targetId = $(params).attr('targetId');
                            $.ajax({
                                type: 'GET',
                                url: processEngineServer + '/api/design/decision/condition',
                                data: {
                                    designId: designId,
                                    diagramId: diagramId,
                                    sourceId: sourceId,
                                    targetId: targetId
                                },
                                success: function (data) {
                                    if (!data.isSuccess) return;
                                    $('#conditionName').val(data.data.conditionName);
                                    $('#conditionExpression').val(data.data.conditionExpression);
                                    $('#dialogDecisionCondition').dialog({
                                        modal: true,
                                        width: 500,
                                        title: '配置判定条件',
                                        buttons: [{
                                            text: '确定',
                                            click: function () {
                                                var conditionName = $('#conditionName').val();
                                                var conditionExpression = $('#conditionExpression').val();
                                                $.ajax({
                                                    type: 'POST',
                                                    url: processEngineServer + '/api/design/decision/condition/modify',
                                                    data: {
                                                        designId: designId,
                                                        diagramId: diagramId,
                                                        sourceId: sourceId,
                                                        targetId: targetId,
                                                        conditionName: conditionName,
                                                        conditionExpression: conditionExpression
                                                    },
                                                    success: function (data) {
                                                        if (data.isSuccess) {
                                                            //params.setLabel(data.data.conditionIndex + '.' + conditionName);
                                                            params.setLabel(conditionName);
                                                            $('#dialogDecisionCondition').dialog('close');
                                                        }
                                                    }
                                                });
                                            }
                                        }]
                                    });
                                }
                            });
                        }
                    }
                }
            ]);
            //info.connection.getOverlay('label').setLabel(count + '.' + name);
            var lbl = info.connection.getOverlay('label');
            $(lbl).attr('sourceId', conn.sourceId);
            $(lbl).attr('targetId', conn.targetId);
        }
        //设置处理动作连接事件
        if (activityType == 'task') {
            name = '未命名动作';
            conn.addOverlay([
                'Label', {
                    label: name,
                    id: 'label',
                    cssClass: 'connection_label',
                    events: {
                        click: function (params) {
                            var sourceId = $(params).attr('sourceId');
                            var targetId = $(params).attr('targetId');
                            //$console(params);
                            $.ajax({
                                type: 'GET',
                                url: processEngineServer + '/api/design/task/action',
                                data: {
                                    designId: designId,
                                    diagramId: diagramId,
                                    sourceId: sourceId,
                                    targetId: targetId
                                },
                                success: function (data) {
                                    if (!data.isSuccess) return;
                                    $('#actionSid').val(data.data.actionSid);
                                    $('#actionName').val(data.data.actionName);
                                    $('#actionDescription').val(data.data.actionDescription);
                                    $('#actionAdditionalControl').val(data.data.actionAdditionalControl);
                                    $('#actionAdditionalControlParam').val(data.data.actionAdditionalControlParam);
                                    $('#actionCommentLabel').val(data.data.actionCommentLabel);
                                    console.log(data.data.actionCommentRequired);
                                    if (data.data.actionCommentRequired != null) {
                                        $('#actionCommentRequired').val(data.data.actionCommentRequired.toString());
                                    }
                                    $('#actionSwitchable').prop('checked', data.data.actionSwitchable);
                                    if (!data.data.actionSwitchable)
                                        $('#trActionSwitchParam').hide();
                                    else
                                        $('#trActionSwitchParam').show();
                                    $('#actionSwitchParam').val(data.data.actionSwitchParam);
                                    $('#dialogTaskAction').dialog({
                                        modal: true,
                                        width: 500,
                                        title: '配置处理动作',
                                        buttons: [{
                                            text: '确定',
                                            click: function () {
                                                var actionSid = $('#actionSid').val();
                                                var actionName = $('#actionName').val();
                                                var actionDescription = $('#actionDescription').val();
                                                var actionAdditionalControl = $('#actionAdditionalControl').val();
                                                var actionAdditionalControlParam = $('#actionAdditionalControlParam').val();
                                                var actionCommentLabel = $('#actionCommentLabel').val();
                                                var actionCommentRequired = $('#actionCommentRequired').val();
                                                var actionSwitchable = $('#actionSwitchable').prop('checked');
                                                var actionSwitchParam = $('#actionSwitchParam').val();
                                                $.ajax({
                                                    type: 'POST',
                                                    url: processEngineServer + '/api/design/task/action/modify',
                                                    data: {
                                                        designId: designId,
                                                        diagramId: diagramId,
                                                        sourceId: sourceId,
                                                        targetId: targetId,
                                                        actionSid: actionSid,
                                                        actionName: actionName,
                                                        actionDescription: actionDescription,
                                                        actionAdditionalControl: actionAdditionalControl,
                                                        actionAdditionalControlParam: actionAdditionalControlParam,
                                                        actionCommentLabel: actionCommentLabel,
                                                        actionCommentRequired: actionCommentRequired,
                                                        actionSwitchable: actionSwitchable,
                                                        actionSwitchParam: actionSwitchParam
                                                    },
                                                    success: function (data) {
                                                        if (data.isSuccess) {
                                                            params.setLabel(actionName + (actionDescription ? '<br />' + actionDescription : ''));
                                                            $('#dialogTaskAction').dialog('close');
                                                        }
                                                    }
                                                });
                                            }
                                        }]
                                    });
                                }
                            });
                        }
                    }
                }
            ]);
            var lbl = info.connection.getOverlay('label');
            $(lbl).attr('sourceId', conn.sourceId);
            $(lbl).attr('targetId', conn.targetId);
        }

        if (!connectionSubmit) return;
        $.ajax({
            type: 'POST',
            url: processEngineServer + '/api/design/connection/create',
            data: {
                designId: designId,
                diagramId: diagramId,
                sourceId: info.sourceId,
                targetId: info.targetId,
                name: name
            },
            success: function (data) {
                if (!data.isSuccess) instance.deleteConnection(info.connection);
            },
            error: function () {
                instance.deleteConnection(info.connection);
            }
        });
    });
    //双击删除连线
    instance.bind('dblclick', function (c) {
        var l = c.getOverlay('label');
        var t = '';
        if (l != undefined) t = $.trim(c.getOverlay('label').getLabel());
        var msg = '是否删除此连线？';
        if (t) msg = '是否删除“' + t + '”？';
        if (confirm(msg)) {
            $.ajax({
                type: 'POST',
                url: processEngineServer + '/api/design/connection/remove',
                data: {designId: designId, diagramId: diagramId, sourceId: c.sourceId, targetId: c.targetId},
                success: function (data) {
                    if (!data.isSuccess) return;
                    instance.deleteConnection(c);
                    //重新设置判定条件索引
                    /*if ($('#' + c.sourceId).attr('activityType') == 'decision') {
                        var detachIndex = parseInt(t.substring(0, t.indexOf('.')));
                        var conns = instance.getConnections({source: c.sourceId});
                        for (var i = 0; i < conns.length; i++) {
                            var lbl = $.trim(conns[i].getOverlay('label').getLabel());
                            var dotIndex = lbl.indexOf('.');
                            var index = parseInt(lbl.substring(0, dotIndex));
                            if (index > detachIndex)
                                conns[i].getOverlay('label').setLabel((index - 1) + '.' + lbl.substring(dotIndex + 1, lbl.length));
                        }
                    }*/
                }
            });
        }
    });

    //-------------------------------------------------------------------------

    //编辑活动
    jsPlumb.on(canvas, 'click', '.ctl_edit', function (e) {
        var el = $(this).closest('.element');
        var activityType = el.attr('activityType');
        var activityId = el.attr('id');
        //处理活动
        if (activityType == 'task') {
            $.ajax({
                type: 'GET',
                url: processEngineServer + '/api/design/task',
                data: {designId: designId, diagramId: diagramId, activityId: activityId},
                success: function (data) {
                    //console.log(data);
                    if (!data.isSuccess) return;
                    $('#taskName').val(data.data.taskName);
                    $('#taskSid').val(data.data.taskSid);
                    $('#taskActorExpression').val(data.data.taskActorExpression);
                    $('#taskAllowDeliver').prop('checked', data.data.taskAllowDeliver);
                    if (!data.data.taskAllowDeliver)
                        $('#trTaskDeliverControl').hide();
                    $('#taskDeliverControl').val(data.data.taskDeliverControl);
                    $('#taskAllowTakeBack').prop('checked', data.data.taskAllowTakeBack);
                    //初始化可退回至范围
                    $('#taskAllowReturnRange').empty();
                    $.each(data.data.taskAllowReturnRange, function (index, item) {
                        $('#taskAllowReturnRange').append('<input type="checkbox" id="taskAllowReturnTo" value="' + item.id + '" />' + item.name + '<br />');
                    });
                    //选中已勾选的退回至活动
                    $.each(data.data.taskAllowReturnTo, function (index, item) {
                        console.log(item);
                        if(item.indexOf("]") == -1){
                            $('#taskAllowReturnTo[value="' + item + '"]').prop('checked', true);
                        }
                        else {
                            var itemLsit= JSON.parse(item);
                            itemLsit.forEach(function(i){
                                $('#taskAllowReturnTo[value="' + i + '"]').prop('checked', true);
                            })
                        }

                    });
                    if (data.data.taskAllowReturnRange.length == 0) {
                        $('#taskAllowReturnRange').append('没有可以退回至的活动。');
                    }
                    $('#actionOrder').empty();
                    $.each(data.data.taskActions, function (c, item) {
                        $('#actionOrder').append('<tr><td style="display:none;">' + item.nextActivityId + '</td><td>' + item.name + '</td><td><button onclick="var row=$(this).closest(\'tr\');var prev=row.prev();if(prev.length){prev.before(row);}">上移</button> <button onclick="var row=$(this).closest(\'tr\');var next=row.next();if(next.length){next.after(row);}">下移</button></td></tr>');
                    });
                    $('#dialogTask').dialog({
                        width: 500,
                        modal: true,
                        title: '配置处理活动',
                        buttons: [{
                            text: '确定',
                            click: function () {
                                var taskName = $.trim($('#taskName').val());
                                var taskSid = $.trim($('#taskSid').val());
                                var taskActorExpression = $.trim($('#taskActorExpression').val());
                                var taskAllowDeliver = $('#taskAllowDeliver').prop('checked');
                                var taskDeliverControl = $.trim($('#taskDeliverControl').val());
                                var taskAllowTakeBack = $('#taskAllowTakeBack').prop('checked');
                                var taskAllowReturnTo = [];
                                $('#taskAllowReturnTo:checked').each(function (i) {
                                    taskAllowReturnTo[i] = $(this).val();
                                });
                                var actionOrder = $.map($('#actionOrder tr td:first-child'), function (item, index) {
                                    return item.innerText;
                                });
                                /*console.log(actionOrder);
                                return;*/

                                $.ajax({
                                    type: 'POST',
                                    url: processEngineServer + '/api/design/task/modify',
                                    data: {
                                        designId: designId,
                                        diagramId: diagramId,
                                        activityId: activityId,
                                        taskName: taskName,
                                        taskSid: taskSid,
                                        taskActorExpression: taskActorExpression,
                                        taskAllowDeliver: taskAllowDeliver,
                                        taskDeliverControl: taskDeliverControl,
                                        taskAllowTakeBack: taskAllowTakeBack,
                                        taskAllowReturnTo: taskAllowReturnTo,
                                        actionOrder: actionOrder
                                    },
                                    success: function (data) {
                                        if (data.isSuccess) {
                                            el.children('.name').html(taskName + (taskSid == '' ? '' : '<br>[' + taskSid + ']'));
                                            $('#dialogTask').dialog('close');
                                        }
                                    }
                                });
                            }
                        }]
                    });
                }
            });
            return;
        }
        //判定活动
        if (activityType == 'decision') {
            $.ajax({
                type: 'GET',
                url: processEngineServer + '/api/design/decision',
                data: {designId: designId, diagramId: diagramId, activityId: activityId},
                success: function (data) {
                    //console.log(data);
                    if (!data.isSuccess) return;
                    $('#decisionName').val(data.data.decisionName);
                    $('#decisionSid').val(data.data.decisionSid);
                    $('#decisionOrder').empty();
                    $.each(data.data.decisionConditions, function (index, item) {
                        $('#decisionOrder').append('<tr><td style="display:none;">' + item.nextActivityId + '</td><td>' + item.name + '</td><td><button onclick="var row=$(this).closest(\'tr\');var prev=row.prev();if(prev.length){prev.before(row);}">上移</button> <button onclick="var row=$(this).closest(\'tr\');var next=row.next();if(next.length){next.after(row);}">下移</button></td></tr>');
                    });
                    $('#dialogDecision').dialog({
                        modal: true,
                        width: 500,
                        title: '配置判定活动',
                        buttons: [{
                            text: '确定',
                            click: function () {
                                var decisionName = $.trim($('#decisionName').val());
                                var decisionSid = $.trim($('#decisionSid').val());
                                var decisionOrder = $.map($('#decisionOrder tr td:first-child'), function (item, index) {
                                    return item.innerText;
                                });
                                /*console.log(decisionOrder);
                                return;*/

                                $.ajax({
                                    type: 'POST',
                                    url: processEngineServer + '/api/design/decision/modify',
                                    data: {
                                        designId: designId,
                                        diagramId: diagramId,
                                        activityId: activityId,
                                        decisionName: decisionName,
                                        decisionSid: decisionSid,
                                        decisionOrder: decisionOrder
                                    },
                                    success: function (data) {
                                        if (data.isSuccess) {
                                            el.children('.name').html(decisionName + (decisionSid == '' ? '' : '<br>[' + decisionSid + ']'));
                                            $('#dialogDecision').dialog('close');
                                        }
                                    }
                                });
                            }
                        }]
                    });
                }
            });
            return;
        }
        //并行活动
        if (activityType == 'concurrency') {
            $.ajax({
                type: 'GET',
                url: processEngineServer + '/api/design/concurrency',
                data: {designId: designId, diagramId: diagramId, activityId: activityId},
                success: function (data) {
                    if (!data.isSuccess) return;
                    $('#concurrencyName').val(data.data.concurrencyName);
                    $('#concurrencySid').val(data.data.concurrencySid);
                    $('#concurrencyEndWay').val(data.data.concurrencyEndWay);
                    $('#dialogConcurrency').dialog({
                        width: 500,
                        modal: true,
                        title: '配置并行活动',
                        buttons: [{
                            text: '确定',
                            click: function () {
                                var concurrencyName = $.trim($('#concurrencyName').val());
                                var concurrencySid = $.trim($('#concurrencySid').val());
                                var concurrencyEndWay = $('#concurrencyEndWay').val();
                                $.ajax({
                                    type: 'POST',
                                    url: processEngineServer + '/api/design/concurrency/modify',
                                    data: {
                                        designId: designId,
                                        diagramId: diagramId,
                                        activityId: activityId,
                                        concurrencyName: concurrencyName,
                                        concurrencySid: concurrencySid,
                                        concurrencyEndWay: concurrencyEndWay
                                    },
                                    success: function (data) {
                                        if (data.isSuccess) {
                                            el.children('.name').html(concurrencyName + (concurrencySid == '' ? '' : '<br>[' + concurrencySid + ']'));
                                            $('#dialogConcurrency').dialog('close');
                                        }
                                    }
                                });
                            }
                        }]
                    });
                }
            });
            return;
        }
        //重复活动
        if (activityType == 'replication') {
            $.ajax({
                type: 'GET',
                url: processEngineServer + '/api/design/replication',
                data: {designId: designId, diagramId: diagramId, activityId: activityId},
                success: function (data) {
                    if (!data.isSuccess) return;
                    $('#replicationName').val(data.data.replicationName);
                    $('#replicationSid').val(data.data.replicationSid);
                    $('#replicationEndWay').val(data.data.replicationEndWay);
                    $('#replicationStartExpression').val(data.data.replicationStartExpression);
                    $('#dialogReplication').dialog({
                        width: 500,
                        modal: true,
                        title: '配置重复活动',
                        buttons: [{
                            text: '确定',
                            click: function () {
                                var replicationName = $.trim($('#replicationName').val());
                                var replicationSid = $.trim($('#replicationSid').val());
                                var replicationEndWay = $('#replicationEndWay').val();
                                var replicationStartExpression = $.trim($('#replicationStartExpression').val())
                                $.ajax({
                                    type: 'POST',
                                    url: processEngineServer + '/api/design/replication/modify',
                                    data: {
                                        designId: designId,
                                        diagramId: diagramId,
                                        activityId: activityId,
                                        replicationName: replicationName,
                                        replicationSid: replicationSid,
                                        replicationEndWay: replicationEndWay,
                                        replicationStartExpression: replicationStartExpression
                                    },
                                    success: function (data) {
                                        if (data.isSuccess) {
                                            el.children('.name').html(replicationName + (replicationSid == '' ? '' : '<br>[' + replicationSid + ']'));
                                            $('#dialogReplication').dialog('close');
                                        }
                                    }
                                });
                            }
                        }]
                    });
                }
            });
            return;
        }
        //结束活动
        /*if (activityType == 'end') {
            $.ajax({
                type: 'GET',
                url: processEngineServer + '/api/design/end',
                data: {designId: designId, diagramId: diagramId, activityId: activityId},
                success: function (data) {
                    if (!data.isSuccess) return;
                    $('#endCcAll').prop('checked', data.data.endCcAll);
                    $('#endCcExpression').val(data.data.endCcExpression);
                    $('#dialogEnd').dialog({
                        width: 500,
                        modal: true,
                        title: '配置结束活动',
                        buttons: [{
                            text: '确定',
                            click: function () {
                                var endCcAll = $('#endCcAll').prop('checked');
                                var endCcExpression = $.trim($('#endCcExpression').val());
                                $.ajax({
                                    type: 'POST',
                                    url: processEngineServer + '/api/design/end/modify',
                                    data: {
                                        designId: designId,
                                        diagramId: diagramId,
                                        activityId: activityId,
                                        endCcAll: endCcAll,
                                        endCcExpression: endCcExpression
                                    },
                                    success: function (data) {
                                        if (data.isSuccess) {
                                            if (endCcAll || endCcExpression != '')
                                                el.children('.title').addClass('highlight');
                                            else
                                                el.children('.title').removeClass('highlight');
                                            $('#dialogEnd').dialog('close');
                                        }
                                    }
                                });
                            }
                        }]
                    });
                }
            });
            return;
        }*/
    });

    //-------------------------------------------------------------------------

    function loadDesign() {
        //加载设计图
        $.ajax({
            type: 'POST',
            url: processEngineServer + '/api/design/load',
            data: {designId: designId, diagramId: diagramId},
            success: function (data) {
                //console.log(data);
                if (!data.isSuccess) {  //加载流程设计图失败
                    $('body').fadeOut(200);
                    return;
                }

                var activities = data.data.activities;
                //添加元素
                $.each(activities, function (index, item) {
                    if (item.type == 'StartActivity')
                        appendElementStart(item.id, item.designInfo.left, item.designInfo.top);
                    else if (item.type == 'TaskActivity') {
                        appendElementTask(item.id, item.name + (item.sid == '' ? '' : '<br>[' + item.sid + ']'), item.designInfo.left, item.designInfo.top, item.designInfo.width, item.designInfo.height);
                    } else if (item.type == 'DecisionActivity')
                        appendElementDecision(item.id, item.name + (item.sid == '' ? '' : '<br>[' + item.sid + ']'), item.designInfo.left, item.designInfo.top, item.designInfo.width, item.designInfo.height);
                    else if (item.type == 'ConcurrencyActivity') {
                        appendElementConcurrency(item.id, item.name + (item.sid == '' ? '' : '<br>[' + item.sid + ']'), item.designInfo.left, item.designInfo.top, item.designInfo.width, item.designInfo.height);
                        $.each(item.subProcesses, function (index, subprocess) {
                            appendElementConcurrencySubprocess(item.id, subprocess.id, subprocess.name);
                        });
                    } else if (item.type == 'ReplicationActivity')
                        appendElementReplication(item.id, item.name + (item.sid == '' ? '' : '<br>[' + item.sid + ']'), item.designInfo.left, item.designInfo.top, item.designInfo.width, item.designInfo.height);
                    else if (item.type == 'EndActivity')
                        appendElementEnd(item.id, item.designInfo.left, item.designInfo.top/*, item.ccAll || item.ccExpression != ''*/);
                });
                //添加连线
                $.each(activities, function (index, item) {
                    if (item.type == 'StartActivity' && item.nextActivityId != '')
                        instance.connect({source: item.id, target: item.nextActivityId});
                    else if (item.type == 'TaskActivity') {
                        $.each(item.actions, function (index, action) {
                            var conn = instance.connect({source: item.id, target: action.nextActivityId});
                            conn.getOverlay('label').setLabel(action.name + (action.description ? '<br />' + action.description : ''));
                        });
                    } else if (item.type == 'DecisionActivity') {
                        $.each(item.conditions, function (index, condition) {
                            var conn = instance.connect({source: item.id, target: condition.nextActivityId});
                            //conn.getOverlay('label').setLabel((index + 1) + '.' + condition.name);
                            conn.getOverlay('label').setLabel(condition.name);
                        });
                    } else if (item.type == 'ConcurrencyActivity' && item.nextActivityId != '')
                        instance.connect({source: item.id, target: item.nextActivityId});
                    else if (item.type == 'ReplicationActivity' && item.nextActivityId != '')
                        instance.connect({source: item.id, target: item.nextActivityId});
                });
                connectionSubmit = true;    //设置连线提交标记，新连线提交到服务端
            }
        });
    }

    loadDesign();

});