var picHeight,areaImage,companyImage;
var areLength;//区域的个数
var companyLength;//厂家个数
var areaResult=null;
var companyResult=null;
$(function () {
    var i;
    var endTime = getEndTime();
    var startTime = getMonthStartTime(endTime);
    picHeight=$(window).height()*0.5-5;
    $.ajax({
        url:'/pqs9200/overview/deviceStatus',
        type:'post',
        dataType:'json',
        data: {
            startTime: startTime,
            endTime: endTime
        },
        beforeSend: function () {
            i = ityzl_SHOW_LOAD_LAYER();
        },
        success:function (data) {
            if (data.code===500|data.body===null){
                companyResult=null;
                areaResult=null;
            }else{
                companyResult=data.body.interval;
                areaResult=data.body.area;
            }
            startQuery();
            //***********关闭loading
            ityzl_CLOSE_LOAD_LAYER(i);
        }
    })
})

//获取起始日期
function getMonthStartTime(endTime) {
    var sep = "-";
    var arr = endTime.split("-");
    var year = arr[0];
    var month = arr[1];
    var date = "01";
    var startTime = year + sep + month + sep + date;
    return startTime;
}

//按区域进行统计
function drawAreaPic (area,intervals) {
    //给div指定宽高
    $("#area").css("height",picHeight);
    var run=[];
    var breaks=[];
    var shutdown=[];
    var areas=[];
    var rate=[];
    if(null!=area){
        for(var i=0;i<area.length;i++){
            areas[i]=area[i].name+"\n("+area[i].amounts+")";
            var monitors=area[i].amounts;
            if(Number(monitors)===0){
                var singleData={};
                var normal={};
                var itemStyle={};
                singleData.value=3.1415;
                normal.color=noMonitor;
                itemStyle.normal=normal;
                singleData.itemStyle=itemStyle;
                run[i]=singleData;
                rate[i]=singleData;
                breaks[i]=0;
                shutdown[i]=0;
            }else{
                run[i]=area[i].status.normal;
                breaks[i]=area[i].status.breaks;
                shutdown[i]=area[i].status.shutdown;
                var onlineRate;
                onlineRate=Number(area[i].online);
                var singleData={};
                var normal={};
                var itemStyle={};
                normal.color = getColor(onlineRate);
                if(onlineRate<3.1414){
                    singleData.value = 3.1415;
                    // item.actual = onlineRate;
                }else{
                    singleData.value = onlineRate;
                }
                itemStyle.normal=normal;
                singleData.itemStyle=itemStyle;
                rate[i]=singleData;
            }
        }
    }
    var option = {
        backgroundColor: canvasBG,//背景色
        title: {
            text: '区域',
            x: 'center'
        },
        color:[green,yellow,grey],
        legend: {
            x: 'left',
            data: ['投运','检修','退运'],
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            },
            formatter: function (params) {
                var tips="";
                tips+=params[0].name;
                var value=params[0].value;
                if(value===3.1415){
                    tips+='<br/>投运 : /';
                    tips+='<br/>检修 : /';
                    tips+='<br/>退运 : /';
                    tips+='<br/>在线率 : /';
                }else{
                    for (var i = 0; i < params.length; i++) {
                        tips+='<br/>'+params[i].seriesName+' : '+params[i].value;
                    }
                }
                return tips;
            }
        },
        //控制图标在dataroom中的位置大小
        grid: {
            left: '1%',
            right: '11%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: [{
            type: 'category',
            data: areas,
            name: '地区\n(终端个数)\n',
            splitLine: {
                show: false
            },
            axisLabel : {
                show:true,
                interval: intervals
            }
        }],
        yAxis: [{
            type: 'value',
            name: '%',
            max:100
        }],
        series: [{
            name: '投运',
            type: 'bar',
            stack: 'sum',
            barMaxWidth: barMax,
            data: run
        }, {
            name: '检修',
            type: 'bar',
            stack: 'sum',
            barMaxWidth:barMax,
            data: breaks
        },{
            name: '退运',
            type: 'bar',
            stack: 'sum',
            barMaxWidth: barMax,
            data: shutdown
        },{
            name: '在线率',
            type: 'bar',
            barGap: 0,
            barMaxWidth: barMax,
            data: rate
        }]
    };
    var district = echarts.init(document.getElementById('area'));
    district.setOption(option);
    areaImage=district.getDataURL();
}

