<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>pytho万能分布式函数调度框架</title>
    <link href="http://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <link href="http://cdn.bootcss.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap-datetimepicker/4.17.47/css/bootstrap-datetimepicker.min.css">
    <link rel="stylesheet" href="{{ url_for('static',filename='assets/css/jquery.mCustomScrollbar.min.css') }}">
    <link rel="stylesheet" href="{{ url_for('static',filename='assets/css/custom.css') }}">
    <style>
        .marginLeft20 {
            margin-left: 20px;
        }

        .liActive {
            background: #FFFF66;
        }

    </style>
</head>
<body>
<div class="page-wrapper">
    <nav class="navbar navbar-inverse navbar-fixed-top">


        <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a href="javascript: void(0)" id="toggle-sidebar" style="color: red"><i class="fa fa-bars"></i></a>
            <a class="navbar-brand" style="padding-left: 60px"><b>python分布式函数调度框架之函数运行结果状态</b></a>
            <a class="navbar-brand" style="padding-left: 160px;color: cyan"><b id="top_text"></b></a>
        </div>
        <div id="navbar" class="navbar-collapse collapse">
            <ul class="nav navbar-nav navbar-right" style="margin-right: 15px;">
                <li><a href="#">rabbitmqAdmin</a></li>
                <li><a href="{{url_for('logout')}}">退出</a></li>
            </ul>
            <!--            <form class="navbar-form navbar-right">-->
            <!--                <input type="text" class="form-control" placeholder="Search...">-->
            <!--            </form>-->

        </div>


    </nav>
    <nav id="sidebar" class="sidebar-wrapper" style="top:50px">
        <div class="sidebar-content">

            <div class="sidebar-search">
                <div>
                    <div class="input-group"><input id="col_name_search" type="text" class="form-control search-menu" placeholder="搜索队列名字。。..." onkeydown="if
                    (event.keyCode===13){searchCols()}"><span class="input-group-addon" id="col_name_search_button" onclick="searchCols()"><i class="fa fa-search"></i></span></div>
                </div>
            </div><!-- sidebar-search  -->
            <div class="sidebar-menu">
                <ul id="ul_cols"></ul>

                <!--                <ul>-->
                <!--                    <div id="div_cols"></div>-->

                <!--                    <li class="header-menu"><span>函数结果集合</span></li>-->
                <!--                    <li><a href="#"><i class="fa fa-tv"></i><span>Menu 1</span></a></li>-->
                <!--                    <li><a href="#"><i class="fa fa-photo"></i><span>Menu 2</span></a></li>-->
                <!--                    <li><a href="#"><i class="fa fa-bar-chart-o"></i><span>Menu 3</span></a></li>-->
                <!--                    <li><a href="#"><i class="fa fa-diamond"></i><span>Menu 4</span></a></li>-->


                <!--                </ul>-->
            </div><!-- sidebar-menu  --></div><!-- sidebar-content  -->
    </nav><!-- sidebar-wrapper  -->
    <main class="page-content">
        <div class="container-fluid" style="margin-top: 40px;">
            {# <h1 style="text-align:center;">Pro sidebar template</h1>#}


            <form class="form-inline" role="form" style="float: left">
                <div class="form-group ">
                    <label for="start_time">起始时间：</label>
                    <input type="text" class="form-control" id="start_time">
                </div>
                <div class="form-group marginLeft20">
                    <label for="end_time">截止时间：</label>
                    <input type="text" class="form-control" id="end_time">
                </div>
                <label for="sucess_status" class="marginLeft20">函数运行状态：</label>
                <select class="form-control" id="sucess_status">
                    <option value="1">全部</option>
                    <option value="2">成功</option>
                    <option value="3">失败</option>

                </select>
                <div class="form-group marginLeft20">
                    <label for="params">函数参数：</label>
                    <input type="text" class="form-control" id="params" placeholder="请输入参数。。">
                </div>
                <button type="button" class="btn btn-default marginLeft20" onclick="document.getElementById('table').style.display = 'block';$('#echartsArea').css('display','none');startRun();queryResult(currentColName,0,true)">查询</button>
            </form>

            <button id="statistic" type="button" class="btn btn-info btn-sm marginLeft20" onclick="statistic()">生成统计表</button>

            <button id="autoFresh" type="button" class="btn btn-success btn-sm marginLeft20" style="float2: right" onclick="startOrStop()">自动刷新中</button>
            <p id="echartsInfoTex" style="clear: both;margin-top: 30px;background-color:yellowgreen ;width:600px;color: white;text-shadow: 0 0 10px black;font-size: 16px;display: none"></p>
            <p id="resultInfoTex" style="clear: both;margin-top: 30px;background-color:green;width:600px;color: white;text-shadow: 0 0 10px black;font-size: 16px;"></p>
            <div id = echartsArea style="display: None">
            <div id="st4" style="width: 100%;height:600px;margin-top:60px;"></div>
            <div id="st3" style="width: 100%;height:600px;margin-top:60px;"></div>
            <div id="st2" style="width: 100%;height:600px;margin-top:60px;"></div>
            <div id="st1" style="width: 100%;height:600px;margin-top:60px;"></div>
            </div>
            <div class="table-responsive">
                <table id="table" class="table table-striped">

                </table>
            </div>
        </div>


    </main><!-- page-content" --></div><!-- page-wrapper -->
<script src="{{ url_for('static',filename='js/jquery-1.11.0.min.js') }}" type="text/javascript"></script>
<script src="http://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>


<script src="https://cdn.bootcss.com/moment.js/2.24.0/moment-with-locales.js"></script>
<script src="https://cdn.bootcss.com/bootstrap-datetimepicker/4.17.47/js/bootstrap-datetimepicker.min.js"></script>
<script type="text/javascript" src="https://cdn.bootcss.com/echarts/3.3.0/echarts.js"></script>

<script src="{{ url_for('static',filename='assets/js//jquery.mCustomScrollbar.concat.min.js') }}"></script>
<script src="{{ url_for('static',filename='assets/js/custom.js') }}"></script>

<script>


    String.prototype.format = function () {
        var values = arguments;
        return this.replace(/\{(\d+)\}/g, function (match, index) {
            if (values.length > index) {
                return values[index];
            } else {
                return "";
            }
        });
    };

    function dateToString(date) {
        const year = date.getFullYear();
        let month = date.getMonth() + 1;
        let day = date.getDate();
        let hour = date.getHours();
        let minute = date.getMinutes();
        let second = date.getSeconds();
        month = month > 9 ? month : ('0' + month);
        day = day > 9 ? day : ('0' + day);
        hour = hour > 9 ? hour : ('0' + hour);
        minute = minute > 9 ? minute : ('0' + minute);
        second = second > 9 ? second : ('0' + second);
        return year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
    }

    //昨天的时间
    var day1 = new Date();
    day1.setDate(day1.getDate() - 2);

    //明天的时间
    var day2 = new Date();
    day2.setDate(day2.getDate() + 1);

    $("#start_time").val(dateToString(day1));
    $("#end_time").val(dateToString(day2));
    useAsync = false;

    function searchCols() {
        // console.info($("#col_name_search").val());
        $.ajax({
            url: "{{ url_for('query_cols_view')}}", data: {col_name_search: $("#col_name_search").val()}, async: useAsync, success: function (result, status) {
                console.info(result);
                if (useAsync === false) {
                    currentColName = result[0].collection_name;
                }
                var html = "";
                for (var item of result) {
                    // console.info(item);
                    html += '<li onclick="queryResult(\'{0}\' ,0,true)"><a href="#"><span > {1}</span><span class="badge" style="margin-top: 0;"> {2}</span></a></li>'.format(item.collection_name, item.collection_name, item.count);
                }
                $("#ul_cols").html(html);

                $("#ul_cols").find("li").on("click", function () {
                    var $index = $(this).index();//获取点击当前的索引
                    $(this).addClass("liActive").siblings("li").removeClass("liActive");//为当前点击元素添加class,移除相邻兄弟元素li的active
                    console.log($index);
                });
            }
        });
    }

    searchCols();
    useAsync = true;

    function queryResult(col_name, page, manualOperate) {
        currentColName = col_name;
        if (manualOperate === true){
            document.getElementById('table').style.display = 'block';
        }

        $.ajax({
            url: "{{ url_for('query_result_view')}}", data: {
                col_name: col_name, start_time: $("#start_time").val(),
                end_time: $("#end_time").val(), is_success: $("#sucess_status").val(), function_params: $("#params").val(), page: page
            }, async: useAsync, success: function (result, status) {
                // console.info(result);

                var html = '  <thead>\n' +
                    '                    <tr>\n' +
                    '                        <th>执行机器-进程-脚本</th>\n' +
                    '                        <th>函数执行完成时间</th>\n' +
                    '                        <th>函数名称</th>\n' +
                    '                        <th>函数入参</th>\n' +
                    '                        <th>函数结果</th>\n' +
                    '                        <th>消耗时间</th>\n' +
                    '                        <th>执行次数</th>\n' +
                    '                        <th>是否成功</th>\n' +
                    '                        <th>错误原因</th>\n' +

                    '                        <th>消息发布时间</th>\n' +
                    '                        <th>线程(协程)数</th>\n' +
                    '                    </tr>\n' +
                    '                    </thead>' +
                    '<tbody>';
                for (var item of result) {
                    // console.info(item);
                    var displayLevel = "success";
                    if (item.run_times > 1) {
                        displayLevel = "warning";
                    }

                    if (item.success === false) {
                        displayLevel = "danger";
                    }
                    var tr = ' <tr class="{0}">\n' +

                        '                        <td>{1}</td>\n' +
                        '                        <td>{2}</td>\n' +
                        '                        <td>{3}</td>\n' +
                        '                        <td>{4}</td>\n' +
                        '                        <td>{5}</td>\n' +
                        '                        <td>{6}</td>\n' +
                        '                        <td>{7}</td>\n' +
                        '                        <td>{8}</td>\n' +
                        '                        <td>{9}</td>\n' +
                        '                        <td>{10}</td>\n' +
                        '                        <td>{11}</td>\n' +

                        '                    </tr>';
                    var successText = item.success === true ? "成功" : "失败";
                    tr = tr.format(displayLevel, item.host_process + ' - ' + item.script_name, item.insert_time_str, item.function, item.params_str, item.result,
                        item.time_cost, item.run_times, successText, item.exception, item.publish_time_str, item.total_thread);
                    html += tr;
                }
                html += '</tbody>';
                $("#table").html(html);

                // document.getElementById('echartsArea').style.display = 'none';


            }
        });
        if (manualOperate === true) {
            updateQueryText()
        }
    }

    function updateQueryText() {

        $.ajax({
            url: "{{ url_for('speed_stats')}}", data: {
                col_name: currentColName, start_time: $("#start_time").val(),
                end_time: $("#end_time").val()
            }, async: useAsync, success: function (result, status) {
                var msg = '所选查询时间范围内运行成功了{0}次,失败了{1}次'.format(result.success_num, result.fail_num);
                console.info(msg);
                $('#resultInfoTex').html(msg);
            }
        })
    }

    queryResult(currentColName, 0, true);
    setInterval(updateQueryText, 30000);

    function updateTopText() {
        var t1 = new Date(new Date().getTime() - 60000);
        var t2 = new Date();
        $.ajax({
            url: "{{ url_for('speed_stats')}}", data: {
                col_name: currentColName, start_time: dateToString(t1), end_time: dateToString(t2)
            }, async: useAsync, success: function (result, status) {
                var msg = '{0}队列,最近一分钟内运行成功了{1}次,失败了{2}次'.format(currentColName, result.success_num, result.fail_num);
                console.info(msg);
                $('#top_text').text(msg);
            }
        })
    }

    updateTopText();

    setInterval(updateTopText, 30000);

    function autoFreshResult() {
        queryResult(currentColName, 0, false);
    }

    // setInterval(autoFreshResult, 30000);

    iid = setInterval(autoFreshResult, 5000);
    runStatus = 1;

    function startRun() {
        $("#autoFresh").text("自动刷新中");
        $("#autoFresh").removeClass("btn-danger");
        $("#autoFresh").addClass("btn-success");
        iid = setInterval(autoFreshResult, 5000);
        runStatus = 1;
    }

    function stopRun() {
        $("#autoFresh").text("暂停刷新了");
        $("#autoFresh").removeClass("btn-success");
        $("#autoFresh").addClass("btn-danger");
        clearInterval(iid);
        runStatus = 0;
    }

    function startOrStop() {
        if (runStatus === 1) {
            stopRun();
        } else {
            startRun();
        }
    }

    class Person {//定义了一个名字为Person的类
        constructor(name, age) {//constructor是一个构造方法，用来接收参数
            this.name = name;//this代表的是实例对象
            this.age = age;
        }

        say() {//这是一个类的方法，注意千万不要加上function
            return "我的名字叫" + this.name + "今年" + this.age + "岁了";
        }
    }

    var obj = new Person("laotie", 88);
    console.log(obj.say());//我的名字叫laotie今年88岁了

    function statistic() {
        $('#echartsInfoTex').html('生成统计表中，需要一段时间。。。。');
        $("#echartsInfoTex").css('display','block');
        $("#echartsArea").css('display','block');
        stopRun();
        document.getElementById('table').style.display = "none";
        $.ajax({
            url: "{{ url_for('speed_statistic_for_echarts')}}", data: {
                col_name: currentColName
            }, async: useAsync, success: function (result, status) {
                // var msg = '{0}队列,最近一分钟内运行成功了{1}次,失败了{2}次'.format(currentColName, result.success_num, result.fail_num);
                console.info(result);
                _buildOneChart('st1', '最近10天的消费情况', '运行次数', result['recent_10_days']['time_arr'], result['recent_10_days']['count_arr']);
                _buildOneChart('st2', '最近24小时的消费情况', '运行次数', result['recent_24_hours']['time_arr'], result['recent_24_hours']['count_arr']);
                _buildOneChart('st3', '最近60分钟的消费情况', '运行次数', result['recent_60_minutes']['time_arr'], result['recent_60_minutes']['count_arr']);
                _buildOneChart('st4', '最近60秒的消费情况', '运行次数', result['recent_60_seconds']['time_arr'], result['recent_60_seconds']['count_arr']);
                $("#echartsInfoTex").css('display','none');

                // $('#top_text').text(msg);
            }
        });


    }

    function _buildOneChart(elementId, titelText, legendData, xData, yData) {

        var myChart = echarts.init(document.getElementById(elementId));



        // 指定图表的配置项和数据
        var option = {
            title: {
                text: titelText
            },
            tooltip: {},
            legend: {
                data: [legendData]
            },

            xAxis: {
                type: 'category',
                data: xData,
                axisLabel: {
                    rotate: 90,

                    interval: 0,

                    // formatter: function (value) {
                    //
                    //     console.info(value);
                    //     var v =  value.split("").join("\n");
                    //     console.info(v);
                    //     return v;
                    // },

                    // show: true, interval: 'auto', inside: false, rotate: 90, margin: 8, formatter: null, showMinLabel: null, showMaxLabel: null,

                },

            },

            yAxis: {},
            series: [{
                name: legendData,
                type: 'bar',
                data: yData
            }]
        };

        // 使用刚指定的配置项和数据显示图表。
        myChart.setOption(option);
        console.info(elementId);


    }


</script>
</body>
</html>