var comImage,runImage,imageName;
var lineIndex=window.parent.document.getElementById("lineIndex").value;
var endTime=getEndTime();
var startTime=getStartTime("年份", endTime);
lineIndex=filterXSS(lineIndex);
startTime=filterXSS(startTime);
endTime=filterXSS(endTime);
$(function () {
    var height=$(window.parent).height()-40;
    $(".picture").css('margin-top','30px');
    $("#run").css('height',height*0.8);
    $("#communicate").css('height',height*0.8);
    getCommunicate(lineIndex,startTime,endTime);
    var tmpstart = getStartTime("月份", endTime);
    getRun(lineIndex,tmpstart,endTime);

})

var lineIndex=window.parent.document.getElementById("lineIndex").value;
var run_Index = 'runtime?line_index='+lineIndex;

$("#query").click(function (){
    var startTime=$("#startTime").val();
    var endTime=$("#endTime").val();
    getCommunicate(lineIndex,startTime,endTime);
    getRun(lineIndex,startTime,endTime);
})

$("#helper").click(function (){
    toHelper("#jcdyxzt");
});

$("#btn_deal").click(function (){
    if(window.top.document.getElementById('runtime') != null){

    }else{
        window.parent.parent.document.getElementById('run_Index').value=run_Index;
        window.top.addTab('runtime?line_index='+lineIndex,'终端运行管理');
    }
});

function getCommunicate(lineIndex,startTime,endTime){
    jQuery.ajax({
        type : 'POST',
        dataType : "json",
        cache : false,
        data :{
            lineIndex:lineIndex,
            startTime:startTime,
            endTime:endTime
        },
        url : '/pqs9200/device/deviceOnline',
        success : function(data) {
            initCommunicate(data);
        }
    });

}

//初始化通信状态
function initCommunicate(interval) {
    var months = new Array();
    var handle = new Array();
    if (interval != null) {
        for (var i = 0; i < interval.length; i++) {
            if (interval[i].month == "01" | i == 0) {
                months[i] = interval[i].month + "\n(" + interval[i].year
                    + ")";
            } else {
                months[i] = interval[i].month;
            }
            handle[i] = interval[i].onlineRate;
        }
    }
    var option = {
        backgroundColor: canvasBG,//背景色,
        title: {
            text: '终端在线率',
            x: 'center',
            textStyle:{
                fontWeight:'normal'
            }
        },
        legend: {
            data: ['在线率'],
            selectedMode: false,
            x: 'left'
        },
        toolbox: {
            show : false
        },
        xAxis : [ {
            type : 'category',
            data : months,
            name : '月份',
            splitLine : {
                show : false
            },
            axisLabel : {
                show : true,
                interval : 0
            }
        } ],
        yAxis: [{
            min: 0,
            max: 100,
            type: 'value',
            name: '在线率(%)'
        }],
        series: [{
            name: '在线率',
            type: 'bar',
            data: handle,
            itemStyle : {
                normal : {
                    color : orange,
                    label : {
                        show : true,
                        textStyle : {
                            label: {show: true, position: 'top'},
                            color : purple
                        }
                    }
                }
            },
            barMaxWidth: barMax
        }]
    };

//    require(["echarts", "echarts/chart/bar"], function (ec) {
    var communicate = echarts.init(document.getElementById('communicate'));
    communicate.setOption(option);
    comImage=communicate.getDataURL();
    communicate.on('click', eConsole);
//    });
}