//填充区域表格
function initAreaTable(data) {
    var height=picHeight-80;
    if(data==null){
        data=[];
    }else{
        //计算总计
        var name='总计';
        var amounts=0;
        for(var i=0;i<data.length;i++){
            amounts=Number(data[i].amounts)+amounts;
        }
        var area={};
        area.name=name;
        area.amounts=amounts;
        var status={};
        status.normalData='/';
        status.breaksData='/';
        status.shutdownData='/';
        area.status=status;
        area.online='/';
        data.push(area);
        data.reverse();
    }
    $("#areaTable").DataTable({
        data: data,
        autoWidth:false,
        order:[1,"desc"],
        columnDefs : [
            { orderable: false, targets: [0,2,3,4] }
        ],
        paging:false,
        lengthChange: false,
        searching:false,
        destroy : true,
        scrollY: height,
        info:false,
        language : {
            url:'/pqs9200/json/chine.json',
        },
        columns: [
            { data: 'name' },
            { data: 'amounts'},
            {data:'status.normalData', render:function (data, type, full, meta) {
                    if(Number(full.amounts)===0){
                        return "/";
                    }
                    return data;
                }},
            {data:'status.breaksData', render:function (data, type, full, meta) {
                    if(Number(full.amounts)===0){
                        return "/";
                    }
                    return data;
                }},
            {data:'status.shutdownData', render:function (data, type, full, meta) {
                    if(Number(full.amounts)===0){
                        return "/";
                    }
                    return data;
                }},
            {data:'online', render:function (data, type, full, meta) {
                    if(Number(data)===3.1415){
                        return "/";
                    }else if(Number(data)===3.14159){
                        return "（暂无数据）";
                    }else{
                        return data;
                    }
                }},
        ],
    })
}


//按终端厂家进行统计
function  drawCompanyPic(companys,intervals) {
    $("#company").css("height",picHeight);
    var run=[];
    var breaks=[];
    var shutdown=[];
    var areas=[];
    var rate=[];
    if(null!=companys){
        for(var i=0;i<companys.length;i++){
            areas[i]=companys[i].name+"\n("+companys[i].amounts+")";
            var monitors=companys[i].amounts;
            if(Number(monitors)===0){
                var singleData={};
                var normal={};
                var itemStyle={};
                singleData.value=3.1415;
                normal.color=noMonitor;
                itemStyle.normal=normal;
                singleData.itemStyle=itemStyle;
                run[i]=singleData;
                rate[i]=singleData;
                breaks[i]=0;
                shutdown[i]=0;
            }else{
                run[i]=companys[i].status.normal;
                breaks[i]=companys[i].status.breaks;
                shutdown[i]=companys[i].status.shutdown;
                var onlineRate;
                onlineRate=Number(companys[i].online);
                var singleData={};
                var normal={};
                var itemStyle={};
                normal.color = getColor(onlineRate);
                if(onlineRate<3.1414){
                    singleData.value = 3.1415;
                }else{
                    singleData.value = onlineRate;
                }
                itemStyle.normal=normal;
                singleData.itemStyle=itemStyle;
                rate[i]=singleData;
            }
        }
    }

    var option = {
        backgroundColor: canvasBG,//背景色
        title: {
            text: '终端厂家',
            left :'46%'
        },
        color:[green,yellow,grey],
        legend: {
            x: 'left',
            data: ['投运','检修','退运'],
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            },
            formatter: function (params) {
                var tips="";
                tips+=params[0].name;
                var value=params[0].value;
                if(value===3.1415){
                    tips+='<br/>投运 : /';
                    tips+='<br/>检修 : /';
                    tips+='<br/>退运 : /';
                    tips+='<br/>在线率 : /';
                }else{
                    for (var i = 0; i < params.length; i++) {
                        tips+='<br/>'+params[i].seriesName+' : '+params[i].value;
                    }
                }
                return tips;
            }
        },
        //控制图标在dataroom中的位置大小
        grid: {
            left: '1%',
            right: '11%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: [{
            type: 'category',
            data: areas,
            name: '终端厂家\n(终端个数)\n',
            splitLine: {
                show: false
            },
            axisLabel : {
                show:true,
                interval: intervals
            }
        }],
        yAxis: [{
            type: 'value',
            name: '%',
            max:100
        }],
        series: [{
            name: '投运',
            type: 'bar',
            stack: 'sum',
            barMaxWidth: barMax,
            data: run
        }, {
            name: '检修',
            type: 'bar',
            stack: 'sum',
            barMaxWidth: barMax,
            data: breaks
        },{
            name: '退运',
            type: 'bar',
            stack: 'sum',
            barMaxWidth: barMax,
            data: shutdown
        },{
            name: '在线率',
            type: 'bar',
            barGap: 0,
            barMaxWidth: barMax,
            data: rate
        }]
    };
    var factory = echarts.init(document.getElementById('company'));
    factory.setOption(option);
    companyImage=factory.getDataURL();
}
//填充终端厂家表格
function initCompanyTable(data) {
    var height=picHeight-50;
    if(data==null){
        data=[];
    }else{
        //计算总计
        var name='总计';
        var amounts=0;
        for(var i=0;i<data.length;i++){
            amounts=Number(data[i].amounts)+amounts;
        }
        var area={};
        area.name=name;
        area.amounts=amounts;
        var status={};
        status.normalData='/';
        status.breaksData='/';
        status.shutdownData='/';
        area.status=status;
        area.online='/';
        data.push(area);
        data.reverse();
    }
    $("#companyTable").DataTable({
        data: data,
        autoWidth:false,
        order:[1,"desc"],
        columnDefs : [
            { orderable: false, targets: [0,2,3,4] }
        ],
        paging:false,
        lengthChange: false,
        searching:false,
        destroy : true,
        scrollY: height,
        info:false,
        language : {
            url:'/pqs9200/json/chine.json',
        },
        columns: [
            { data: 'name' },
            { data: 'amounts'},
            {data:'status.normalData', render:function (data, type, full, meta) {
                    if(Number(full.amounts)===0){
                        return "/";
                    }
                    return data;
                }},
            {data:'status.breaksData', render:function (data, type, full, meta) {
                    if(Number(full.amounts)===0){
                        return "/";
                    }
                    return data;
                }},
            {data:'status.shutdownData', render:function (data, type, full, meta) {
                    if(Number(full.amounts)===0){
                        return "/";
                    }
                    return data;
                }},
            {data:'online', render:function (data, type, full, meta) {
                    if(Number(data)===3.1415){
                        return "/";
                    }else if(Number(data)===3.14159){
                        return "（暂无数据）";
                    }else{
                        return data;
                    }
                }},
        ],
    })
}

