<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="utf-8" %>
<%@include file="/WEB-INF/ehr/commons/jsp/commonInclude.jsp" %>
<%--<script src="${contextRoot}/develop/echarts/echarts.js"></script>--%>
<script>
    var host = "";
    var myChart;
    $(function () {
        myChart = echarts.init(document.getElementById('main'));
        getServerTree();
        //l-layout-left
        //初始化layout
        $("#div_wrapper").ligerLayout({
            height: "99%",
            leftWidth: 200,
            isLeftCollapse: false,//左边区域初始化不可以隐藏
            allowLeftCollapse: false//左边区域不可以隐藏
        });

        /*初始化时间控件-start*/
        $("#repeatStartTime").ligerDateEditor({
            width: 240,
            showTime: true
        });
        $("#repeatEndTime").ligerDateEditor({
            width: 240,
            showTime: true
        });
        $("#repeatStartTime").ligerDateEditor("setValue", prevDate());
        $("#repeatEndTime").ligerDateEditor("setValue", nowDate());
        /*初始化时间控件-end*/

        //初始化图表
        var type = $(".div-menu .active").attr("data-item");
        var beginTime = $("#repeatStartTime").ligerDateEditor("getValue");
        var endTime = $("#repeatEndTime").ligerDateEditor("getValue");
        getServerInfo(host, type, beginTime, endTime);
        getInfo(host, type, endTime);


        //搜索按钮事件
        $(".m-form-control").on("click", "#btnSearch", function () {
            var beginTime = $("#repeatStartTime").ligerDateEditor("getValue");
            var endTime = $("#repeatEndTime").ligerDateEditor("getValue");
            if (beginTime == "" && $endTime == "") {
                $.ligerDialog.error("请选择起始结束时间！");
                return false;
            }

            if (beginTime > endTime) {
                $.ligerDialog.error("开始时间不能大于结束时间！");
                return false;
            }

            var type = $(".div-menu .active").attr("data-item");
            //获取服务器监控数据
            getServerInfo(host, type, beginTime, endTime);
            getInfo(host, type, endTime);
        })

        //选项卡切换时间
        $(".div-menu").on("click", ".c-item", function () {
            $(".div-menu .c-item").removeClass("active");
            $(this).addClass("active");
            var type = $(this).attr("data-item");
            //获取服务器监控数据
            var beginTime = $("#repeatStartTime").ligerDateEditor("getValue");
            var endTime = $("#repeatEndTime").ligerDateEditor("getValue");
            if (beginTime > endTime) {
                $.ligerDialog.error("开始时间不能大于结束时间！");
                myChart.clear();
                return false;
            }
            getServerInfo(host, type, beginTime, endTime);
            getInfo(host, type, endTime);
        })
    });

    function getServerTree() {
        var serviceTree = $("#div_wrapper_left_ul_resourcetree");
        //初始化树
        $.ajax({
            type: "GET",
            dataType: "json",
            url: "${contextRoot}/monitor/server/trees",
            async: false,
            success: function (msg) {
                var data = JSON.parse(msg.message);
                host = data[0].id;
                if (msg.successFlg) {
                    // 初始化树形菜单
                    serviceTree = serviceTree.ligerTree({
                        data: data,
                        idFieldName: 'id',
                        nodeWidth: 200,
                        parentIDFieldName: 'pid',
                        isExpand: false,
                        onClick: function (obj) {
                            //初始化图表
                            host = obj.data.id;
                            var beginTime = $("#repeatStartTime").ligerDateEditor("getValue");
                            var endTime = $("#repeatEndTime").ligerDateEditor("getValue");
                            if (beginTime == "" && $endTime == "") {
                                $.ligerDialog.error("请选择起始结束时间！");
                                return false;
                            }

                            if (beginTime > endTime) {
                                $.ligerDialog.error("开始时间不能大于结束时间！");

                                return false;
                            }


                            var type = $(".div-menu .active").attr("data-item");
                            //获取服务器监控数据
                            getServerInfo(host, type, beginTime, endTime);
                            getInfo(host, type, endTime);
                        },
                        onSuccess: function (data) {
                            alert(2222);
                            host = data[0].id;
                        }
                    });
                }
            }
        });
    }

    function getServerInfo(host, type, beginTime, endTime) {
        $.ajax({
            type: "GET",
            url: "${contextRoot}/monitor/server/usage",
            dataType: "json",
            data: {host: host, type: type, beginTime: beginTime, endTime: endTime},
            cache: false,
            success: function (re) {
                if (re.successFlg) {
                    //TODO 设置图表
                    switch (type) {
                        case "cpu":
                            env.cpuInfo(re);
                            break;
                        case "memory":
                            env.memory(re);
                            break;
                        case "files":
                            env.files(re);
                            break;
                        case "net":
                            env.net(re);
                            break;
                        default:
                            break;
                    }
                }
                else {
                    $.ligerDialog.error(re.message);
                }
            },
            error: function (data) {
                $.ligerDialog.error("Status:" + data.status + "(" + data.statusText + ")");
            }
        });
    }

    var env = {
        $resourceTree: $("#div_wrapper_left_ul_resourcetree"),//树对象
        init: function () {
            //初始化树
            var resourceTree = this.$resourceTree;
            $.ajax({
                type: "POST",
                url: "${contextRoot}/monitor/server/hosts",
                success: function (msg) {
                    // 初始化树形菜单
                    resourceTree = $('#div_wrapper_left_ul_resourcetree').ligerTree({
                        data: msg.data,
                        idFieldName: 'host',
                        nodeWidth: 200,
                        isExpand: false,
                        onClick: function (obj) {
                        },
                        onSuccess: function (data) {
                            alert("success");
                        }
                    });
                }
            });
        },
        cpuInfo: function (re) {
            var data = re.data;
            var option = {
                series: [
                    {
                        name: '系统使用率',
                        type: 'line',
                        data: []
                    },
                    {
                        name: '总使用率',
                        type: 'line',
                        data: []
                    }
                ]
            }
            myChart = echarts.init(document.getElementById('main'));
            if (data != null && data.length > 0) {
                var x = [];
                var y1 = [];
                var y2 = [];
                for (var i = 0; i < data.length; i++) {
//                 var create_date = data[i].create_date.substring(11,16);
//                 x.push(create_date);
                    x.push(data[i].create_date);
                    y1.push(data[i].data.sysPerc);
                    y2.push(data[i].data.totalPerc);
                }
                // 基于准备好的dom，初始化echarts实例
                // 指定图表的配置项和数据
                option = {
                    title: {
                        text: ' CPU指标',
                        left: 'center'
                    },
                    tooltip: {
                        trigger: 'axis',
                        formatter: '{b} <br/>{a0}: {c0}% <br/>{a1}: {c1}%'
                    },
                    dataZoom: {
                        show: true,
                        start: 0,
                        end: 100
                    },
                    legend: {
                        left: 'left',
                        data: ['系统使用率', '总使用率']
                    },
                    xAxis: {
                        type: 'category',
                        name: '时间',
                        splitLine: {show: false},
                        data: x
                    },
                    grid: {
                        left: '3%',
                        right: '4%',
                        bottom: '3%',
                        containLabel: true
                    },
                    yAxis: {
                        type: 'log',
                        name: '使用率'
                    },
                    series: [
                        {
                            name: '系统使用率',
                            type: 'line',
//                         itemStyle: {normal: {areaStyle: {type: 'default'}}},
                            data: y1
                        },
                        {
                            name: '总使用率',
                            type: 'line',
//                         itemStyle: {normal: {areaStyle: {type: 'default'}}},
                            data: y2
                        }
                    ]
                };
                myChart.setOption(option);
                myChart.on('mouseover', function (params) {
//                 getInfo(host,type,params.name);
                    console.log(params);
                });
                //设置图例下方的信息

            }
            else {
                //TODO 清除数据处理
                myChart.setOption(option);
                myChart.clear();
            }
        },
        memory: function (re) {
            var data = re.data;
            var option = {
                series: [
                    {
                        name: '使用率',
                        type: 'line',
                        data: []
                    }
                ]
            };
            myChart = echarts.init(document.getElementById('main'));
            if (data != null && data.length > 0) {
                var x = [];
                var y1 = [];
                var y2 = [];
                for (var i = 0; i < data.length; i++) {
//                    var create_date = data[i].create_date.substring(11,16);
                    x.push(data[i].create_date);
                    y1.push(data[i].data.usedPerc);
//                    y2.push(data[i].data.freePerc);
                }
                // 基于准备好的dom，初始化echarts实例
                // 指定图表的配置项和数据
                option = {
                    title: {
                        text: ' 内存使用率指标',
                        left: 'center'
                    },
                    tooltip: {
                        trigger: 'axis',
                        formatter: '{b} <br/>{a0}: {c0}% '
                    },
                    dataZoom: {
                        show: true,
                        start: 0,
                        end: 100
                    },
                    legend: {
                        left: 'left',
                        data: ['使用率']
                    },
                    xAxis: {
                        type: 'category',
                        name: '时间',
                        splitLine: {show: false},
                        data: x
                    },
                    grid: {
                        left: '3%',
                        right: '4%',
                        bottom: '3%',
                        containLabel: true
                    },
                    yAxis: {
                        type: 'log',
                        name: '使用率'
                    },
                    series: [
                        {
                            name: '使用率',
                            type: 'line',
                            data: y1
                        }
                    ]
                };
                myChart.setOption(option);
            }
            else {
                //TODO 清除数据
                myChart.setOption(option);
                myChart.clear();
            }
        },
        files: function (re) {
            var data = re.data;
            myChart = echarts.init(document.getElementById('main'));
            var option = {
                series: [
                    {
                        name: '已使用',
                        type: 'line',
                        data: []
                    },
                    {
                        name: '总量',
                        type: 'line',
                        data: []
                    }
                ]
            };
            if (data != null && data.length > 0) {
                var x = [];
                var y1 = [];
                var y2 = [];
                for (var i = 0; i < data.length; i++) {
                    var count = 0
                    var total = 0;
//                    var create_date = data[i].create_date.substring(11,16);
                    x.push(data[i].create_date);
                    for (var j = 0; j < data[i].data.length; j++) {
                        count += data[i].data[j].used;
                        total += data[i].data[j].total;
                    }
                    y1.push(count);
                    y2.push(total);
                }
                // 基于准备好的dom，初始化echarts实例
                // 指定图表的配置项和数据
                option = {
                    title: {
                        text: ' 磁盘指标',
                        left: 'center'
                    },
                    tooltip: {
                        trigger: 'axis',
                        formatter: '{b} <br/>{a0}: {c0} G <br/>{a1}: {c1} G'

                    },
                    dataZoom: {
                        show: true,
                        start: 0,
                        end: 100
                    },
                    legend: {
                        left: 'left',
                        data: ['已使用', '总量']
                    },
                    xAxis: {
                        type: 'category',
                        name: '时间',
                        splitLine: {show: false},
                        data: x
                    },
                    grid: {
                        left: '3%',
                        right: '4%',
                        bottom: '3%',
                        containLabel: true
                    },
                    yAxis: {
                        type: 'log',
                        name: '使用率'
                    },
                    series: [
                        {
                            name: '已使用',
                            type: 'line',
                            data: y1
                        },
                        {
                            name: '总量',
                            type: 'line',
                            data: y2
                        }
                    ]
                };
                myChart.setOption(option);
            }
            else {
                //TODO 清除数据
                myChart.setOption(option);
                myChart.clear();
            }
        },
        net: function (re) {
            var me = this;
            var data = re.data;
            var option = {
                series: [
                    {
                        name: '接收',
                        type: 'line',
                        data: []
                    },
                    {
                        name: '发送',
                        type: 'line',
                        data: []
                    }
                ]
            };
            myChart = echarts.init(document.getElementById('main'));
            if (data != null && data.length > 0) {
                var x = [];
                var y1 = [];
                var y2 = [];

                for (var i = 0; i < data.length; i++) {
//                    var create_date = data[i].create_date.substring(11,16);
                    x.push(data[i].create_date);
                    y1.push(data[i].data.rxbps);
                    y2.push(data[i].data.txbps);
                }
                // 基于准备好的dom，初始化echarts实例
                // 指定图表的配置项和数据
                option = {
                    title: {
                        text: ' 网络指标',
                        left: 'center'
                    },
                    tooltip: {
                        trigger: 'axis',
                        formatter: '{b} <br/>{a0}: {c0} kbps <br/>{a1}: {c1} kbps'
                    },
                    dataZoom: {
                        show: true,
                        start: 0,
                        end: 100
                    },
                    legend: {
                        left: 'left',
                        data: ['接收', '发送']
                    },
                    xAxis: {
                        type: 'category',
                        name: '时间',
                        splitLine: {show: false},
                        data: x
                    },
                    grid: {
                        left: '3%',
                        right: '4%',
                        bottom: '3%',
                        containLabel: true
                    },
                    yAxis: {
                        type: 'log',
                        name: '使用率（kbps）'
                    },
                    series: [
                        {
                            name: '接收',
                            type: 'line',
                            data: y1
                        },
                        {
                            name: '发送',
                            type: 'line',
                            data: y2
                        }
                    ]
                };
                myChart.setOption(option);
            }
            else {
                //TODO 清除数据
                myChart.setOption(option);
                myChart.clear();
            }
        }
    }


    /*当前时间*/
    function nowDate() {
        var date = new Date();
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var day = date.getDate();
        var hour = date.getHours();
        var minute = date.getMinutes();
        var second = date.getSeconds();
        return year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
    }
    /*前一天时间*/
    function prevDate() {
        var now = new Date();
        var date = new Date(now.getTime() - 24 * 3600 * 1000);
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var day = date.getDate();
        return year + '-' + month + '-' + day + ' 00:00:00';
    }


    /* **************************动态DIV添加************************ */

    /*  详情数据*/
    function getInfo(host, type, date) {
        $.ajax({
            type: "GET",
            url: "${contextRoot}/monitor/server/detail",
            dataType: "json",
            data: {host: host, type: type, date: date},
            cache: false,
            success: function (re) {
                if (re.successFlg) {
                    //TODO 设置详情数据
                    var data = re.data;
                    if (data != null && !isEmpty(data)) {
                        var envData = data.data;
                        var $envInfo = $("#detail");
                        var html;
                        switch (type) {
                            case "cpu":
                                html = getCpuHtml(envData);
                                break;
                            case "memory":
                                html = getMemoryHtml(envData);
                                break;
                            case "files":
                                html = getFilesHtml(envData);
                                break;
                            case "net":
                                html = getNetHtml(envData);
                                break;
                            default:
                                break;
                        }
                        $envInfo.html(html);
                    } else {
                        myChart.clear();
                    }
                }
                else {
                    $.ligerDialog.error(re.message);
                }
            },
            error: function (data) {
                $.ligerDialog.error("Status:" + data.status + "(" + data.statusText + ")");
            }
        });
    }


    function getCpuHtml(envData) {
        var html = "<div class=\"div-item\">\n" +
                "                    <div>\n" +
                "                        <div class=\"d-item\">利用率</div>" +
//                "                        <div class=\"d-item\">速度</div>" +
                "                    </div>" +
                "                    <div class=\"mb20\">\n" +
                "                        <div class=\"c-content\">" + envData.userPerc + "%</div>" +
//                "                        <div class=\"c-content\">2.18GHZ</div>\n" +
                "                    </div>\n" +
//                "                    <div>\n" +
//                "                        <div class=\"d-item\">进程</div>\n" +
//                "                        <div class=\"d-item\">线程</div>\n" +
//                "                        <div class=\"d-item\">句柄</div>\n" +
//                "                    </div>\n" +
//                "                    <div class=\"mb20\">\n" +
//                "                        <div class=\"c-content\">107</div>\n" +
//                "                        <div class=\"c-content\">1720</div>\n" +
//                "                        <div class=\"c-content\">59868</div>\n" +
//                "                    </div>\n" +
//                "                    <div class=\"f-dis-inline f-fs12\">正常运行时间</div>\n" +
//                "                    <div class=\"mb20\">\n" +
//                "                        <div class=\"c-content\">11:19:15:40</div>\n" +
//                "                    </div>\n" +
                "                </div>\n" +
                "                <div class=\"div-item\">\n" +
                "                    <div class=\"div-right-item\">最大速度：<span class=\"f-fs14 c-fwb\">" + envData.model.substring(envData.model.length - 8) + "</span></div>\n" +
//                "                    <div class=\"div-right-item\">插槽：<span class=\"f-fs14 c-fwb\">1</span></div>\n" +
                "                    <div class=\"div-right-item\">内核：<span class=\"f-fs14 c-fwb\">" + envData.quantity + "</span></div>\n" +
                "                    <div class=\"div-right-item\">逻辑处理器：<span class=\"f-fs14 c-fwb\">" + envData.totalCores + "</span></div>\n" +
                "                    <div class=\"div-right-item\">物理处理器：<span class=\"f-fs14 c-fwb\">" + envData.totalSockets + "</span></div>\n" +
//                "                    <div class=\"div-right-item\">L1缓存：<span class=\"f-fs14 c-fwb\">121KB</span></div>\n" +
//                "                    <div class=\"div-right-item\">L2缓存：<span class=\"f-fs14 c-fwb\">512KB</span></div>\n" +
//                "                    <div class=\"div-right-item\">L3缓存：<span class=\"f-fs14 c-fwb\">3.0MB</span></div>\n" +
                "                </div>";

        return html;
    }

    function getMemoryHtml(envData) {
        var html = "<div class=\"div-item\">\n" +
                "                    <div>\n" +
                "                        <div class=\"d-item\">已使用</div>" +
                "                        <div class=\"d-item\">可用</div>" +
                "                    </div>" +
                "                    <div class=\"mb20\">\n" +
                "                        <div class=\"c-content\">" + envData.used + "G</div>" +
                "                        <div class=\"c-content\">" + envData.free + "G</div>\n" +
                "                    </div>\n" +
                "                    <div>\n" +
                "                        <div class=\"d-item\">交换区使用量</div>\n" +
                "                        <div class=\"d-item\">交换区可用量</div>\n" +
                "                    </div>\n" +
                "                    <div class=\"mb20\">\n" +
                "                        <div class=\"c-content\">" + envData.swapUsed + "G</div>\n" +
                "                        <div class=\"c-content\">" + envData.swapFree + "G</div>\n" +
                "                    </div>\n" +
                "                </div>\n" +
                "                <div class=\"div-item\">\n" +
                "            <div>" +
                "                        <div class=\"d-item\">总量：</div>\n" +
                "                        <div class=\"d-item\">交换区总量：</div>\n" +
                "                    </div>\n" +
                "                    <div class=\"mb20\">\n" +
                "                        <div class=\"c-content\">" + envData.total + "G</div>\n" +
                "                        <div class=\"c-content\">" + envData.swapTotal + "G</div>\n" +
                "                    </div>\n" +
                "                </div>";
        return html;
    }

    function getFilesHtml(envData) {
        var html = "";
        var total = "";
        var use = "";
        if (envData.length > 0) {
            for (var i = 0; i < envData.length; i++) {
                total += "<div class=\"div-right-item\">" + envData[i].devName + "盘总量：<span class=\"f-fs14 c-fwb\">" + envData[i].total + "G</span></div>";
                use += "<div class=\"div-right-item\">" + envData[i].devName + "盘已使用：<span class=\"f-fs14 c-fwb\">" + envData[i].used + "G</span></div>";

            }
            html = "<div class=\"div-item\">" + total + "</div><div class=\"div-item\">" + use + "</div>";
        }
        return html;
    }

    function getNetHtml(envData) {
        var html = "<div class=\"div-item\">\n" +
                "                    <div>\n" +
                "                        <div class=\"d-item\">发送</div>" +
                "                    </div>" +
                "                    <div class=\"mb20\">\n" +
                "                        <div class=\"c-content\">" + envData.txbps + " kbps</div>" +
                "                    </div>\n" +
                "                    <div>\n" +
                "                        <div class=\"d-item\">接收</div>\n" +
                "                    </div>\n" +
                "                    <div class=\"mb20\">\n" +
                "                        <div class=\"c-content\">" + envData.rxbps + " kbps</div>\n" +
                "                    </div>\n" +
                "                </div>\n" +
                "                <div class=\"div-item\">\n" +
                "                    <div class=\"div-right-item\">適配器名：<span class=\"f-fs14 c-fwb\">" + envData.name + "</span></div>\n" +
                "                    <div class=\"div-right-item\">连接类型：<span class=\"f-fs14 c-fwb\">" + envData.type + "</span></div>\n" +
                "                    <div class=\"div-right-item\">IP地址：<span class=\"f-fs14 c-fwb\">" + envData.address + "</span></div>\n" +
                "                    <div class=\"div-right-item\">Mac地址：<span class=\"f-fs14 c-fwb\">" + envData.mac + "</span></div>\n" +
                "                </div>";
        return html;
    }

    function isEmpty(value) {
        return (Array.isArray(value) && value.length === 0)
                || (Object.prototype.isPrototypeOf(value) && Object.keys(value).length === 0);
    }


</script>