var taskListenerGrid, taskListenerFieldGrid;
$(function () {
    initListenerGrid();
});

function initListenerGrid() {
    var toolbarOptions = UICtrl.getDefaultToolbarOptions({
        addHandler: addListenerHandler,
        updateHandler: updateListenerHandler,
        deleteHandler: deleteListenerHandler,
    });
    var taskListeners = parent.getTaskListeners();
    console.log(taskListeners);
    taskListenerGrid = UICtrl.grid("#task-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: taskListeners},
        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,
    });
    taskListenerFieldGrid = 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/showTaskListenerDetails.load?shape=' + parent.getSelectionShape(),
        title: '添加任务监听器',
        width: 500,
        height: 430,
        init: function (div) {
            initListenerDialog(div);
        },
        okVal: '确定',
        ok: function () {
            saveTaskListener(this);
        }
    });
}


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

function initListenerDialog(div) {
    $('#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();
            }
            if (val.text == 'delegateExpression') {
                $('#implementation_click button')
                    .removeProp('disabled')
                    .removeClass('disabled');
            } else {
                $('#implementation_click button')
                    .prop('disabled', 'disabled')
                    .addClass('disabled');
            }
        }
    });
    var __id = $('#submitForm [name="__id"]').val(), fieldExtensions = [];
    if (__id) {
        var rows = DataUtil.getGridData({gridManager: taskListenerGrid, 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;
            }
        }
    }
    $('#implementation_click button', div).click(function () {
        $('#implementation-selector-container').remove();
        $('<div id="implementation-selector-container"><input id="implementationSelector" name="implementationSelector" /></div>').insertBefore('#implementation_click');
        $('#implementationSelector').searchbox({
            type: 'bpm',
            name: 'taskListener',
            getParam: function () {
                return {};
            },
            onChange: function (data) {
                $('#implementation', div).val(data.text ? ('#{' + data.text + '}') : data.text);
            }
        });
        $('#implementation-selector-container').css({
            height: 1,
            width: 1,
        })
        $('#implementation-selector-container .input-group input').css({
            width: 0.1,
            height: 0.1,
            padding: 0,
            margin: 0
        });
        $('#implementation-selector-container .input-group-btn').remove();
        $('#implementation-selector-container #implementationSelector_text').trigger('click');
    });
    initFieldGrid(fieldExtensions);
}

function saveTaskListener(dialog) {
    // 获取 listener 信息
    var listener = $('#submitForm').formToJSON({encode: false});
    // 获取 field 信息
    var fieldExtensions = DataUtil.getGridData({gridManager: taskListenerFieldGrid, 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 = taskListenerGrid.getSelected();
            if (selected.__id == __id) {
                taskListenerGrid.updateRow(selected, listener);
                dialog.close();
            }
        } else {
            taskListenerGrid.addRows(listener);
            dialog.close();
        }
    }
}


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

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

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

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