//特殊处理，表头紧缩问题--start
var it=null;
function startQuery() {
    //实时刷新时间单位为毫秒
    it= setInterval('refreshQuery()',100);

}
/* 刷新查询 */
function refreshQuery(){
    var width=$("#companyT").width();
    if(width>100){
        drawAreaPic(areaResult);
        drawCompanyPic(companyResult);
        initAreaTable(areaResult);
        initCompanyTable(companyResult);
        window.clearInterval(it)
    }
}

//点击保存图片
$('#saveImage').on('click', function () {
    var name = "终端运行统计";
    drawOnCanvas(areaImage, companyImage, name);
});



//点击导出报表数据
$("#exportData").on("click",function () {
    var xhr = new XMLHttpRequest();
    var endTime = getEndTime();
    var startTime = getMonthStartTime(endTime);
    xhr.open('post', '/pqs9200/overview/downloadRuntimeStatusData', true);
    xhr.responseType = 'blob';
    xhr.setRequestHeader('Content-Type', 'application/json;charset=utf-8');
    var commontParamter={};
    commontParamter.area='overview';
    commontParamter.startTime=startTime;
    commontParamter.endTime=endTime;
    var i = ityzl_SHOW_LOAD_LAYER();
    xhr.send(JSON.stringify(commontParamter))
    xhr.onload = function () {
        if (this.status === 200) {
            var blob = this.response;
            var a = document.createElement('a');
            var url = window.URL.createObjectURL(blob);
            a.href = url;
            //设置文件名称
            a.download = '终端运行统计.xlsx';
            a.click();
            a.remove();
        }
        //***********关闭loading
        ityzl_CLOSE_LOAD_LAYER(i);
    }

})

//根据在线率获取颜色
function getColor(data) {
    if (data >= 90) {
        return green;
    } else if (data === 3.1415) {
        return noMonitor;
    } else if (data === 3.14159) {
        return noData;
    } else if (data < 60) {
        return red;
    } else {
        return yellow;
    }
}
