var graph = new Graph(document.getElementById('graph'));
/**
 * 当前选择的mxCell
 **/
var selectionCell;
graph.resizeContainer = true;
graph.setEnabled(false);
graph.setTooltips(false);
graph.addMouseListener({
    mouseDown: function (sender, evt) {
        var state = evt.state;
        if (!state) {
            selectionCell = null;
            showProcessInstanceInfo($('#info'));
            return;
        }
        var cell = state.cell;
        selectionCell = cell;
        if (cell != null) { // cell may be null
            showActivityInfo(cell, $('#info'));
            initBusinessActionTab();
            initExeEfficiencyTab();
        } else {
            showProcessInstanceInfo($('#info'));
        }
    },
    mouseMove: function (sender, evt) {
    },
    mouseUp: function (sender, evt) {
    }
});

graph.dblClick = function (evt, cell) {
    var mxe = new mxEventObject(mxEvent.DOUBLE_CLICK, 'event', evt, 'cell', cell);
    this.fireEvent(mxe);
    if (this.isEnabled() && !mxEvent.isConsumed(evt) && !mxe.isConsumed()) {
        mxe.consume();
    }
}

function initInfoTabs() {
    $('#infoTabs').tab({
        onClick: function ($clicked) {
            var id = $clicked.attr('id');
            switch (id) {
                case 'businessActionTab':
                    initBusinessActionTab();
                    break;
                case 'exeEfficiencyTab':
                    initExeEfficiencyTab();
                    break;
                default:
                    break;
            }
        }
    });
}

graph.addListener(mxEvent.DOUBLE_CLICK, function (sender, evt) {
    var cell = evt.getProperty('cell');
    // do something with the cell and consume the
    // event to prevent in-place editing from start
    if (cell) {
        var formUrl = cell.getAttribute('formUrl');
        var activityCode = cell.getAttribute('code');
        var label = cell.getAttribute('label');
        if (formUrl) {
            var tabUrl = 'bpm/procInst/forwardForm.do?activityCode=' + activityCode + '&id=' + getProcInstId();
            UICtrl.addTabItem({
                tabid: activityCode + '_formUrl',
                text: label,
                url: tabUrl
            });
        }
    }
});

/**
 * 展示流程节点信息
 */
function showActivityInfo(cell, container) {
    container.empty();
    var shape;
    if (cell.edge) {
        shape = 'bpmn.connector';
    } else {
        var style = _.map(cell.getStyle().split(';'), function (s) {
            return s.split('=');
        });
        style = _.object(style);
        shape = style.shape;
    }
    var label = cell.getAttribute('label');
    label = $.i18nProp(shape) + '<span style="color: red;">[' + label + ']</span>';
    $('#layout').layout('setCenterTitle', label);

    $('<div id="flexField"></div>')
        .appendTo(container)
        .flexField({
            bizCode: shape,
            needTitle: false,
            onInit: function () {
                initFlexField(cell, container);
            }
        });
    if (shape == 'bpmn.task') {
        var operationGuide = $('<div></div>').appendTo(container);
        createFileList(operationGuide, 'bizTaskOperationGuide', cell.id, $.i18nProp('operationGuide'));
    }
}

function initFlexField(cell, container) {
    var attrNames = cell.getValue().getAttributeNames();
    for (var i = 0; i < attrNames.length; i++) {
        var attrName = attrNames[i];
        if (attrName.endsWith("TextView")) {
            continue;
        }
        var attrVal = cell.getAttribute(attrName);
        var elem = container.find('[fieldname="' + attrName + '"]');
        elem.val(attrVal)
        if (elem.hasClass('ui-combox-element')) {
            var textId = elem.attr('name') + '_text';
            var textView = cell.getAttribute(attrName + 'TextView') || attrVal;
            $('#' + textId).val(textView);
        }
    }
}

/**
 * 展示流程信息
 */
function showProcessInstanceInfo(container) {
    $('#layout').layout('setCenterTitle', '流程信息');
    $('#businessAction').empty();
    $('#exeEfficiency').empty();
    container.empty();
    $('<div id="flexField"></div>')
        .appendTo(container)
        .flexField({
            bizCode: 'process.bpmn',
            needTitle: false,
            onInit: function () {
                var cell = graph.getModel().getRoot();
                initFlexField(cell, container);
            }
        });
    var operationGuide = $('<div></div>').appendTo(container);
    createFileList(operationGuide, 'operationGuide', $('#procdefId').val(), $.i18nProp('operationGuide'));
}

