var lastSelectedId = 0, gridManager, selectFunctionDialog;
$(function () {
    UICtrl.initDefaultLayout();
    loadProcdefKindTree();
    initializeGrid();
});

function loadProcdefKindTree() {
    $('#maintree').commonTree({
        loadTreesAction: '/bpm/procdef/queryProcdefKind.ajax',
        appendAction: '/bpm/procdef/addProcdefKind.ajax',
        deleteAction: '/bpm/procdef/deleteProcdefKind.ajax',
        updateAction: '/bpm/procdef/updateProcdefKind.ajax',
        loadNodeAction: '/bpm/procdef/loadProcdefKind.load',
        updateSequenceAction: '/bpm/procdef/updateSequence.ajax',
        idFieldName: 'id',
        parentIDFieldName: "parentId",
        textFieldName: "name",
        onClick: function (data) {
            $("#layout").layout("setCenterTitle", "<span class='tomato-color'>[" + data.name + "]</span>流程定义列表");
            lastSelectedId = data.id;
            var params = $("#queryMainForm").formToJSON();
            params.parentId = lastSelectedId;
            UICtrl.gridSearch(gridManager, params);
        },
        isLeaf: function (data) {
            return data.kindId == 0;
        },
        IsShowMenu: true
    });
}


function initializeGrid() {
    var toolbarOptions = UICtrl.getDefaultToolbarOptions({
        addHandler: showInsertChildDialog,
        updateHandler: showUpdateDialog,
        moveHandler: moveHandler,
        deleteHandler: deleteHandler,
        procVarHandler: {id: 'procVarHandler', text: '流程变量', click: procVarHandler},
        showProcessChart: {id: 'showProcessChart', text: '流程图', click: showProcessChartHandler},
        deploy: {id: 'deploy', text: '发布', img: 'fa-wifi', click: deployHandler},
        showProcessDeploy: {id: 'showProcessDeploy', text: '发布历史', click: showProcessDeploymentHandler},
        enable: {id: 'enable', text: '启用', click: enableHandler},
        disable: {id: 'disable', text: '禁用', click: disableHandler},
        exportImage: {id: 'exportImage', text: '导出流程图片', click: exportImage},
        saveSortIDHandler: updateSequence,
    });

    gridManager = UICtrl.grid('#maingrid', {
        columns: [
            {display: "编码", name: "code", width: 100, minWidth: 60, type: "string", align: "left"},
            {display: "名称", name: "name", width: 100, minWidth: 60, type: "string", align: "left"},
            {display: "图类型", name: "chartKindIdTextView", width: 100, minWidth: 60, type: "string", align: "left"},
            {display: "路径", name: "fullName", width: 200, minWidth: 60, type: "string", align: "left"},
            {
                display: "排序号", name: "sequence", width: 60, minWidth: 60, type: "int", align: "left",
                render: function (item) {
                    item.id = item.id; //只为了能够更新sequence
                    return UICtrl.sequenceRender(item);
                }
            },
            {
                display: "状态", name: "status", width: 60, minWidth: 60, type: "string", align: "left",
                render: function (item) {
                    return renderBooleanKind(item.status);
                }
            }
        ],
        dataAction: 'server',
        url: web_app.name + '/bpm/procdef/sliceQueryProcessDefinitions.ajax',
        parms: {},
        sortName: "sequence",
        SortOrder: "asc",
        toolbar: toolbarOptions,
        width: '99.8%',
        height: '100%',
        heightDiff: -13,
        checkbox: true,
        fixedCellHeight: true,
        selectRowButtonOnly: true,
        onDblClickRow: function (data, rowindex, rowobj) {
            doShowUpdateDialog(data.id);
        }
    });
    UICtrl.setSearchAreaToggle(gridManager);
}

function renderBooleanKind(value) {
    return "<div class='" + (value ? "status-enable" : "status-disable") + "'/>";
}

function showInsertChildDialog() {
    var node = $('#maintree').commonTree('getSelected');
    if (!node) {
        Public.errorTip('请选择左侧分类。');
        return;
    }
    UICtrl.showAjaxDialog({
        title: "添加流程定义",
        param: {parentId: node.id},
        width: 600,
        url: web_app.name + '/bpm/procdef/showAddProcessDefinition.load',
        ok: doSaveProcessDefinition,
        init: initChartKindIdSelector
    });
}

function procVarHandler() {
    var row = DataUtil.getSelectedRow(gridManager);
    if (!row) {
        return;
    }
    if (row.chartKindId != 'process.bpmn2') {
        Public.tip('只有BPMN2流程图支持该操作');
        return;
    }
    UICtrl.showFrameDialog({
        title: '流程变量[<span style="color: red;">' + row.name + ':' + row.code + '</span>]',
        url: web_app.name + '/bpm/procVar/forwardProcVarList.do?procdefId=' + row.id,
        width: 700,
        height: 500,
        ok: function () {
            this.close();
        }
    });
}

function initChartKindIdSelector() {
    if ($('#id').val()) {
        UICtrl.disable('#chartKindId');
    }
}

function doSaveProcessDefinition() {
    var _self = this;
    var id = $("#id").val();
    $('#submitForm').ajaxSubmit({
        url: web_app.name + (id ? '/bpm/procdef/updateProcessDefinition.ajax' : '/bpm/procdef/addProcessDefinition.ajax'),
        success: function () {
            reloadGrid();
            _self.close();
        }
    });
}

//弹出修改对话框
function showUpdateDialog() {
    var id = DataUtil.getUpdateRowId(gridManager);
    if (!id) {
        Public.errorTip("请选择需要修改的数据。");
        return;
    }
    doShowUpdateDialog(id);
}

