/**
 * 首页监控图相关功能
 *
 * @since 2017-07-17
 * @author chengll
 */
(function(factory) {
    if(typeof define === 'function' && define.amd) {
        var scripts = ['jquery', 'echarts','horizonTable','gritter'];
        define(scripts, factory);
    }else {
        factory(jQuery, echarts);
    }
}(function($, echarts) {
    "use strict";
    var optionTime = null;//实时监控数据配置项
    var timeInterval; //实时时间间隔对象
    var dateTime = []; //实时监控时间
    var activeData = []; //实时监控 --内存中活动实例数
    var totleData = [];  //实时监控 --内存中实例数总数
    var licenseData = []; //实时监控 --license
    var yearHis = 0; //实时监控 -- 后台返回的年份
    var currentYearHis = 0; //实时监控 -- 当前显示的年份

    var $instanceMonitor = $("#instance-monitoring");
    var $exceptionMonitor = $('#exception-monitor-chart');
    var $requestMonitor = $('#request-monitor-chart');
    var $time = $('#time-charts');
    var $history = $('#history-charts');
    var $flowMonitor = $('#flow-monitor-chart');

    var instanceMonitorChart = null;
    var exceptionMonitorChart = null;
    var flowMonitorChart = null;
    var requestMonitorChart = null;
    var timeChart = null;
    var hisChart = null;

    var operatorError = function() {
        horizon.notice.error(horizon.lang.message['operateError']);
    };

    var urls = {
        getCount : horizon.tools.formatUrl('/home/find/count'),
        getConsume : horizon.tools.formatUrl('/home/find/consume'),
        exception : horizon.tools.formatUrl('/home/find/exception'),
        findFlow : horizon.tools.formatUrl('/home/flow/sort'),
        history : horizon.tools.formatUrl('/monitor/memory/history'),
        realTime : horizon.tools.formatUrl('/monitor/memory/realtime'),
        requestRecord : horizon.tools.formatUrl('/system/server/requestRecord'),
        chartUrl : horizon.tools.formatUrl('/home/instance/monitor/chart')
    };

    //容器的大小
    var containerSize = {
        height: function() {
            var _height = horizon.tools.getPageContentHeight();
            _height = _height - $('.flow-status-pic').outerHeight(true) - $('.widget-header-ram').outerHeight(true);
            if($(window).width() < 768) {
                _height = _height/2.5 - parseInt($('.page-content').css('paddingTop'))
            }else{
                _height = _height/2 - parseInt($('.page-content').css('paddingTop'))
            }
            return _height;
        },
        width: function() {
            return $('.page-content-area').outerWidth(true);
        },
        picHeight: function() {
            var _picHeight = containerSize.height();
            _picHeight -= $('.widget-header-flow').outerHeight(true);
            _picHeight -= _picHeight/5;
            return _picHeight;
        }
    };
    var countList = {
        // 初始化数据总数
        init:function(){
            $.ajax({
                url : urls.getCount,
                dataType:'json',
                cache : false,
                error : function(){
                    horizon.notice.error(horizon.lang['message']['operateError']);
                },
                success : function(data) {
                    if(data) {
                        $.each(data,function(key,value){
                            $("#"+key).html(value);
                        });
                    }else{
                        horizon.notice.error(horizon.lang['homepage']['getDataFail']);
                    }
                }
            });
        },
        consume:function(){
            $.ajax({
                url : urls.getConsume,
                dataType:'json',
                cache : false,
                error : function(){
                    horizon.notice.error(horizon.lang['message']['operateError']);
                },
                success : function(data) {
                    if(data) {
                        $.each(data,function(key,value){
                            $("#" + key).text(value);
                        });
                    }else{
                        horizon.notice.error(horizon.lang['homepage']['getDataFail']);
                    }
                }
            });
        }
    };

    var instanceMonitoring = {
        //初始化实例监控图
        init: function() {
            instanceMonitorChart = echarts.init($instanceMonitor[0]);
            var option = {
                tooltip: {
                    trigger: 'axis'
                },
                legend: {
                    data:[]
                },
                toolbox:{
                    show:true,
                    feature:{
                        myTool1: {
                            show: true,
                            title: horizon.lang.homepage['refresh'],
                            icon: 'image://' + horizon.paths.assetspath + '/manager/homepage/img/refresh.png',
                            onclick: function (){
                                instanceMonitorChart.clear();
                                instanceMonitoring.init();
                            }
                        }
                    }
                },
                grid: {
                    left: '4%',
                    right: '4%',
                    top:'15%',
                    bottom: '0%',
                    containLabel: true
                },
                xAxis:  {
                    type: 'category',
                    boundaryGap: false,
                    splitLine:{
                        show:false
                    },
                    axisLine:{
                        lineStyle:{
                            color:'#CCCCCC'
                        }
                    },
                    axisLabel:{
                        textStyle:{
                            color:'#000000'
                        }
                    },
                    data: []
                },
                yAxis: {
                    type: 'value',
                    minInterval:1,
                    splitLine:{
                        show:true,
                        lineStyle: {
                            color: ['#f3f5f9'],
                            type:'solid'
                        }
                    },
                    axisLine:{
                        lineStyle:{
                            color:'#CCCCCC'
                        }
                    },
                    axisLabel:{
                        textStyle:{
                            color:'#000000'
                        }
                    }
                },
                series: [
                    {
                        name:horizon.lang['homepage']['finishInstance'],
                        type:'line',
                        data:[]
                    },
                    {
                        name:horizon.lang['homepage']['notFinishInstance'],
                        type:'line',
                        data:[]
                    }
                ]

            };
            $.ajax({
                url: urls.chartUrl,
                dataType: 'json',
                cache: false,
                error: function() {
                },
                success: function(data) {
                    if (data) {
                        if(data.length == 0) {
                        	instanceMonitorChart.clear();
                            instanceMonitorChart.hideLoading();
                            instanceMonitorChart.setOption({
                                title: {
                                    text: horizon.lang.homepage['successNodata'],
                                    textStyle: {
                                        fontFamily: 'Microsoft YaHei',
                                        fontSize: 14,
                                        fontWeight: 'normal',
                                        color: '#666'
                                    },
                                    left: 'center',
                                    top: 'middle'
                                }
                            });
                        }else{
                            var legendData =[];
                            var xaxisData=[];
                            var seriesData =[];
                            var itemStyleExecption = {
                                'createCount' : { normal:{color:'#478FCA'} },
                                'finishCount' : { normal:{color:'#ABD4A5'} }
                            };
                            var xaxis=function(){
                                return {1:{text:horizon.lang['homepage']['notFinishInstance'],name:'createCount' },
                                    2:{text:horizon.lang['homepage']['finishInstance'],name:'finishCount' }
                                }
                            };
                            //---- 填充X轴数据-----
                            for(var i=0;i<data.length;i++){
                                var item = data[i];
                                xaxisData.push(item.activeDate);
                            }
                            //---- 填充显示数据 -----
                            for(var key in xaxis()){
                                var xaxisitem = xaxis()[key];
                                legendData.push(xaxisitem.text);
                                var obj = {
                                    name:xaxisitem.text,
                                    type:'line',
                                    itemStyle:itemStyleExecption[xaxisitem.name]
                                };
                                var seriesd =[];
                                for(var i=0;i<data.length;i++){
                                    var item = data[i];
                                    seriesd.push(item[xaxisitem.name]);
                                }
                                obj.data=seriesd;
                                seriesData.push(obj);
                            }
                            instanceMonitorChart.hideLoading();
                            instanceMonitorChart.setOption({
                                legend: { data:legendData  },
                                xAxis: { data:xaxisData  },
                                series: seriesData
                            });
                            instanceMonitorChart.resize();
                        }
                    }
                }
            });
            instanceMonitorChart.setOption(option);
        }
    };

    var exceptionMonitor = {
        //初始化异常监控数据
        initExceptionMonitorEcharts: function(data) {
            exceptionMonitorChart = echarts.init($exceptionMonitor[0]);
            if(data.length == 0) {
                exceptionMonitorChart.hideLoading();
                exceptionMonitorChart.setOption({
                    title: {
                        text: horizon.lang.homepage['successNodata'],
                        textStyle: {
                            fontFamily: 'Microsoft YaHei',
                            fontSize: 14,
                            fontWeight: 'normal',
                            color: '#666'
                        },
                        left: 'center',
                        top: 'middle'
                    }
                });
                return;
            }
            var optionExceptionMonitor = {
                tooltip : {
                    trigger: 'axis',
                },
                toolbox:{
                    show:true,
                    feature:{
                        myTool1: {
                            show: true,
                            title: horizon.lang.homepage['refresh'],
                            icon: 'image://' + horizon.paths.assetspath + '/manager/homepage/img/refresh.png',
                            onclick: function (){
                                exceptionMonitorChart.clear();
                                exceptionMonitor.ajaxExceptionMonitorData();
                            }
                        }
                    }
                },
                grid: {
                    left: '4%',
                    right: '4%',
                    top:'15%',
                    bottom: '0%',
                    containLabel: true
                },
                legend: {
                    data:function () {
                        return [
                            horizon.lang['homepage']['extendedCount'],
                            horizon.lang['homepage']['revokeCount'],
                            horizon.lang['homepage']['stopCount']
                            ]
                    }()
                },
                xAxis: [
                    {
                        type : 'category',
                        boundaryGap: false,
                        splitLine:{
                            show:false
                        },
                        axisLine:{
                            lineStyle:{
                                color:'#CCCCCC'
                            }
                        },
                        axisLabel:{
                            textStyle:{
                                color:'#000000'
                            }
                        },
                        data : function (){
                            //---- 填充X轴数据-----
                            var list = [];
                            for(var i = 0; i < data.length; i++){
                                var item = data[i];
                                list.push(item.activeDate.substr(5));
                            }
                            return list;
                        }()
                    }
                ],
                yAxis: [
                    {
                        type: 'value',
                        minInterval:1,
                        splitLine:{
                            show:true,
                            lineStyle: {
                                color: ['#f3f5f9'],
                                type:'solid'
                            }
                        },
                        axisLine:{
                            lineStyle:{
                                color:'#CCCCCC'
                            }
                        },
                        axisLabel:{
                            textStyle:{
                                color:'#000000'
                            }
                        }
                    }
                ],
                series : function () {
                    var extendedData = [];
                    var stopData = [];
                    var revokeData = [];
                    for(var i = 0; i < data.length; i++){
                        var item = data[i];
                        extendedData.push(item.extendedCount);
                        stopData.push(item.exceptionCount);
                        revokeData.push(item.revokeCount);
                    }
                    var itemStyleExecption = {
                        'extendedCount' : { normal:{color:'#d87c7c'} },
                        'stopCount' : { normal:{color:'#33CCCC'} },
                        'revokeCount' : { normal:{color:'#D3D3D3'} }
                    };
                    var extended = {
                        name:horizon.lang['homepage']['extendedCount'],
                        type:'line',
                        data:extendedData,
                        itemStyle:itemStyleExecption['extendedData']
                    };
                    var revoke = {
                        name:horizon.lang['homepage']['revokeCount'],
                        type:'line',
                        data:revokeData,
                        itemStyle:itemStyleExecption['revokeCount']
                    }
                    var stop = {
                        name:horizon.lang['homepage']['stopCount'],
                        type:'line',
                        data:stopData,
                        itemStyle:itemStyleExecption['stopCount']
                    };
                    return [extended, revoke, stop];
                }()
            };
            if (optionExceptionMonitor && typeof optionExceptionMonitor === 'object') {
                exceptionMonitorChart.setOption(optionExceptionMonitor);
            }
            exceptionMonitorChart.resize();
        },
        ajaxExceptionMonitorData: function() {
            exceptionMonitorChart = echarts.init($exceptionMonitor[0]);
            $.ajax({
                url: urls.exception,
                dataType: 'json',
                cache: false,
                error: function() {
                    operatorError();
                },
                success: function(data) {
                    exceptionMonitor.initExceptionMonitorEcharts(data);
                }
            });
        }
    };

    var flowMonitor = {
        initFlowMonitorEchats: function(data) {
            flowMonitorChart = echarts.init($flowMonitor[0]);
            if(data.length == 0) {
                flowMonitorChart.hideLoading();
                flowMonitorChart.setOption({
                    title: {
                        text: horizon.lang.homepage['noFlow'],
                        textStyle: {
                            fontFamily: 'Microsoft YaHei',
                            fontSize: 14,
                            fontWeight: 'normal',
                            color: '#666'
                        },
                        left: 'center',
                        top: 'middle'
                    }
                });
                return;
            }
            var optionFlowMonitor = {
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow'
                    }
                },
                toolbox:{
                    show:true,
                    feature:{
                        myTool1: {
                            show: true,
                            title: horizon.lang.homepage['refresh'],
                            icon: 'image://' + horizon.paths.assetspath + '/manager/homepage/img/refresh.png',
                            onclick: function (){
                                flowMonitorChart.clear();
                                flowMonitor.ajaxFlowMonitorData();
                            }
                        }
                    }
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                xAxis: [
                    {
                        type: 'category',
                        data: function () {
                            var list = [];
                            for(var i = 0; i < data.length;i++){
                                list.push(data[i].flowName)
                            }
                            return list
                        }(),
                        axisTick: {
                            alignWithLabel: true
                        },
                        axisLabel: {
                            interval:0,
                            formatter: function (value){
                                if ($.trim(value).replace(/[^\x00-\xff]/g, "aa").length > 8){
                                    return value.substring(0,4) + ('...');
                                }
                                return value;
                            }
                        }
                    }
                ],
                yAxis: [
                    {
                        type: 'value',
                        minInterval:1
                    }
                ],
                series: [
                    {
                        name: horizon.lang.homepage['userCount'],
                        type: 'bar',
                        barWidth: '30%',
                        data: function () {
                            var list = [];
                            for(var i = 0; i < data.length;i++){
                                list.push(data[i].userCount)
                            }
                            return list
                        }(),
                        itemStyle:{ normal:{color:'#478FCA'}}
                    }
                ]
            };
            if (optionFlowMonitor && typeof optionFlowMonitor === 'object') {
                flowMonitorChart.setOption(optionFlowMonitor);
            }
            flowMonitorChart.resize();
        },

        ajaxFlowMonitorData: function() {
            $.ajax({
                url: urls.findFlow,
                dataType: 'json',
                cache: false,
                error: function() {
                    operatorError();
                },
                success: function(data) {
                    if(data) {
                        flowMonitor.initFlowMonitorEchats(data);
                    }
                }
            });
        }
    };

    //历史监控
    var hisMonitor = {
        //初始化历史监控数据
        initEchartsHis: function (hisChart) {
            yearHis = new Date().toJSON().substring(0, 4);
            currentYearHis = yearHis;
            //配置项基本信息
            var optionHis = {
                baseOption: {
                    tooltip: {},
                    toolbox: {
                        show: true,
                        itemSize: 20,
                        feature: {
                            myPrev: {
                                show: true,
                                title: horizon.lang.homepage['prevYear'],
                                icon: 'image://' + horizon.paths.assetspath + '/manager/homepage/img/next.bmp',
                                onclick: function () {
                                    yearHis--;
                                    hisMonitor.ajaxHisData(yearHis, hisChart);
                                }
                            },
                            myNext: {
                                show: true,
                                title: horizon.lang.homepage['nextYear'],
                                icon: 'image://' + horizon.paths.assetspath + '/manager/homepage/img/prev.bmp',
                                onclick: function () {
                                    yearHis++;
                                    hisMonitor.ajaxHisData(yearHis, hisChart);
                                }
                            }
                        },
                        right: '10%'
                    },
                    xAxis: {
                        splitLine: {
                            show: false
                        },
                        axisLine: {
                            lineStyle: {
                                color: '#CCCCCC'
                            }
                        },
                        axisLabel: {
                            textStyle: {
                                color: '#000000'
                            }
                        },
                        data: []
                    },
                    yAxis: {
                        minInterval:1,
                        splitLine: {
                            show: true,
                            lineStyle: {
                                color: ['#f3f5f9'],
                                type: 'solid'
                            }
                        },
                        axisLine: {
                            lineStyle: {
                                color: '#CCCCCC'
                            }
                        },
                        axisLabel: {
                            textStyle: {
                                color: '#000000'
                            }
                        }
                    },
                    series: [
                        {
                            name: horizon.lang.homepage['activeNumInMemory'],
                            type: 'bar',
                            itemStyle: {
                                normal: {
                                    color: '#8FC6EA'
                                }
                            },
                            data: []
                        },
                        {
                            name: horizon.lang.homepage['licenseNum'],
                            type: 'bar',
                            itemStyle: {
                                normal: {
                                    color: '#d87c7c'
                                }
                            },
                            data: []
                        },
                        {
                            name: horizon.lang.homepage['instanceTotalInMemory'],
                            type: 'bar',
                            itemStyle: {
                                normal: {
                                    color: '#ABD4A5'
                                }
                            },
                            data: []
                        }
                    ]
                },
                media: [
                    {
                        query: {
                            maxHeight: 200
                        },
                        option: {
                            grid: {
                                left: '4%',
                                right: '3%',
                                top: '2%',
                                bottom: '15%'
                            },
                            title: {
                                text: ''
                            },
                            legend: {
                                data: []
                            }
                        }
                    },
                    {
                        query: {
                            maxWidth: 400
                        },
                        option: {
                            grid: {
                                left: '4%',
                                right: '3%',
                                top: '2%',
                                bottom: '20%'
                            },
                            title: {
                                text: ''
                            },
                            legend: {
                                data: []
                            }
                        }
                    },
                    {
                        query: {
                            maxWidth: 1240
                        },
                        option: {
                            grid: {
                                left: '4%',
                                right: '3%',
                                top: '15%',
                                bottom: '12%'
                            }
                        }
                    },
                    {
                        option: {
                            grid: {
                                left: '4%',
                                right: '2%',
                                top: '15%',
                                bottom: '12%'
                            },
                            title: {
                                x: 'center',
                                top: 5
                            },
                            legend: {
                                data: [horizon.lang.homepage['activeNumInMemory'],
                                    horizon.lang.homepage['licenseNum'],
                                    horizon.lang.homepage['instanceTotalInMemory']],
                                x: 'left'
                            }
                        }
                    }
                ]
            };
            hisChart.showLoading();
            //显示图表
            if (optionHis && typeof optionHis === 'object') {
                hisChart.setOption(optionHis);
            }
        },
        ajaxHisData: function (year, hisChart) {
            $.ajax({
                url: urls.history,
                dataType: 'json',
                data: {
                    year: year
                },
                cache: false,
                error: function () {
                    operatorError();
                    hisChart.hideLoading();
                },
                success: function (data) {
                    if (data && data.license) {
                        yearHis = data.date;
                        currentYearHis = data.date;
                        var licenseCount = 0;
                        for (var i = 0, len = data.license.length; i < len; i++) {
                            var license = data.license[i];
                            if (license && license != '') {
                                if(license == 2147483647){
                                    data.license[i] = parseInt(data.totle[i]) + 10
                                }
                            }
                        }
                        // var typeChar = 'line';
                        // if (licenseCount == 1) {
                        //     typeChar = 'bar';
                        // }
                        hisChart.hideLoading();
                        hisChart.setOption({
                            title: {
                                text: data.date + horizon.lang.homepage['yearHistoryMonitor']
                            },
                            xAxis: {
                                minInterval:1,
                                data: horizon.lang.homepage.months
                            },
                            series: [
                                {
                                    name: horizon.lang.homepage['activeNumInMemory'],
                                    type: 'bar',
                                    data: data.active
                                },
                                {
                                    name: horizon.lang.homepage['licenseNum'],
                                    type: 'bar',
                                    data: data.license
                                },
                                {
                                    name: horizon.lang.homepage['instanceTotalInMemory'],
                                    type: 'bar',
                                    data: data.totle
                                }
                            ]
                        });
                    } else {
                        var errorGritter = function () {
                            horizon.notice.error(yearHis + horizon.lang.homepage['noData']);
                            yearHis = currentYearHis;
                        };
                        if ($('.gritter-item-wrapper').length) {
                            errorGritter();
                        } else {
                            errorGritter();
                        }
                        hisChart.hideLoading();
                    }
                }
            });
        }
    };
    //实时监控
    var timeMonitor = {
        initEchartsTime: function(timeChart) {
            //实时监控配置项
            optionTime = {
                baseOption: {
                	tooltip: {},
                    xAxis: {
                        type: 'category',
                        splitLine:{
                            show:false
                        },
                        axisLine:{
                            lineStyle:{
                                color:'#CCCCCC'
                            }
                        },
                        axisLabel:{
                            textStyle:{
                                color:'#000000'
                            }
                        },
                        boundaryGap: false,
                        data: dateTime
                    },
                    yAxis: {
                        minInterval:1,
                        boundaryGap: [0, '50%'],
                        type: 'value',
                        splitLine:{
                            show:true,
                            lineStyle: {
                                color: ['#f3f5f9'],
                                type:'solid'
                            }
                        },
                        axisLine:{
                            lineStyle:{
                                color:'#CCCCCC'
                            }
                        },
                        axisLabel:{
                            textStyle:{
                                color:'#000000'
                            }
                        }
                    },
                    legend:{
                    	data:[horizon.lang.homepage['licenseNum'],horizon.lang.homepage['instanceTotalInMemory'],horizon.lang.homepage['activeNumInMemory']]
                    },
                    series: [
                        {
                            name: horizon.lang.homepage['licenseNum'],
                            type: 'line',
                            data: licenseData
                        },
                        {
                            name: horizon.lang.homepage['instanceTotalInMemory'],
                            type: 'line',
                            areaStyle: {
                                normal: {
                                    color: '#8FC6EA'
                                }
                            },
                            smooth: true,
                            data: totleData
                        },
                        {
                            name: horizon.lang.homepage['activeNumInMemory'],
                            type: 'line',
                            areaStyle: {
                                normal: {
                                    color: '#EA8D8D'
                                }
                            },
                            smooth: true,
                            data: activeData
                        }
                    ]
                },
              media:[
                    {
                        query: {
                            maxHeight:200
                        },
                        option: {
                            grid:{
                                left: '4%',
                                right: '3%',
                                top: '2%',
                                bottom: '15%'
                            },
                            legend: {
                                data: []
                            }
                        }
                    },
                    {
                        query: {
                            maxWidth:400
                        },
                        option: {
                            grid:{
                                left: '10%',
                                right: '5%',
                                top: '2%',
                                bottom: '20%'
                            },
                            legend: {
                                data: []
                            }
                        }
                    },
                    {
                        option: {
                            grid:{
                                left: '4%',
                                right: '2%',
                                top: '10%',
                                bottom: '10%'
                            },
                            legend: {
                                data: [horizon.lang.homepage['licenseNum'],
                                    horizon.lang.homepage['activeNumInMemory'],
                                    horizon.lang.homepage['instanceTotalInMemory']],
                                x: 'center'
                            }
                        }
                    }
                ]
            };
            timeChart.showLoading();
            //实时监控ajax数据
            timeMonitor.ajaxTimeData(timeChart);
            //实时刷新
            timeMonitor.setTimeInterval(timeChart);
        },
        setTimeInterval: function(timeChart) {
            timeInterval = setInterval(function () {
                //切换其他菜单时停止实时刷新
                if (!$('.homepage').length) {
                    window.clearInterval(timeInterval);
                    return;
                }
                timeMonitor.ajaxTimeData(timeChart);
                timeChart.setOption({
                    xAxis: {
                        minInterval:1,
                        data: dateTime
                    },
                    series: [
                        {
                            name: horizon.lang.homepage['licenseNum'],
                            data: licenseData
                        },
                        {
                            name: horizon.lang.homepage['activeNumInMemory'],
                            data: activeData
                        },
                        {
                            name: horizon.lang.homepage['instanceTotalInMemory'],
                            data: totleData
                        }
                    ]
                });
            }, 5000);
        },
        ajaxTimeData: function(timeChart) {
            $.ajax({
                url: urls.realTime,
                dataType: 'json',
                cache: false,
                error: function() {
                    operatorError();
                    window.clearInterval(timeInterval);
                },
                success: function(data) {
                    if(data) {
                        if (data.status === 'error' && data.code === 401) {
                            return;
                        }
                    	var selected = {}; //是一个对象
                        timeChart.hideLoading();
                        var time = data.dateTime.substring(11,19);
                        dateTime.push(time);
                        activeData.push(data.active);
                        totleData.push(data.totle);
                        var licenseNum = data.license;
                        var option = timeChart.getOption();
                        if(licenseNum==2147483647){
                        	licenseData.push(data.totle+10)
                        }else{
                        	licenseData.push(data.license)
                        }
                        if(option && option.legend){
                        	 selected = option.legend[0].selected? option.legend[0].selected:{};
                        }
                        optionTime.baseOption.legend.selected = selected;
                        if(dateTime.length > 15){
                            dateTime.shift();
                            activeData.shift();
                            totleData.shift();
                            licenseData.shift();
                        }
                        if(optionTime && typeof optionTime === 'object') {
                            timeChart.setOption(optionTime, true);
                        }
                    }
                }
            });
        }
    };
    var requestMonitor = {
        initRequestEcharts: function (data) {
            requestMonitorChart = echarts.init($requestMonitor[0]);
            if(JSON.stringify(data) == '{}') {
                requestMonitorChart.hideLoading();
                requestMonitorChart.setOption({
                    title: {
                        text: horizon.lang.homepage['successNodata'],
                        textStyle: {
                            fontFamily: 'Microsoft YaHei',
                            fontSize: 14,
                            fontWeight: 'normal',
                            color: '#666'
                        },
                        left: 'center',
                        top: 'middle'
                    }
                });
                return;
            }
            var optionRequest = {
                tooltip: {
                    trigger: 'axis',
                    formatter: "{b} <br/>{a}:{c}ms"
                },
                toolbox:{
                    show:true,
                    feature:{
                        myTool1: {
                            show: true,
                            title: horizon.lang.homepage['refresh'],
                            icon: 'image://' + horizon.paths.assetspath + '/manager/homepage/img/refresh.png',
                            onclick: function (){
                                requestMonitorChart.clear();
                                requestMonitor.ajaxRequestRecordData();
                            }
                        }
                    }
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                legend: {
                    data: function () {
                        //---- 填充X轴数据-----
                        var list = [];
                        for (var key in data) {
                            list.push(key);
                        }
                        return list;
                    }(),
                    selectedMode: 'single'
                },
                xAxis: [
                    {
                        type: 'category',
                        boundaryGap: false,
                        data: function () {
                            var list = [];
                            for (var key in data) {
                                var each = data[key];
                                for (var i = 0; i < each.length; i++) {
                                    var item = each[i];
                                    list.push(item['recordTime'].substring(11, 16));
                                }
                                return list;
                            }
                        }()
                    }
                ],
                yAxis: [
                    {
                        type: 'value',
                        name:'ms',
                        nameTextStyle: {
                            fontWeight: "bolder",
                            fontSize: 14
                        }
                    }
                ],
                series: function () {
                    var seriesData = []
                    for (var key in data) {
                        var each = data[key];
                        var eachData = [];
                        for (var i = 0; i < each.length; i++) {
                            var item = each[i];
                            eachData.push(item.avgRtt);
                        }
                        var temp = {
                            name: key,
                            type: 'line',
                            stack: "Total",
                            data: eachData,
                            axisPointer: {
                                show: true
                            },
                            smooth: true,
                            itemStyle:{ normal:{color:'#d87c7c'} }
                        }
                        seriesData.push(temp)
                    }
                    return seriesData;
                }()
            };
            // requestMonitorChart.on('legendselectchanged', function (obj) {
            //     var selected = obj.selected;
            //     var name = obj.name;
            //     if (selected != undefined) {
            //         if (requestMonitor.isOnlyClickedOneIsUnSelected(name, selected)) {
            //             requestMonitor.onlyEnableCurrentSelectedLegend(name, selected, requestMonitorChart);
            //         }
            //     }
            // });
            if (optionRequest && typeof optionRequest === 'object') {
                requestMonitorChart.setOption(optionRequest, true);
            }
            requestMonitorChart.resize();
        },
        ajaxRequestRecordData: function () {
            $.ajax({
                url: urls.requestRecord,
                dataType: 'json',
                cache: false,
                error: function () {
                    operatorError();
                },
                success: function (data) {
                    requestMonitor.initRequestEcharts(data);
                }
            });
        },
        isOnlyClickedOneIsUnSelected: function (name, selected) {
            var unSelectedCount = 0;
            for (var item in selected) {
                if (!selected.hasOwnProperty(item)) {
                    continue;
                }
                if (selected[item] == false) {
                    ++unSelectedCount;
                }
            }
            return unSelectedCount == 1 && selected[name] == false;
        },
        onlyEnableCurrentSelectedLegend:function (name, selected, echartInstance) {
            var legend = [];
            for ( var item in selected) {
                if (!selected.hasOwnProperty(item)) {
                    continue;
                }
                legend.push({'name': item});

            }
            echartInstance.dispatchAction({
                type: 'legendToggleSelect',
                batch: legend
            });

        }
    }
    var monitorInit = {
        init: function() {
            $instanceMonitor = $("#instance-monitoring");
            $exceptionMonitor = $('#exception-monitor-chart');
            $requestMonitor = $('#request-monitor-chart');
            $flowMonitor = $('#flow-monitor-chart');
            timeChart = null;
            hisChart = null;

            //实例监控
            $instanceMonitor.css({
                'width': '100%',
                'height':  containerSize.picHeight()
            });
            instanceMonitoring.init();

            //异常监控
            $exceptionMonitor.css({
                'width': '100%',
                'height':  containerSize.picHeight()
            });
            exceptionMonitor.ajaxExceptionMonitorData();

            //初始化流程状态图
            $requestMonitor.css({
                'width': '100%',
                'height': containerSize.picHeight()+4.5
            });
            requestMonitor.ajaxRequestRecordData();
            //初始化流程监控图
            $flowMonitor.css({
                'width': '100%',
                'height': containerSize.picHeight()+4.5
            });
            flowMonitor.ajaxFlowMonitorData();

            //初始化实时监控
            $('#realtime').on(horizon.tools.clickEvent(), function() {
                $time = $('#time-charts');
                $('#history-charts').css('visibility', 'hidden');
                $('#time-charts').removeClass().css('visibility', 'visible');
                $('#rt_his').removeClass().attr("class","btn btn-white btn-sm btn-round border-width-1");
                $('#realtime').removeClass().attr("class","btn btn-primary btn-sm btn-round border-width-1");
                $time.css({
                    'width': containerSize.width(),
                    'height': containerSize.picHeight()
                });
                if(timeChart == null) {
                    timeChart = echarts.init($time[0]);
                }
                timeMonitor.initEchartsTime(timeChart);
                timeChart.resize();
                $('#history-charts').addClass('hidden')
            }).trigger(horizon.tools.clickEvent());

            // 历史监控
            $('#rt_his').on(horizon.tools.clickEvent(), function() {
                $history = $('#history-charts');
                $('#time-charts').css('visibility', 'hidden');
                $('#history-charts').removeClass().css('visibility', 'visible');
                $('#realtime').removeClass().attr("class","btn btn-white btn-sm btn-round border-width-1");
                $('#rt_his').removeClass().attr("class","btn btn-primary btn-sm btn-round border-width-1");
                $history.css({
                    'width': containerSize.width(),
                    'height': containerSize.picHeight()
                });
                if(hisChart == null) {
                    hisChart = echarts.init($('#history-charts')[0]);
                }
                hisMonitor.initEchartsHis(hisChart);
                hisChart.resize();
                window.clearInterval(timeInterval);
                //图表ajax数据
                hisMonitor.ajaxHisData(new Date().toJSON().substring(0, 4), hisChart);
                $('#time-charts').addClass('hidden');
            });
            var browser = horizon.tools.browser();
            if(browser.browser == 'IE' && browser.version <= 8.0) {
                window.attachEvent('onresize', function() {
                    monitorInit.resize();
                });
            }else{
                window.addEventListener('resize', function() {
                    monitorInit.resize();
                });
            }
            $('.sidebar-collapse').on(horizon.tools.clickEvent() + '.ace.menu', function(e){
                setTimeout(function(){
                    monitorInit.resize();
                },100);
            });
        },
        resize: function() {
            if($('body').hasClass('embed') && $(window).width() < 768) {
                $('.hid-left').removeClass('hidden');
                $('.hid-right').addClass('hidden');
            }else if($('body').hasClass('embed') && $(window).width() >= 768){
                $('.hid-right').removeClass('hidden');
                $('.hid-left').addClass('hidden');
            }
            if(instanceMonitorChart != null){
                $instanceMonitor.css({
                    'width': '100%',
                    'height':  containerSize.picHeight()
                });
                instanceMonitorChart.resize();
            }
            if(exceptionMonitorChart != null){
                $exceptionMonitor.css({
                    'width': '100%',
                    'height':  containerSize.picHeight()
                });
                exceptionMonitorChart.resize();
            }
            if(requestMonitorChart != null) {
                $requestMonitor.css({
                    'width': '100%',
                    'height': containerSize.picHeight()+4.5
                });
                requestMonitorChart.resize();
            }
            if(flowMonitorChart != null) {
                $flowMonitor.css({
                    'width': '100%',
                    'height': containerSize.picHeight()+4.5
                });
                flowMonitorChart.resize();
            }
            if(hisChart != null) {
                $history.css({
                    'width': '100%',
                    'height': containerSize.picHeight()
                });
                hisChart.resize();
            }
            $time.css({
                'width': '100%',
                'height': containerSize.picHeight()
            });
            timeChart.resize();
        }
    };

    return horizon.engine['home'] = {
        init: function(){
            countList.init();
            countList.consume();
            monitorInit.init();
        }
    };
}));