(function($) {
    
    /* "use strict" */
    var dlabChartlist = function() {
        var MemUsage =0.0;
        var CpuUsage =0.0;
        var ThisCoinType="";
        var intervalId = null;
        var ModePandelHistoryDay = 1;
        var ModeWorkHistoryDay = 1;
        // var DiskUsage =0.0;
        // var realTimeTcpCnt =0.0;
        // 获取币种
        var GetCoinType = function(){
            var xhr = new XMLHttpRequest();
            xhr.open('GET','api/coinTypeGet',false);
            xhr.send();
            if (xhr.readyState == 4 && xhr.status == 200) {
                var data = xhr.responseText;
                data = JSON.parse(data);
                if(data.status == "ok"){
                    ThisCoinType = data.data;
                }
            }
        }
        //内存CPU统计
        var flotRealtimeCpuAndMemFunc = function(){
            document.getElementById("flotRealtimeCpuAndMem").innerHTML ="";
            if(intervalId!=null){
                clearInterval(intervalId);
            }
            var dataMem = [], totalPoints = 50;
            var dataCpu = [];
            function getRandomDataMem() {
                if (dataMem.length > 0)
                dataMem = dataMem.slice(1);
                while (dataMem.length < totalPoints) {
                    dataMem.push(MemUsage);
                }
                var res = [];
                for (var i = 0; i < dataMem.length; ++i) {
                    res.push([i, dataMem[i]])
                }
                return res;
            }
            function getRandomDataCpu() {
                if (dataCpu.length > 0)
                dataCpu = dataCpu.slice(1);
                while (dataCpu.length < totalPoints) {
                    dataCpu.push(CpuUsage);
                }
                var res = [];
                for (var i = 0; i < dataCpu.length; ++i) {
                    res.push([i, dataCpu[i]])
                }
                return res;
            }
            // Set up the control widget
            var updateInterval = 500;
            var plot5 = $.plot('#flotRealtimeCpuAndMem', [{data:getRandomDataMem(),label:"内存"},{data:getRandomDataCpu(),label:"CPU"}], {
                colors: ['#17A2BB','#FF910F'],
                series: {
                    lines: {
                        show: true,
                        lineWidth: 0,
                        fill: 0.9
                    },
                    shadowSize: 0	// Drawing is faster without shadows
                },
                grid: {
                    borderColor: 'transparent',
                    borderWidth: 1,
                    labelMargin: 5,
                    hoverable: true, //鼠标移动
                    clickable: true, //鼠标点击
                },
                xaxis: {
                    color: 'transparent',
                    show: false,
                    font: {
                        size: 10,
                        color: '#fff'
                    }
                },
                yaxis: {
                    min: 0,
                    max: 100,
                    //color: 'transparent',
                    font: {
                        size: 15,
                        color: '#f0f0f'
                    }
                },
                cursor: {
                    // 是否显示光标，若为true，光标默认为十字
                    show: true
                  },
                legend: {
                    show: true,
                }
            });
            intervalId = window.setInterval(function clock() {
                update_plot5();
            }, updateInterval);
            function update_plot5() {
                plot5.setData([{data:getRandomDataMem(),label:"内存"},{data:getRandomDataCpu(),label:"CPU"}]);
                plot5.draw();
            }
            $("#flotRealtimeCpuAndMem").bind("plothover", function(event, pos, item) {
                if (item) {
                    // var x = item.datapoint[0].toFixed(2),
                     var  y = item.datapoint[1].toFixed(2);
                    $("#linechart-tooltip").html(item.series.label +':'+ y+'%').css({ top: item.pageY + 5, left: item.pageX + 5 }).fadeIn(200);
                } else {
                    $("#linechart-tooltip").hide();
                }
            });
            $("<div id='linechart-tooltip' class='chart-tooltip'></div>").appendTo("body");
        }
        function CalHash(v){
            var tmptmp = v.toFixed(2)+"Sol";
            // sol m g t p e
            if( v>1000){
                tmptmp = (v/(1000)).toFixed(2)+"KH";
            }
            if( v>1000*1000){
                tmptmp = (v/(1000*1000)).toFixed(2)+"MH";
            }
            if( v>1000*1000*1000){
                tmptmp = (v/(1000*1000*1000)).toFixed(2)+"GH";
            }
            if( v>1000*1000*1000*1000){
                tmptmp = (v/(1000*1000*1000*1000)).toFixed(2)+"TH";
            }
            if( v>1000*1000*1000*1000*1000){
                tmptmp = (v/(1000*1000*1000*1000*1000)).toFixed(2)+"PH";
            }
            if( v>1000*1000*1000*1000*1000*1000){
                tmptmp = (v/(1000*1000*1000*1000*1000*1000)).toFixed(2)+"PH";
            }
           return tmptmp;
        }
        //历史数据统计
        var HistoryStatistical = function(coinType,date) {
            var HashRateOptions = {
                series: [{
                    name: '矿机',
                    data: [0],
                     color: 'rgba(55,142,240,0.7)',
                },{
                    name: '算力',
                    data: [0],
                    color: 'rgba(241,92,128,0.7)',
                },{
                    name: '平均延迟',
                    data: [0],
                    color: 'rgba(43,144,143,0.7)',
                } ,{
                    name: '抽水转换率',
                    data: [0],
                    color: 'rgba(247,163,92,0.7)',
                }  ],
                chart: {
                    type: 'line',
                    height: 300,
                    toolbar: {
                        show: false,
                    },
                },
                plotOptions: {
                    bar: {
                        horizontal: false,
                        columnWidth: '70%',
                        endingShape: 'rounded'
                    },
                },
                colors: ['#886CC0'],
                dataLabels: {
                    enabled: false,
                },
                markers: {
                    shape: "circle",
                },
                legend: {
                    show: true,
                },
                stroke: {
                    show: true,
                    width: 5,
                    curve: 'smooth',
                    colors: ['var(--primary)'],
                },
                grid: {
                    borderColor: '#eee',
                    show: true,
                    xaxis: {
                        lines: {
                            show: true,
                        }
                    },
                    yaxis: {
                        lines: {
                            show: false,
                        }
                    },
                },
                xaxis: {
                    categories: [],
                    show: false,
                    labels: {
                        style: {
                            colors: '#7E7F80',
                            fontSize: '13px',
                            fontFamily: 'Poppins',
                            fontWeight: 100,
                            cssClass: 'apexcharts-xaxis-label',
                        },
                        show: false
                    },
                    crosshairs: {
                        show: false,
                    }
                },
                yaxis: [{
                    show: false,
                    labels: {
                        offsetX: -15,
                        style: {
                            colors: '#7E7F80',
                            fontSize: '14px',
                            fontFamily: 'Poppins',
                            fontWeight: 100,
                        },
                        formatter: function(y) {
                            return y.toFixed(0) + "台";
                        },
                    },
                },
                {
                    show: false,
                    labels: {
                        offsetX: -15,
                        style: {
                            colors: '#7E7F80',
                            fontSize: '14px',
                            fontFamily: 'Poppins',
                            fontWeight: 100,
                        },
                        formatter: function(y) {
                            return CalHash(y);
                        },
                    },
                },
                {
                    show: false,
                    labels: {
                        offsetX: -15,
                        style: {
                            colors: '#7E7F80',
                            fontSize: '14px',
                            fontFamily: 'Poppins',
                            fontWeight: 100,
                        },
                        formatter: function(y) {
                            return y.toFixed(2) +"ms";
                        },
                    },
                },
                {
                    show: false,
                    labels: {
                        offsetX: -15,
                        style: {
                            colors: '#7E7F80',
                            fontSize: '14px',
                            fontFamily: 'Poppins',
                            fontWeight: 100,
                        },
                        formatter: function(y) {
                            return y.toFixed(2)+"%";
                        },
                    },
                }],
                fill: {
                    opacity: 1,
                    colors: '#FAC700'
                },
                tooltip: {
                    y: [{
                        formatter: function(val) {
                            return val + "台";
                        }
                    },
                    {
                        formatter: function(val) {
                            return CalHash(val);
                        }
                    },
                    {
                        formatter: function(val) {
                            return val.toFixed(2)+"ms";
                        }
                    },
                    {
                        formatter: function(val) {
                            return val.toFixed(2)+"%";
                        }
                    }]
                }
            };
            var chartBarHashRate = new ApexCharts(document.querySelector("#HistoryHashrate"), HashRateOptions);
            var xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function() {
                if (xhr.readyState == 4 && xhr.status == 400) {
                    window.location.href="/login";
                    return;
                }
                if (xhr.readyState == 4 && xhr.status == 200) {
                    var data = xhr.responseText;
                    data = JSON.parse(data);
                    var index=0;
                    for (var p in data.worker_info) {
                        if(p%ModeWorkHistoryDay==0){
                            HashRateOptions.series[0].data[index] = data.worker_info[p].worker_on_line_cnt;
                            HashRateOptions.series[1].data[index] = data.worker_info[p].hash_rate;
                            HashRateOptions.series[2].data[index] = data.worker_info[p].average_latency;
                            HashRateOptions.series[3].data[index] = data.worker_info[p].average_fee_point*100;
                            HashRateOptions.xaxis.categories[index] = timestampToTime(data.worker_info[p].time);
                            index++;
                        }
                    }
                    document.getElementById("HistoryHashrate").innerHTML ="";
                    // HashRateOptions.yaxis[0].max = 50;
                    // HashRateOptions.yaxis[1].max = 10;
                    chartBarHashRate.render();
                }
            }
            xhr.open('GET', 'api/workerInfoHistory?coinType='+coinType+'&date='+date, true);
            xhr.send();
        }
        function secondsFormat(s) {
            var day = Math.floor(s / (24 * 3600)); // Math.floor()向下取整 
            var hour = Math.floor((s - day * 24 * 3600) / 3600);
            var minute = Math.floor((s - day * 24 * 3600 - hour * 3600) / 60);
            var second = s - day * 24 * 3600 - hour * 3600 - minute * 60;
            return day + "天" + hour + "时" + minute + "分" + second + "秒";
        }
        //时时数据统计
        var RealTimeStatistical = function() {
            var xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function() {
                if (xhr.readyState == 4 && xhr.status == 400) {
                    window.location.href="/login";
                    return;
                }
               // var ToTalClientI=0;
                //var ToTalFrontProxyCntI=0;
                var ToTalTotalShareI=0;
               // var ToTalhours_1_total_shareI=0;
                if (xhr.readyState == 4 && xhr.status == 200) {
                    var data = xhr.responseText;
                    data = JSON.parse(data);
                    //ToTalClientI = data.coin[0].total_client;
                    ToTalTotalShareI = data.coin[0].total_share;
                    //ToTalFrontProxyCntI = data.general.total_client;
                    //ToTalhours_1_total_shareI = data.coin[0].hours_1_total_share;
                    MemUsage = parseFloat(Number(data.memory_usage+1.0).toFixed(2));
                    CpuUsage = parseFloat(Number(data.cpu_usage+1.0).toFixed(2));
                    document.getElementById("TotalWorker").innerHTML = "矿机:"+ '<span class="text-success">'+data.coin[0].total_on_line_client+'</span> / '+'<span class="text-danger">'+data.coin[0].total_off_on_line_client+'</span> 台';
                    document.getElementById("TotalHashRate").innerText =  "算力:"+CalHash(data.coin[0].total_hash_rate);
                    document.getElementById("AverageFeePont").innerText =  "抽水转换率:"+(data.coin[0].average_fee_point*100).toFixed(2) +"%";
                    document.getElementById("AverageLatency").innerText = "平均延迟:"+ data.coin[0].average_latency.toFixed(1)+"ms";
                    document.getElementById("TotalShares").innerHTML = "总提交:"+'<span class="text-success">'+ToTalTotalShareI+'</span> / '+'<span class="text-danger">'+data.coin[0].total_invalid_share+'</span> 份';
                    document.getElementById("MachineUsage").innerText = "CPU:"+CpuUsage+"% / "+"内存:"+MemUsage+"%";
                    document.getElementById("PorttranSysRunTime").innerText = "运行:"+secondsFormat(data.run_time);
                    // DiskUsage = parseFloat(Number(data.disk_usage).toFixed(2));
                    // realTimeTcpCnt = data.total_tcp_cnt;
                }
            }
            var intervalId = window.setInterval(function clock() {
                xhr.open('GET', 'api/statistical?coinType='+ThisCoinType, true)
                xhr.send();
            }, 3 * 1000);
            xhr.open('GET', 'api/statistical?coinType='+ThisCoinType, true)
            xhr.send();
        }
        function timestampToTime(timestamp) {
            var date = new Date(timestamp * 1000);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
            var Y = date.getFullYear() + '-';
            var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
            var D = date.getDate() + ' ';
            var h = date.getHours() + ':';
            var m = date.getMinutes();
            //var s = date.getSeconds();
            return Y+M+D+h+m;
        }
        var lineChart2 = function(date){
            var op = {
                element: 'flotRealtimeCpuAndMem',
                data: [],
                xkey: 'period',
                ykeys: [],
                labels: ['内存', 'CPU'],
                fillOpacity: 0.95,
                // pointStrokeColors: ['rgb(16, 202, 147)', 'rgb(255, 92, 0)'],
                behaveLikeLine: true,
                gridLineColor: 'transparent',
                lineWidth: 0,
                hideHover: 'auto',
                lineColors: ['rgb(16, 202, 147)', 'rgb(255, 92, 0)'],
                resize: true,
                pointSize: 0,
                axes: false
            };
            var xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function() {
                if (xhr.readyState == 4 && xhr.status == 400) {
                    window.location.href="/login";
                    return;
                }
                if (xhr.readyState == 4 && xhr.status == 200) {
                    var data = xhr.responseText;
                    data = JSON.parse(data);
                    var index=0;
                    for (var p in data.panel_info) {
                        if(p%ModePandelHistoryDay==0){
                            var op2 = {
                                period: timestampToTime(data.panel_info[p].time),
                                memory_usage: data.panel_info[p].memory_usage.toFixed(2),
                                cpu_usage: (data.panel_info[p].cpu_usage+1).toFixed(2)
                            };
                            if (data.panel_info[p].memory_usage > data.panel_info[p].cpu_usage){
                                op.ykeys[0] = 'memory_usage';
                                op.ykeys[1] = 'cpu_usage';
                            }else{
                                op.ykeys[1] = 'memory_usage';
                                op.ykeys[0] = 'cpu_usage';
                            }
                            op.data[index]=op2;
                            index++;
                        }
                    }
                    document.getElementById("flotRealtimeCpuAndMem").innerHTML ="";
                    Morris.Area(op);
                }
            }
            xhr.open('GET', 'api/statisticalPanelHistory?date='+date, true)
            xhr.send();
        }
        document.getElementById("qPanelRealTime").onclick=function(){
            flotRealtimeCpuAndMemFunc();
        }
        document.getElementById("qPanelhistory_1day").onclick=function(){
            ModePandelHistoryDay = 1;
            lineChart2("1day");
            if(intervalId!=null){
                clearInterval(intervalId);
            }
        }
        document.getElementById("qPanelhistory_7day").onclick=function(){
            ModePandelHistoryDay = 7;
            lineChart2("7day");
            if(intervalId!=null){
                clearInterval(intervalId);
            }
        }
        document.getElementById("qPanelhistory_30day").onclick=function(){
            ModePandelHistoryDay = 30;
            lineChart2("30day");
            if(intervalId!=null){
                clearInterval(intervalId);
            }
        }
        document.getElementById("qWorkhistory_1day").onclick=function(){
            ModeWorkHistoryDay = 1;
            HistoryStatistical(ThisCoinType,"1day");
        }
        document.getElementById("qWorkhistory_7day").onclick=function(){
            ModeWorkHistoryDay = 7;
            HistoryStatistical(ThisCoinType,"7day");
        }
        document.getElementById("qWorkhistory_30day").onclick=function(){
            ModeWorkHistoryDay = 30;
            HistoryStatistical(ThisCoinType,"30day");
        }
        return {
            init: function() {},
            load: function() {
                GetCoinType();
                HistoryStatistical(ThisCoinType,"1day");
                RealTimeStatistical();
                flotRealtimeCpuAndMemFunc();
            },
            resize: function() {}
        }
    }();
    jQuery(window).on('load', function() {
        setTimeout(function() {
            dlabChartlist.load();
        }, 1000);
    });
})(jQuery);