function eConsole(param) {
    var data = param.name;
    if (typeof data == 'undefined') {
        return;
    }
    if (param.type == 'click') {
        var start = startTime.substring(0,4) + "-" + data.substring(0,2) + "-" + "01";
        var end = startTime.substring(0,4) + "-" + data.substring(0,2) + "-" + "31";
        getRun(lineIndex,start,end);
    }
}
function initRun(list) {
    Highcharts.setOptions({
        global : {
            useUTC : false
        }
    });
    Highcharts.stockChart('run', {
        title: {
            text: '实时运行状态'
        },
        rangeSelector:{
            enabled:false,
        },
        chart:{
            backgroundColor:canvasBG
        },
        exporting: {
            enabled:false
        },
        //导航器各项属性设置
        navigator: {
            margin: 1,
            xAxis: {
                labels: {
                    format: '{value:%Y-%m-%d %H:%M}'
                }
            },
            series: [{
                data: list
            }]
        },
        scrollbar : {
            enabled : false
        },
        exporting:{
            enabled:false
        },
        credits:false,
        colors:[red],
        tooltip: {
            borderColor:grey,
            backgroundColor:'rgba(105,105,105,0.7)',
            style:{
                color:'white',
                fontSize: "15px",
                padding: 10,
            },
            formatter: function () {
                var s = '<b>时间：' + Highcharts.dateFormat('%Y-%m-%d %H:%M', this.x) + '</b>';
                var y=this.y;
                var yd;
                if (y===0){
                    yd='中断';
                }else if (y===-1){
                    yd='退出';
                }else{
                    yd='正常';
                }
                $.each(this.points, function () {
                    s += '<br/>' + this.series.name + ': ' +yd;
                });
                return s;
            },
            shared: true
        },
        xAxis:{
            labels: {
                format: '{value:%Y-%m-%d %H:%M}'
            }
        },
        yAxis: {
            opposite:false,
            allowDecimals:false,
            max:1.1,
            min:-1,
            labels:{
                formatter:function () {
                    var y=this.value;
                    var yd;
                    if (y===0){
                        yd='中断';
                    }else if (y===-1){
                        yd='退出';
                    }else{
                        yd='正常';
                    }
                    return yd;
                }
            }
        },
        legend: {
            align: 'left',
            verticalAlign: 'top',
            enabled:true
        },
        series: [{
            type:'line',
            turboThreshold:0,
            marker: {
                symbol: 'circle'
            },
            name: '运行状态',
            data: list
        }
        ],
    });
}

function getRun(lineIndex,startTime,endTime){
    var layii=0;
    $.ajax({
        type : 'POST',
        dataType : "json",
        cache : false,
        data:{
            lineIndex:lineIndex,
            startTime:startTime,
            endTime:endTime
        },
        beforeSend: function () {
            layii = ityzl_SHOW_LOAD_LAYER_PARENT();
        },
        url : '/pqs9200/device/run',
        success : function(data) {
            var list = [];
            if (data.code===200){
                for( var i = 0; i < data.body.length; i++){
                    var point=[];
                    var xx=data.body[i].time;
                    var yy=data.body[i].sbzt;
                    point = [xx,yy];
                    list.push(point);
                }
                initRun(list);
            }else {

            }
            //***********关闭loading
            ityzl_CLOSE_LOAD_LAYER_PARENT(layii);
        }
    });

}

function refreshState(json){
    var lineIndex=window.parent.document.getElementById("lineIndex").value;

    for(var i =0 ;i < json.length;i++){
        var lineId = json[i].lineid;
        var devFlag = json[i].devflag;

        if(lineId == lineIndex){
            $("#devFlag").val(devFlag);
        }
    }

}

function drawOnCanvas(imageOne, imageTwo,name) {
    var canvas = document.getElementById("canvasipal");
    var Gc = canvas.getContext("2d");
    var drawImg = new Image();
    drawImg.src = imageOne;
    drawImg.onload = function () {
        draw(this);
    };
    function draw(obj) {
        Gc.drawImage(obj, 0, 0, 500, 450);
    };
    var drawImg1 = new Image();
    drawImg1.src = imageTwo;
    drawImg1.onload = function () {
        draw1(this);
    };
    function draw1(obj) {
        Gc.drawImage(obj, 500,0, 500, 450);
        var type = 'png';
        canvasToImageIpal(name,type);
    };

}


function convertCanvasToImage(canvas){
    var image = new Image();
    image.src = canvas.toDataURL("image/png");
    return image;
}

//点击保存图片
$('#saveImage').on('click',function(){
    imageName = '终端运行管理 ';
    var canvasipal = document.getElementById('canvasipal');
    var chartData = $("#run").highcharts().getSVG();
    canvg(canvasipal, chartData);
    runImage = convertCanvasToImage(canvasipal).src;
    document.getElementById("canvasipal").width = 1000;
    document.getElementById("canvasipal").height = 450;
    drawOnCanvas(comImage, runImage,imageName);
});