/**
 * 实例监控
 * @author pengys
 */
(function (factory) {
    if (typeof define === 'function' && define.amd) {
        define(['jquery', 'horizonFlowtree', 'horizonSelectuser',
            'horizonTable', 'horizonJqueryui', 'horizonFlowchart', 'gritter'], factory);
    }else {
        factory(jQuery);
    }
}(function($) {
    "use strict";
    var $dialog = $('#instance-dialog');
    var _height = {
        outerHeight: function() {
            var _height = horizon.tools.getPageContentHeight(),
                $pageHeader = $('.page-header');
            if($pageHeader.css('display') != 'none') {
                _height -= $pageHeader.outerHeight(true);
            }
            return _height;
        },
        treeHeight: function() {
            var outerHeight = this.outerHeight();
            var $container = $('.modal-dialog');
            return outerHeight - parseInt($container.css('borderTopWidth'))*2
                - parseInt($container.find('.modal-body').css('paddingTop'))*2
                - $container.find('.widget-header').outerHeight(true);
        }
    };
    var flowtree = {
        flowId: null,
        groupId: null,
        init: function() {
            $('#flow-tree').flowtree({
                data: {
                    type: 'flow'
                },
                defaultNode: [ {
                    id: 'allList',
                    type: 'item',
                    text: horizon.lang['base']['allflow'],
                    additionalParameters: {
                        'item-selected': true
                    }
                } ],
                defaultNodePosition: 'top',
                selected: flowtree.selNode,
                deselected: flowtree.deselected,
                opened: flowtree.selGroup,
                closed: flowtree.selGroup
            });
        },
        selNode: function() {
            if (arguments[1].target.id == 'allList') {
                flowtree.groupId = null;
                flowtree.flowId = null;
            } else {
                flowtree.flowId = arguments[1].target.flowId;
                flowtree.groupId = arguments[1].group;
            }
            table.getGroupData();
        },
        selGroup: function() {
            $(arguments[0].target).find('.tree-item.tree-selected').removeClass('tree-selected');
            flowtree.flowId = null;
            flowtree.groupId = arguments[1].group;
            table.getGroupData();
        },
        deselected: function() {
            $(arguments[1].el).addClass('tree-selected');
        }
    };
    var table = {
        //初始化视图数据
        settings: {
            title:horizon.lang['instance-monitor']['tableTitle'],
            height: _height.outerHeight,
            checkbox: 0,
            columns: [
                {
                    dataProp : 'id'
                },
                {
                    name : 'title',
                    title : horizon.lang['instance-monitor']['columnsTitle'],
                    width : '200px',
                    searchable : true,
                    orderable: false,
                    fnClick :function(nTd, nTdData, rowData, iRow, i) {
                        table.openWorkFlowInfo(rowData);
                    }
                },
                {
                    name : 'status',
                    title :  horizon.lang['instance-monitor']['columnsState'],
                    width : '200px',
                    orderable: false,
                    columnClass :'center'
                },
                {
                    name : 'actionUser',
                    title :  horizon.lang['instance-monitor']['columnsLastOperator'],
                    width : '200px',
                    orderable: false,
                    columnClass :'center'
                },
                {
                    name : 'date',
                    title :  horizon.lang['instance-monitor']['columnsLastOperatorTime'],
                    width : '200px',
                    columnClass :'center'
                }
            ],
            buttons: [
                {
                    id: 'delWork',
                    text: horizon.lang['base']['delete'],
                    icon: 'glyphicon glyphicon-trash red',
                    fnClick: function() {
                        var ids = table.mytable.checkRowKeyArray;
                        if(!ids.length) {
                            horizon.notice.error(horizon.lang['instance-monitor']['selectDelete']);
                            return;
                        }else {
                            $dialog.dialog({
                                closeText:horizon.lang['base']['cancel'],
                                title:horizon.lang['message']['title'],
                                dialogText:horizon.lang['instance-monitor']['confirmRemoveMemory'],
                                dialogTextType:'alert-danger',
                                buttons: [
                                    {
                                        html: horizon.lang['base']['ok'],
                                        "class" : "btn btn-primary btn-xs",
                                        click: function() {
                                            operate.removeMemInstance(ids.join(';'));
                                            $( this ).dialog( "close" );
                                        }
                                    }
                                ]
                            });
                        }
                    }
                },
                {
                    id: 'delIdelWork',
                    text: horizon.lang['instance-monitor']['deleteAllIdleMemory'],
                    icon: 'glyphicon glyphicon-trash red',
                    fnClick: function() {
                        $dialog.dialog({
                            closeText:horizon.lang['base']['cancel'],
                            title:horizon.lang['message']['title'],
                            dialogText:horizon.lang['instance-monitor']['confirmRemoveMemory'],
                            dialogTextType:'alert-danger',
                            buttons: [
                                {
                                    html: horizon.lang['base']['ok'],
                                    "class" : "btn btn-primary btn-xs",
                                    click: function() {
                                        operate.removeAllIdleMemInstance();
                                        $( this ).dialog( "close" );
                                    }
                                }
                            ]
                        });
                    }
                }
            ],
            pluginSettings: {
                "order":[[4,'desc']]
            }
        },
        init: function() {
            table.mytable = $('#myDatatable').horizonTable({
                settings: table.settings,
                ajaxDataSource: horizon.tools.formatUrl('/monitor/memory/list'),
                ajaxDataParam: {
                    flowStatus: function() {
                        return flowtree.flowStatus;
                    },
                    group: function() {
                        return flowtree.group;
                    }
                }
            });
        },
        getGroupData:function() {
            //清空简单搜索项
            table.mytable.pluginTable._fnFilterComplete(table.mytable.pluginTable.fnSettings(), {
                "sSearch": ''
            } );

            var aoServerParams = table.mytable.pluginTable.fnSettings().aoServerParams;
            aoServerParams.push({
                "fn": function(aoData) {
                    aoData.push({
                        'name': 'flowId',
                        'value': flowtree.flowId
                    });
                    aoData.push({
                        'name': 'type',
                        'value': flowtree.groupId
                    });
                }
            });
            table.mytable.pluginTable.fnDraw(false);
        },
        openWorkFlowInfo: function() {
            var workid = arguments[0].id;
            var url = horizon.paths.flowpath + '?workId=' + workid;
            horizon.open({url:url});
        }
    };
    var operate = {
        //删除
        removeMemInstance:function(ids) {
            table.mytable.showProcessing();
            $.ajax({
                url : horizon.tools.formatUrl('/monitor/memory/remove'),
                data : {ids: ids},
                dataType:'json',
                cache : false,
                error : function(){
                    table.mytable.hideProcessing();
                    horizon.notice.error(horizon.lang['message']['operateError']);
                },
                success : function(data) {
                    table.mytable.hideProcessing();
                    if(data) {
                        horizon.notice.success(horizon.lang['message']['deleteSuccess']);
                       // $('#flow-tree').flowtree('reload');
                        table.mytable.reload();
                    }else{
                        horizon.notice.error(horizon.lang['message']['deleteFail']);
                    }
                }
            });
        },
        removeAllIdleMemInstance:function() {
            table.mytable.showProcessing();
            $.ajax({
                url : horizon.tools.formatUrl('/monitor/memory/remove/idle'),
                dataType:'json',
                cache : false,
                error : function(){
                    table.mytable.hideProcessing();
                    horizon.notice.error(horizon.lang['message']['operateError']);
                },
                success : function(data) {
                    table.mytable.hideProcessing();
                    if(data.restype=='success') {
                        horizon.notice.success(horizon.lang['message']['deleteSuccess']);
                        //$('#flow-tree').flowtree('reload');
                        table.mytable.reload();
                    }else{
                        horizon.notice.error(data.msg[0]? data.msg[0]: horizon.lang['message']['deleteFail']);
                    }
                }
            });
        }
    };
    return horizon.engine['memInstance'] = {
        init: function() {
            flowtree.init();
            table.init();
        },
    };
}));