/**
 *  系统通用参数可视化配置
 *
 *  @author pengys 2022/1/31
 */
(function(factory) {
    if (typeof define === 'function' && define.amd) {
        define([ 'jquery', 'echarts','horizonTable','gritter'], factory);
    } else {
        factory(echarts);
    }
}(function($,echarts){
    "use strict";
    var $cpuMonitor = $("#cpu-monitor-chart");
    var $jvmMonitor = $('#jvm-monitor-chart');

    var cpuMonitorChart = null;
    var jvmMonitorChart = null;

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

    var urls = {
        cpuRecord : horizon.tools.formatUrl('/system/server/cpuRecord'),
        cpuList : horizon.tools.formatUrl('/system/server/cpu/list'),
        jvmRecord : horizon.tools.formatUrl('/system/server/jvmRecord'),
        jvmList : horizon.tools.formatUrl('/system/server/jvm/list'),
        runRecord : horizon.tools.formatUrl('/system/server/runRecord'),
        diskList : horizon.tools.formatUrl('/system/server/disk/list'),
        diskRecord : horizon.tools.formatUrl('/system/server/diskRecord')
    };

    //容器的大小
    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 cpuMonitor = {
        //初始化实例监控图
        initCpuMonitorEcharts: function(data) {
            cpuMonitorChart = echarts.init($cpuMonitor[0]);
            if(data.length == 0) {
                cpuMonitorChart.clear();
                cpuMonitorChart.hideLoading();
                cpuMonitorChart.setOption({
                    title: {
                        text: horizon.lang['system-monitor']['successNodata'],
                        textStyle: {
                            fontFamily: 'Microsoft YaHei',
                            fontSize: 14,
                            fontWeight: 'normal',
                            color: '#666'
                        },
                        left: 'center',
                        top: 'middle'
                    }
                });
                systemMonitorInit.resize();
                return;
            }
            var optionCpuMonitor = {
                tooltip: {
                    trigger: 'axis'
                },
                toolbox:{
                    show:true,
                    feature:{
                        myTool1: {
                            show: true,
                            title: horizon.lang['system-monitor']['refresh'],
                            icon: 'image://' + horizon.paths.assetspath + '/manager/profile/img/refresh.png',
                            onclick: function (){
                                cpuMonitorChart.clear();
                                cpuMonitor.ajaxCpuMonitorData();
                            }
                        }
                    }
                },
                legend: {
                    data:[
                        horizon.lang['system-monitor']['totalCpu'],
                        horizon.lang['system-monitor']['serverCpu'],
                        horizon.lang['system-monitor']['freeCpu']
                    ]
                },
                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: function () {
                        //---- 填充X轴数据-----
                        var list = [];
                        for(var i = 0; i < data.length; i++){
                            var item = data[i];
                            list.push(item['recordTime'].substring(11,16));
                        }
                        return list;
                    }()
                },
                yAxis: {
                    type: 'value',
                    axisLabel: {
                        show: true,
                        interval: 'auto',
                        formatter: '{value} %'//纵坐标百分比
                    }
                   // name: horizon.lang['system-monitor']['percentage']
                },
                series: function () {
                    var totalData = [];
                    var usedData = [];
                    var freeData = [];
                    for(var i = 0; i < data.length; i++){
                        var item = data[i];
                        if(item.used){
                            usedData.push(item.used);
                        }
                        if(item.free){
                            freeData.push(item.free);
                        }
                        if(item.total){
                            totalData.push(item.total);
                        }
                    }
                    var itemStyle= {
                        'total' : { normal:{color:'#d87c7c'} },
                        'used' : { normal:{color:'#33CCCC'} },
                        'free' : { normal:{color:'#FF9966'} }
                    };
                    var total = {
                        name:horizon.lang['system-monitor']['totalCpu'],
                        type:'line',
                        data:totalData,
                        trigger: 'item',
                        axisPointer:{
                            show: true
                        },
                        smooth: true,
                        itemStyle:itemStyle['total']
                    };
                    var used = {
                        name: horizon.lang['system-monitor']['serverCpu'],
                        type:'line',
                        data:usedData,
                        axisPointer:{
                            show: true
                        },
                        smooth: true,
                        itemStyle:itemStyle['used']
                    };
                    var free = {
                        name:horizon.lang['system-monitor']['freeCpu'],
                        type:'line',
                        data:freeData,
                        axisPointer:{
                            show: true
                        },
                        smooth: true,
                        itemStyle:itemStyle['free']
                    }
                    var result = [];
                    if(usedData.length > 0){
                        result.push(used)
                    }
                    if(freeData.length > 0){
                        result.push(free)
                    }
                    if(totalData.length > 0){
                        result.push(total)
                    }
                    return result;
                }()

            };
            if (optionCpuMonitor && typeof optionCpuMonitor === 'object') {
                cpuMonitorChart.setOption(optionCpuMonitor);
            }
            cpuMonitorChart.resize();
        },
        ajaxCpuMonitorData:function () {
            $.ajax({
                url: urls.cpuRecord,
                data:{
                    server: $("#allServerCpu option:selected").val()
                },
                dataType: 'json',
                cache: false,
                error: function() {
                },
                success: function(data) {
                  cpuMonitor.initCpuMonitorEcharts(data);
                }
            });
        }

    };

    var jvmMonitor = {
        //初始化异常监控数据
        initJvmMonitorEcharts: function(data) {
            jvmMonitorChart = echarts.init($jvmMonitor[0]);
            if(data.length == 0) {
                jvmMonitorChart.hideLoading();
                jvmMonitorChart.setOption({
                    title: {
                        text: horizon.lang['system-monitor']['successNodata'],
                        textStyle: {
                            fontFamily: 'Microsoft YaHei',
                            fontSize: 14,
                            fontWeight: 'normal',
                            color: '#666'
                        },
                        left: 'center',
                        top: 'middle'
                    }
                });
                systemMonitorInit.resize();
                return;
            }
            var optionJvmMonitor = {
                tooltip : {
                    trigger: 'axis',
                },
                toolbox:{
                    show:true,
                    feature:{
                        myTool1: {
                            show: true,
                            title: horizon.lang['system-monitor']['refresh'],
                            icon: 'image://' + horizon.paths.assetspath + '/manager/profile/img/refresh.png',
                            onclick: function (){
                                jvmMonitorChart.clear();
                                jvmMonitor.ajaxJvmMonitorData();
                            }
                        }
                    }
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                legend: {
                    data:[
                        horizon.lang['system-monitor']['maxMemory'],
                        horizon.lang['system-monitor']['totalMemory'],
                        horizon.lang['system-monitor']['freeMemory'],
                        horizon.lang['system-monitor']['usedMemory']
                    ]
                },
                xAxis: [
                    {
                        type : 'category',
                        boundaryGap: false,
                        data : function (){
                            //---- 填充X轴数据-----
                            var list = [];
                            for(var i = 0; i < data.length; i++){
                                var item = data[i];
                                list.push(item['recordTime'].substring(11,16));
                            }
                            return list;
                        }()
                    }
                ],
                yAxis: [
                    {
                        type: 'value',
                        axisLabel: {
                            show: true,
                            interval: 'auto',
                            formatter: '{value}MB'//
                        }
                    }
                ],
                series : function () {
                    var totalData = [];
                    var freeData = [];
                    var usedData = [];
                    var maxData = [];
                    for(var i = 0; i < data.length; i++){
                        var item = data[i];
                        totalData.push(item.total);
                        freeData.push(item.free);
                        usedData.push(item.used);
                        maxData.push(item.max)
                    }

                    var itemStyle = {
                        'total': { normal:{color:'#33cccc'} },
                        'free': { normal:{color:'#00cc33'} },
                        'used': { normal:{color:'#ff6633'} },
                        'max': {normal:{color:'#c71585'}}
                    };
                    var max = {
                        name: horizon.lang['system-monitor']['maxMemory'],
                        type:'line',
                        data:maxData,
                        trigger: 'item',
                        axisPointer:{
                            show: true
                        },
                        smooth: true,
                        itemStyle:itemStyle['max']
                    };
                    var total = {
                        name:horizon.lang['system-monitor']['totalMemory'],
                        type:'line',
                        data:totalData,
                        trigger: 'item',
                        axisPointer:{
                            show: true
                        },
                        smooth: true,
                        itemStyle:itemStyle['total']
                    };
                    var free = {
                        name:horizon.lang['system-monitor']['freeMemory'],
                        type:'line',
                        data:freeData,
                        axisPointer:{
                            show: true
                        },
                        smooth: true,
                        itemStyle:itemStyle['free']
                    };
                    var used = {
                        name:horizon.lang['system-monitor']['usedMemory'],
                        type:'line',
                        data:usedData,
                        axisPointer:{
                            show: true
                        },
                        smooth: true,
                        itemStyle:itemStyle['used']
                    }
                    return [max, total, free, used];
                }()
            };
            if (optionJvmMonitor && typeof optionJvmMonitor === 'object') {
                jvmMonitorChart.setOption(optionJvmMonitor);
            }
            jvmMonitorChart.resize();
        },
        ajaxJvmMonitorData: function() {
            $.ajax({
                url: urls.jvmRecord,
                dataType: 'json',
                data:{
                    server:$("#allServerJvm option:selected").val()
                },
                cache: false,
                error: function() {
                    operatorError();
                },
                success: function(data) {
                    jvmMonitor.initJvmMonitorEcharts(data);
                }
            });
        }
    };

    var runMonitor = {
        initRunMonitor: function() {
            runMonitor.mytable = $('#appRun-monitor-chart').horizonTable({
               settings: {
                   reload:false,
                   searchable:false,
                   multipleSearchable: false,
                   height: containerSize.picHeight,
                   cache: false,
                   type:'post',
                   dataType: 'json',
                   columns: [
                       {
                           name : 'serverName',
                           title : horizon.lang['system-monitor']['serverName'],
                           width : '80px',
                           searchable : false,
                           orderable : false,
                           multipleSearchable : false
                       },
                       {
                           name : 'runTotalDHM',
                           title : horizon.lang['system-monitor']['runTotalDHM'],
                           width : '120px',
                           searchable : false,
                           orderable : false,
                           multipleSearchable : false
                       },
                       {
                           name : 'stopTotalDHM',
                           title :horizon.lang['system-monitor']['stopTotalDHM'],
                           width : '120px',
                           searchable : false,
                           orderable : false,
                           multipleSearchable : false
                       },
                       {
                           name : 'hostIp',
                           title : horizon.lang['system-monitor']['hostIp'],
                           width : '100px',
                           orderable : false,
                           multipleSearchable : false
                       }
                   ]
               },
               ajaxDataSource: urls.runRecord
           });
           $('.dataTables_header').addClass('hidden');
           $('.dataTables_footer').addClass('hidden')
        },
    };
    var diskMonitor = {
        initDiskMonitor: function() {
            diskMonitor.mytable = $('#disk-monitor-chart').horizonTable({
                settings: {
                    reload:false,
                    searchable:false,
                    multipleSearchable: false,
                    height: containerSize.picHeight,
                    cache: false,
                    type:'post',
                    dataType: 'json',
                    columns: [
                        {
                            name : 'serverName',
                            title : horizon.lang['system-monitor']['serverName'],
                            width : '80px',
                            searchable : false,
                            orderable : false,
                            multipleSearchable : false
                        },
                        {
                            name : 'total',
                            title : horizon.lang['system-monitor']['diskTotal'],
                            width : '80px',
                            searchable : false,
                            orderable : false,
                            multipleSearchable : false
                        },
                        {
                            name : 'used',
                            title :horizon.lang['system-monitor']['diskUsed'],
                            width : '80px',
                            searchable : false,
                            orderable : false,
                            multipleSearchable : false
                        },
                        {
                            name : 'free',
                            title : horizon.lang['system-monitor']['diskFree'],
                            width : '80px',
                            orderable : false,
                            multipleSearchable : false
                        },
                        {
                            name : 'diskUsage',
                            title : horizon.lang['system-monitor']['diskUsage'],
                            width : '60px',
                            orderable : false,
                            multipleSearchable : false
                        },
                        {
                            name : 'hostIp',
                            title : horizon.lang['system-monitor']['hostIp'],
                            width : '100px',
                            searchable : false,
                            orderable : false,
                            multipleSearchable : false
                        },
                    ]
                },
                ajaxDataSource: urls.diskRecord,
                ajaxDataParam: {
                    server:$("#allServerDisk option:selected").val()
                }
            });
            $('.dataTables_header').addClass('hidden');
            $('.dataTables_footer').addClass('hidden')
        },
    };

    var serverList={
        changeServer:function () {
            $('#allServerJvm').change(function () {
                if (jvmMonitorChart){
                    jvmMonitorChart.clear();
                }
                jvmMonitor.ajaxJvmMonitorData();
            });
            $('#allServerCpu').change(function () {
                if (cpuMonitorChart){
                    cpuMonitorChart.clear();
                }
                cpuMonitor.ajaxCpuMonitorData();
            });
        },
        initCpuList:function () {
            $('#allServerCpu').children('option').remove();
            $.ajax({
                url: urls.cpuList,
                cache: false,
                dataType: 'json',
                async: false,
                success: function (data) {
                    if (data.length) {
                        $('#allServerCpu').removeClass('hidden')
                        $.each(data, function (i, server) {
                            var $option = $('<option value="' + server + '">' + server+ '</option>');
                            $('#allServerCpu').append($option);
                        });
                        $('#allServerCpu').val(data[0]).trigger('change');
                    }else {
                        cpuMonitor.initCpuMonitorEcharts([])
                    }
                }
            });
        },
        initJvmList:function () {
            $('#allServerJvm').children('option').remove();
            $.ajax({
                url: urls.jvmList,
                cache: false,
                dataType: 'json',
                async: false,
                success: function (data) {
                    if (data.length) {
                        $('#allServerJvm').removeClass('hidden')
                        $.each(data, function (i, server) {
                            var $option = $('<option value="' + server + '">' + server+ '</option>');
                            $('#allServerJvm').append($option);
                        });
                        $('#allServerJvm').val(data[0]).trigger('change');;
                    }else {
                        jvmMonitor.initJvmMonitorEcharts([]);
                    }
                }
            });
        }
    }
    var systemMonitorInit = {
        init: function() {
            $cpuMonitor = $("#cpu-monitor-chart");
            $jvmMonitor = $('#jvm-monitor-chart');
            //实例监控
            $cpuMonitor.css({
                'width': '100%',
                'height':  containerSize.picHeight()
            });
            //cpuMonitor.ajaxCpuMonitorData();

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

            runMonitor.initRunMonitor();
            diskMonitor.initDiskMonitor();
            var browser = horizon.tools.browser();
            if(browser.browser == 'IE' && browser.version <= 8.0) {
                window.attachEvent('onresize', function() {
                    systemMonitorInit.resize();
                });
            }else{
                window.addEventListener('resize', function() {
                    systemMonitorInit.resize();
                });
            }
            $('.sidebar-collapse').on(horizon.tools.clickEvent() + '.ace.menu', function(e){
                setTimeout(function(){
                    systemMonitorInit.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(cpuMonitorChart != null){
                $cpuMonitor.css({
                    'width': '100%',
                    'height':  containerSize.picHeight()
                });
                cpuMonitorChart.resize();
            }
            if(jvmMonitorChart != null){
                $jvmMonitor.css({
                    'width': '100%',
                    'height':  containerSize.picHeight()
                });
                jvmMonitorChart.resize();
            }
        }
    };
    return horizon.engine['sysMonitored'] = {
        init: function(){
            serverList.changeServer();
            serverList.initCpuList();
            serverList.initJvmList();
            systemMonitorInit.init();
        }
    };
}));