/**
 * 初始化业务动作面板。
 */
function initBusinessActionTab() {
    var cell = selectionCell;
    var container = $('#businessAction');
    container.empty();
    if (!cell) {
        return;
    }
    var code = cell.getAttribute('code');
    if (!code) {
        return;
    }
    Public.ajax(web_app.name + '/bpm/procdef/queryServiceByActivityCode.ajax', {
            procdefId: $('#procdefId').val(),
            activityCode: code
        },
        function (service) {
            var form = $('<form  class="hg-form"></form>');
            container.append(form);
            container.append('<div id="inParamGrid"></div>');
            // 初始化入参列表
            var inParamGrid = UICtrl.grid('#inParamGrid', {
                columns: [
                    {display: "服务参数", name: "paramCode", width: 150, minWidth: 60, type: "string", align: "left"},
                    {
                        display: "流程变量",
                        name: "variableCode",
                        width: 150,
                        minWidth: 60,
                        type: "string",
                        align: "left",
                    },
                ],
                dataAction: 'server',
                url: web_app.name + '/bpm/serviceParam/queryInParamMapping.ajax',
                parms: {
                    procdefId: $('#procdefId').val(),
                    activityCode: code,
                    serviceId: service ? service.id : ''
                },
                width: '99.8%',
                height: '300px',
                heightDiff: -13,
                checkbox: true,
                fixedCellHeight: true,
                selectRowButtonOnly: true,
                usePager: false,
                title: '入参'
            });
            // 初始化出参列表
            container.append('<div id="outParamGrid"></div>');
            var outParamGrid = UICtrl.grid('#outParamGrid', {
                columns: [
                    {display: "服务参数", name: "paramCode", width: 150, minWidth: 60, type: "string", align: "left"},
                    {
                        display: "流程变量",
                        name: "variableCode",
                        width: 150,
                        minWidth: 60,
                        type: "string",
                        align: "left",
                    },
                ],
                dataAction: 'server',
                url: web_app.name + '/bpm/serviceParam/queryOutParamMapping.ajax',
                parms: {
                    kindId: 1,
                    procdefId: $('#procdefId').val(),
                    activityCode: code,
                    serviceId: service ? service.id : ''
                },
                width: '99.8%',
                height: '300px',
                heightDiff: -13,
                checkbox: true,
                fixedCellHeight: true,
                selectRowButtonOnly: true,
                usePager: false,
                title: '出参',
            });

            // 服务选择框
            var serviceFieldHtml = [];
            serviceFieldHtml.push('<div class="hg-form-row">');
            serviceFieldHtml.push('<div class="col-xs-4 col-sm-3"><label class="hg-form-label" title="服务名称">&nbsp;服务名称:</label></div>');
            serviceFieldHtml.push('<div class="col-xs-8 col-white-bg col-sm-9">');
            serviceFieldHtml.push('<div class="form-control">' + (service ? service.name : '') + '</div></div>');
            serviceFieldHtml.push('</div>');
            serviceFieldHtml.push('<div class="hg-form-row">');
            serviceFieldHtml.push('<div class="col-xs-4 col-sm-3"><label class="hg-form-label" title="服务编码">&nbsp;服务编码:</label></div>');
            serviceFieldHtml.push('<div class="col-xs-8 col-white-bg col-sm-9">');
            serviceFieldHtml.push('<div class="form-control">' + (service ? service.code : '') + '<div/></div>');
            serviceFieldHtml.push('</div>');
            var serviceField = $(serviceFieldHtml.join(''));
            form.append(serviceField);

            var reloadGrid = function () {
                var params = {
                    kindId: 0,
                    procdefId: $('#procdefId').val(),
                    activityCode: code,
                    serviceId: $('#serviceId').val()
                };
                UICtrl.gridSearch(inParamGrid, params);
                var params2 = {
                    kindId: 1,
                    procdefId: $('#procdefId').val(),
                    activityCode: code,
                    serviceId: $('#serviceId').val()
                };
                UICtrl.gridSearch(outParamGrid, params2);
            }
        });
}

function getProcInstId() {
    return $('#id').val();
}

function getServiceCode() {
    var cell = selectionCell;
    var container = $('#businessAction');
    container.empty();
    if (!cell) {
        return;
    }
    var code = cell.getAttribute('code');
    return code;
}