//进行修改操作
function doShowUpdateDialog(id) {
    UICtrl.showAjaxDialog({
        title: "修改流程定义",
        url: web_app.name + '/bpm/procdef/showProcessDefinition.load',
        param: {id: id},
        width: 600,
        ok: doSaveProcessDefinition,
        close: reloadGrid,
        init: initChartKindIdSelector
    });
}

function moveHandler() {
    ids = DataUtil.getSelectedIds({
        gridManager: gridManager,
        idFieldName: "id"
    });
    if (!ids) {
        return;
    }

    if (!selectFunctionDialog) {
        selectFunctionDialog = UICtrl.showDialog({
            title: "移动到...",
            width: 350,
            content: '<div style="overflow-x: hidden; overflow-y: auto; width: 340px;height:250px;"><ul id="movetree"></ul></div>',
            init: function () {
                $('#movetree').commonTree({
                    loadTreesAction: "/bpm/procdef/queryProcdefKind.ajax",
                    idFieldName: 'id',
                    IsShowMenu: false
                });
            },
            ok: function () {
                doMoveProcessDefinition(ids);
            },
            close: function () {
                this.hide();
                return false;
            }
        });
    } else {
        $('#movetree').commonTree('refresh');
        selectFunctionDialog.show().zindex();
    }
}

function doMoveProcessDefinition(ids) {
    var moveToNode = $('#movetree').commonTree('getSelected');
    var moveToId = moveToNode.id;
    if (!moveToId) {
        Public.tip('请选择移动到的节点。');
        return false;
    }

    var params = {};
    params.parentId = moveToId;
    params.ids = $.toJSON(ids);
    Public.ajax(web_app.name + "/bpm/procdef/moveProcessDefinition.ajax", params, function (data) {
        reloadGrid();
        selectFunctionDialog.hide();
    });
}

/**
 * 发布流程定义
 */
function deployHandler() {
    var row = DataUtil.getSelectedRow(gridManager);
    if (!row) {
        return;
    }
    if (row.chartKindId != 'process.bpmn2') {
        Public.tip('只有BPMN2流程图支持该操作');
        return;
    }
    UICtrl.confirm('发布会覆盖已发布的版本，您确定要发布该流程定义吗？',
        function () {
            Public.ajax(web_app.name + '/bpm/processDeployment/deploy.ajax',
                {procdefId: row.id},
                function () {
                    reloadGrid();
                });
        });
}

/**
 * 删除流程定义
 */
function deleteHandler() {
    var ids = DataUtil.getSelectedIds({
        gridManager: gridManager,
        idFieldName: "id"
    });
    if (!ids) {
        return;
    }
    UICtrl.confirm('您确定要删除选择的流程定义吗？',
        function () {
            Public.ajax(web_app.name + '/bpm/procdef/deleteProcessDefinition.ajax',
                {ids: $.toJSON(ids)},
                function (data) {
                    reloadGrid();
                });
        });
}

function showProcessChartHandler() {
    var row = DataUtil.getSelectedRow(gridManager);
    if (!row) {
        return;
    }
    UICtrl.addTabItem({
        tabid: 'graphEditor' + row.id,
        text: '绘制流程图-' + row.name + '[' + row.code + ']',
        url: web_app.name + '/bpm/graph/forwardEditor.do?procdefId=' + row.id
    });
}

function showProcessDeploymentHandler() {
    var row = DataUtil.getSelectedRow(gridManager);
    if (!row) {
        return;
    }
    if (row.chartKindId != 'process.bpmn2') {
        Public.tip('只有BPMN2流程图支持该操作');
        return;
    }
    UICtrl.showFrameDialog({
        title: '流程定义发布信息',
        url: web_app.name + '/bpm/processDeployment/showProcessDeployment.do?procdefId=' + row.id,
        width: 860,
        height: 500,
        ok: function () {
            this.close();
        }
    });
}

/**
 * 启用流程定义
 */
function enableHandler() {
    var ids = DataUtil.getSelectedIds({
        gridManager: gridManager,
        idFieldName: "id"
    });
    if (!ids) {
        return;
    }
    Public.ajax(web_app.name + '/bpm/procdef/enableProcessDefinition.ajax',
        {ids: $.toJSON(ids)},
        function (data) {
            reloadGrid();
        });
}

function disableHandler() {
    var ids = DataUtil.getSelectedIds({
        gridManager: gridManager,
        idFieldName: "id"
    });
    if (!ids) {
        return;
    }
    Public.ajax(web_app.name + '/bpm/procdef/disableProcessDefinition.ajax',
        {ids: $.toJSON(ids)},
        function (data) {
            reloadGrid();
        });
}


function exportImage() {
    var row = DataUtil.getSelectedRow(gridManager);
    if (!row) {
        return;
    }
    Public.openPostWindow('bpm/procdef/exportImage.ajax', {id: row.id});
}

function updateSequence() {
    var action = "/bpm/procdef/updateSequence.ajax";
    DataUtil.updateSequence({
        action: action,
        idFieldName: "id",
        gridManager: gridManager,
        onSuccess: reloadGrid
    });
}

// 查询
function query(obj) {
    var param = $(obj).formToJSON();
    UICtrl.gridSearch(gridManager, param);
}

//重置表单
function resetForm(obj) {
    $(obj).formClean();
}

function reloadGrid() {
    $("#maintree").commonTree('refresh', lastSelectedId);
    var params = $("#queryMainForm").formToJSON();
    UICtrl.gridSearch(gridManager, params);
}
