var listenerGrid, fieldGrid;
$(function () {
    initListenerGrid();
});

function initListenerGrid() {
    var toolbarOptions = UICtrl.getDefaultToolbarOptions({
        addHandler: addListenerHandler,
        updateHandler: updateListenerHandler,
        deleteHandler: deleteListenerHandler,
    });
    var listeners = parent.getProcessExecutionListeners();
    console.log(listeners);
    listenerGrid = UICtrl.grid("#listener-grid", {
        columns: [
            {
                display: '事件名',
                name: 'event',
                width: 60,
                minWidth: 60,
                type: "string",
                align: "center",
            },
            {display: '类型', name: 'implementationType', width: 100, minWidth: 60, type: "string", align: "left"},
            {display: '监听器实现', name: 'implementation', width: 400, minWidth: 60, type: "string", align: "left"},
        ],
        dataAction: 'local',
        data: {Rows: listeners},
        usePager: false,
        toolbar: toolbarOptions,
        width: '100%',
        height: '500',
        heightDiff: -13,
        checkbox: true,
        fixedCellHeight: true,
        selectRowButtonOnly: true,
        onDblClickRow: function (data, rowindex, rowobj) {
        }
    });
}

function initFieldGrid(rows) {
    var toolbarOptions = UICtrl.getDefaultToolbarOptions({
        addHandler: addFieldHandler,
        deleteHandler: deleteFieldHandler,
    });
    fieldGrid = UICtrl.grid("#field-grid", {
        columns: [
            {
                display: '字段名',
                name: 'fieldName',
                width: 60,
                minWidth: 60,
                type: "string",
                editor: {type: 'text', required: true}
            },
            {
                display: 'String value',
                name: 'stringValue',
                width: 150,
                minWidth: 60,
                type: "string",
                editor: {type: 'text'}
            },
            {
                display: 'Expression',
                name: 'expression',
                width: 150,
                minWidth: 60,
                type: "string",
                editor: {type: 'text'}
            },
        ],
        dataAction: 'local',
        data: {Rows: rows},
        usePager: false,
        toolbar: toolbarOptions,
        width: '100%',
        height: '240',
        heightDiff: -13,
        checkbox: true,
        fixedCellHeight: true,
        selectRowButtonOnly: true,
        enabledEdit: true,
    });
}


function addListenerHandler() {
    UICtrl.showAjaxDialog({
        url: web_app.name + '/procDefinition/showListenerDetails.load?shape=' + parent.getSelectionShape(),
        title: '添加执行监听器',
        width: 500,
        height: 430,
        init: function () {
            initListenerDialog();
        },
        okVal: '确定',
        ok: function () {
            saveListener(this);
        }
    });
}


function updateListenerHandler() {
    var row = DataUtil.getSelectedRow(listenerGrid);
    if (!row) {
        return;
    }
    UICtrl.showAjaxDialog({
        url: web_app.name + '/procDefinition/showListenerDetails.load',
        param: {
            __id: row.__id,
            shape: parent.getSelectionShape()
        },
        title: '修改执行监听器',
        width: 500,
        height: 430,
        init: function () {
            initListenerDialog();
        },
        okVal: '确定',
        ok: function () {
            saveListener(this);
        }
    });
}

function initListenerDialog() {
    $('#submitForm [name="implementation"]').parent().parent().hide();
    $('#submitForm [name="implementationType"]').combox({
        'onChange': function (val) {
            if (val.text) {
                $('#submitForm [name="implementation"]').parent().parent().show()
                    .find('label').text(val.text + ' :');
            } else {
                $('#submitForm [name="implementation"]').parent().parent().hide();
            }
        }
    });
    var __id = $('#submitForm [name="__id"]').val(), fieldExtensions = [];
    if (__id) {
        var rows = DataUtil.getGridData({gridManager: listenerGrid, isAllData: true});
        for (var i = 0; i < rows.length; i++) {
            var row = rows[i];
            if (row.__id == __id) {
                fieldExtensions = row.fieldExtensions;
                $('#submitForm [name="event"]').combox('setValue', row.event);
                $('#submitForm [name="implementationType"]').combox('setValue', row.implementationType);
                var typeText = $('#submitForm [name="implementationType"]').combox('getText');
                $('#submitForm [name="implementation"]').val(row.implementation);
                $('#submitForm [name="implementation"]').parent().parent().show()
                    .find('label').text(typeText + ' :');
                break;
            }
        }
    }
    initFieldGrid(fieldExtensions);
}

function saveListener(dialog) {
    // 获取 listener 信息
    var listener = $('#submitForm').formToJSON({encode: false});
    // 获取 field 信息
    var fieldExtensions = DataUtil.getGridData({gridManager: fieldGrid, isAllData: true});
    for (var i = 0; i < fieldExtensions.length; i++) {
        delete fieldExtensions[i].__id;
    }
    listener.fieldExtensions = fieldExtensions;
    if (listener) {
        var __id = $('#submitForm [name="__id"]').val();
        if (__id) {
            var selected = listenerGrid.getSelected();
            if (selected.__id == __id) {
                listenerGrid.updateRow(selected, listener);
                dialog.close();
            }
        } else {
            listenerGrid.addRows(listener);
            dialog.close();
        }
    }
}


function deleteListenerHandler() {
    DataUtil.delSelectedRows({gridManager: listenerGrid});
}

function addFieldHandler() {
    fieldGrid.addRows({});
}

function deleteFieldHandler() {
    DataUtil.delSelectedRows({gridManager: fieldGrid});
}

/**
 * 获取全部执行监听器。
 */
function getExecutionListeners() {
    var listeners = DataUtil.getGridData({
        gridManager: listenerGrid,
        isAllData: true
    });
    for (var i = 0; i < listeners.length; i++) {
        delete listeners[i].__id;
    }
    return listeners;
}