<%@ 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/lib/plugin/switchery/switchery.js"></script>
<script src="${contextRoot}/develop/lib/plugin/echarts/echarts-all.js"></script>

<script>

    $(function () {
        //l-layout-left
        //初始化layout
        initSwitcher();

        $("#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*/

        //搜索按钮事件
        $(".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 id = $("#selectId").val();
            //获取服务器监控数据
            getServiceInfo(id, beginTime, endTime);
        });
        //初始化树
        getServiceTree();
    });


    function initSwitcher() {
        var me = this;
        //开关控件
        var changeCheckbox = document.querySelector('#jobStatusSwitch');
        var switchery = new Switchery(changeCheckbox, {disabled: true, size: 'large'});
        changeCheckbox.onchange = function () {
            var a = me.switchery;
            var jobId = $("#selJob").ligerComboBox("getValue");

            if (!changeCheckbox.checked) {
                me.valid(jobId, "0");
            }
            else {
                me.valid(jobId, "1");
            }
        };
    }

    function getServiceTree() {
        var serviceTree = $("#div_wrapper_left_ul_servicetree");
        //初始化树
        $.ajax({
            type: "GET",
            dataType: "json",
            url: "${contextRoot}/monitor/service/trees",
            success: function (msg) {
                if (msg.successFlg) {
                    // 初始化树形菜单
                    var message = JSON.parse(msg.message);
                    serviceTree = serviceTree.ligerTree({
                        data: message,
                        idFieldName: 'id',
                        nodeWidth: 200,
                        parentIDFieldName: 'pid',
                        isExpand: false,
                        onClick: function (obj) {
                            $("#selectId").val(obj.data.id);
                            var beginTime = $("#repeatStartTime").ligerDateEditor("getValue");
                            var endTime = $("#repeatEndTime").ligerDateEditor("getValue");
                            //初始化图表
                            getServiceInfo(obj.data.id, beginTime, endTime);
                        },
                        onSuccess: function (data) {

                        }
                    });
                    $("#selectId").val(message[0].id);
                    var beginTime = $("#repeatStartTime").ligerDateEditor("getValue");
                    var endTime = $("#repeatEndTime").ligerDateEditor("getValue");
                    getServiceInfo(message[0].id, beginTime, endTime);
                }
            }
        });
    }

    function getServiceInfo(id, beginTime, endTime) {
        beginTime = new Date(beginTime).format("yyyyMMddhhmm");
        endTime = new Date(endTime).format("yyyyMMddhhmm");
        debugger
        $.ajax({
            type: "GET",
            url: "${contextRoot}/monitor/service/metrics",
            dataType: "json",
            data: {id: id, beginTime: beginTime, endTime: endTime},
            cache: false,
            success: function (re) {
                if (re.successFlg) {
                    //TODO 设置图表
                    var message = JSON.parse(re.message);
//                    var serviceInfo = message.serviceInfo;
//                    $("#serviceName").text(serviceInfo.name);
//                    $("#serviceDescription").text(serviceInfo.description);

                    service.bandwidth(message.data);
                    service.qps(message.data);
                    service.delay(message.data);
                    service.usage(message.data);
//                    service.setJobStatus();
                } else {
                    $.ligerDialog.error(re.message);
                }
            },
            error: function (data) {
                $.ligerDialog.error("Status:" + data.status + "(" + data.statusText + ")");
            }
        });
    }

    var service = {
        switchery: null,
        bandwidth: function (data) {
            // 基于准备好的dom，初始化echarts实例
            var myChart = echarts.init(document.getElementById('main1'));
            if (data != null && data.length > 0) {
                var x = [];
                var inPut = [];
                var outPut = [];
                for (var i = 0; i < data.length; i++) {
                    var createTime = data[i].time.substring(8, 12);
                    x.push(createTime);
                    inPut.push(data[i].in);
                    outPut.push(data[i].out);
                }
                // 指定图表的配置项和数据
                var option = {
                    title: {
                        text: ' 带宽',
                        left: 'center'
                    },
                    tooltip: {
                        trigger: 'axis'
                    },
                    dataZoom: {
                        show: true,
                        start: 50,
                        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',
                    },
                    series: [
                        {
                            name: '输入',
                            type: 'line',
                            data: inPut
                        },
                        {
                            name: '输出',
                            type: 'line',
                            data: outPut
                        },
                    ]
                };
                myChart.setOption(option);
                //设置图例下方的信息
            } else {
                myChart.clear();
            }
        },
        qps: function (data) {
            // 基于准备好的dom，初始化echarts实例
            var myChart = echarts.init(document.getElementById('main2'));
            if (data != null && data.length > 0) {
                var x = [];
                var y = [];
                for (var i = 0; i < data.length; i++) {
                    var createTime = data[i].time.substring(8, 12);
                    x.push(createTime);
                    y.push(data[i].pv);
                }
                // 指定图表的配置项和数据
                var option = {
                    title: {
                        text: ' TPS',
                        left: 'center'
                    },
                    tooltip: {
                        trigger: 'axis'
                    },
                    dataZoom: {
                        show: true,
                        start: 50,
                        end: 100
                    },
                    legend: {
                        left: 'left',
                        data: ['TPS']
                    },
                    xAxis: {
                        type: 'category',
                        name: '时间',
                        splitLine: {show: false},
                        data: x
                    },
                    grid: {
                        left: '3%',
                        right: '4%',
                        bottom: '3%',
                        containLabel: true
                    },
                    yAxis: {
                        type: 'log',
                    },
                    series: [
                        {
                            name: 'TPS',
                            type: 'line',
                            data: y
                        },
                    ]
                };
                myChart.setOption(option);
            }
            else {
                myChart.clear();
            }
        },
        delay: function (data) {
            // 基于准备好的dom，初始化echarts实例
            var myChart = echarts.init(document.getElementById('main3'));
            if (data != null && data.length > 0) {
                var x = [];
                var delay = [];
                var avgDelay = [];
                for (var i = 0; i < data.length; i++) {
                    var createTime = data[i].time.substring(8, 12);
                    x.push(createTime);
                    delay.push(data[i].delay);
                    avgDelay.push(data[i].avgDelay);
                }
                // 指定图表的配置项和数据
                var option = {
                    title: {
                        text: ' 延时',
                        left: 'center'
                    },
                    tooltip: {
                        trigger: 'axis'
                    },
                    dataZoom: {
                        show: true,
                        start: 50,
                        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',
                    },
                    series: [
                        {
                            name: '延时',
                            type: 'line',
                            data: delay
                        },
                        {
                            name: '平均延时',
                            type: 'line',
                            data: avgDelay
                        }
                    ]
                };
                myChart.setOption(option);
            }
            else {
                myChart.clear();
            }
        },
        usage: function (data) {
            // 基于准备好的dom，初始化echarts实例
            var myChart = echarts.init(document.getElementById('main4'));
            if (data != null && data.length > 0) {
                var x = [];
                var y1 = [];
                for (var i = 0; i < data.length; i++) {
                    var createTime = data[i].time.substring(8, 12);
                    x.push(createTime);
                    var count = data[i].pv;
                    var successful = data[i].successful;
                    y1.push(successful / count * 100);
                }

                // 指定图表的配置项和数据
                var option = {
                    title: {
                        text: ' 使用率',
                        left: 'center'
                    },
                    tooltip: {
                        trigger: 'axis',
                        formatter: function (params) {
                            var index = params[0].dataIndex;
                            return params[0].seriesName + "<br/>" +
                                params[0].name + ' : ' + params[0].value + '% (' + data[index].successful + '/' + data[index].pv + ')';
                        }
                    },
                    dataZoom: {
                        show: true,
                        start: 50,
                        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',
                    },
                    series: [
                        {
                            name: '使用率',
                            type: 'line',
                            data: y1
                        }
                    ]
                };
                myChart.setOption(option);
            }
            else {
                myChart.clear();
            }
        },
        //任务状态
        setJobStatus: function (status) {
            var me = this;
            if (status == "1") {
                $('#jobStatusSwitch').attr("checked", true);
                me.switchery.element.checked = true;
                me.switchery.setPosition();
                $("#jobStatus").html('<span class="green job_run">正在运行中...</span>');
            }
            else {

                $('#jobStatusSwitch').removeAttr("checked");
                me.switchery.element.checked = false;
                me.switchery.setPosition();
                $("#jobStatus").html('<span class="red job_stop">运行暂停</span>');
            }
        }
    };


    /*当前时间*/
    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() - 1 * 3600 * 1000);
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var day = date.getDate();
        return year + '-' + month + '-' + day + ' 00:00:00';
    }

</script>