/**
 * 初始化执行情况面板
 */
function initExeEfficiencyTab() {
    var container = $('#exeEfficiency');
    container.empty();
    var serviceCode = getServiceCode();
    if (!serviceCode) {
        return;
    }
    Public.ajax(basePath + '/bpm/bizTask/queryByActivityCode.ajax', {
        procInstId: getProcInstId(),
        serviceCode: getServiceCode()
    }, function (task) {
        if (!task) {
            return;
        }
        var html = ['<div  class="hg-form">'];
        html.push('<div class="hg-form-row">');
        html.push('<div class="col-xs-5 col-sm-4"><label class="hg-form-label" title="执行状态">&nbsp;执行状态:</label></div>');
        html.push('<div class="col-xs-7 col-white-bg col-sm-8">');
        html.push('<div class="form-control">' + (task.statusTextView || '') + '<div/></div></div>');
        html.push('</div>');
        html.push('<div class="hg-form-row">');
        html.push('<div class="col-xs-5 col-sm-4"><label class="hg-form-label" title="开始时间">&nbsp;开始时间:</label></div>');
        html.push('<div class="col-xs-7 col-white-bg col-sm-8">');
        html.push('<div class="form-control">' + (task.startDate || '') + '<div/></div></div>');
        html.push('<div class="hg-form-row">');
        html.push('<div class="col-xs-5 col-sm-4"><label class="hg-form-label" title="开始处理时间">&nbsp;开始处理时间:</label></div>');
        html.push('<div class="col-xs-7 col-white-bg col-sm-8">');
        html.push('<div class="form-control">' + (task.takeDate || '') + '<div/></div></div>');
        html.push('<div class="hg-form-row">');
        html.push('<div class="col-xs-5 col-sm-4"><label class="hg-form-label" title="结束时间">&nbsp;结束时间:</label></div>');
        html.push('<div class="col-xs-7 col-white-bg col-sm-8">');
        html.push('<div class="form-control">' + (task.endDate || '') + '<div/></div></div>');
        html.push('<div class="hg-form-row">');
        html.push('<div class="col-xs-5 col-sm-4"><label class="hg-form-label" title="已耗时">&nbsp;已耗时:</label></div>');
        html.push('<div class="col-xs-7 col-white-bg col-sm-8">');
        html.push('<div class="form-control">' + formatDuration(task.duration) + ' <div/></div></div>');
        var timeLimit = formatTimeLimit(task);
        if (timeLimit) {
            html.push('<div class="hg-form-row">');
            html.push('<div class="col-xs-5 col-sm-4"><label class="hg-form-label" title="时间限制">&nbsp;时间限制:</label></div>');
            html.push('<div class="col-xs-7 col-white-bg col-sm-8">');
            html.push('<div class="form-control">' + timeLimit + '</div></div></div>');
        }
        html.push('</div></div>');
        container.html(html.join(''));
    });
}

/**
 * 格式化业务节点耗时。
 * @param duration 业务节点耗时（毫秒）
 * @returns {string}
 */
function formatDuration(duration) {
    if (!duration) {
        return '';
    }
    if (duration < 1000) {
        return duration + '毫秒';
    }
    var seconds = duration / 1000.0
    if (seconds < 60) {
        return seconds.toFixed(2) + '秒';
    }
    var minutes = duration / 60000.0;
    if (minutes < 60) {
        return minutes.toFixed(2) + '分钟';
    }
    var hours = duration / 3600000.0;
    return hours.toFixed(2) + '小时';
}

/**
 *
 * @param duration 业务节点耗时（毫秒）
 */
function formatTimeLimit(task) {
    var cell = selectionCell;
    var timeLimit = cell.getAttribute('timeLimit');
    if (!timeLimit) {
        return;
    }
    return (timeLimit * 1000) >= task.duration
        ? timeLimit
        : (timeLimit + '秒(' + task.limitDate + ') <span style="color: red;">超时</span>');
}

function showGraph() {
    var data = $('#xml').val();
    var xmlDoc = mxUtils.parseXml(data);
    var codec = new mxCodec(xmlDoc);
    codec.decode(xmlDoc.documentElement, graph.getModel());
};

$(function () {
    showGraph();
    initInfoTabs();
    showProcessInstanceInfo($('#info'));
})