var picHeight,areaImage,companyImage;
var tabs;
var $area=$("#area");
var $startTime=$("#startTime");
var $endTime=$("#endTime");
var areaResult=null;
var companyResult=null;
var areLength;//区域的个数
var companyLength;//厂家个数
$("#interval").val("月份");

//开关初始化
$(function () {
    picHeight=($(window).height()-38)*0.5;
    $.ajax({
        type: "POST",
        url: "/pqs9200/user/getAreasInfo",
        dataType:'json',
        success:function (data) {
            $("#area").val(data[0].name);
            $("#area").attr("index", data[0].id);
            areaTree = $.fn.zTree.init($("#areaTree"), settingAreaTree, data);
            //初始化页面内容
            var area = $area.eq(0).attr("index");
            var startTime = $startTime.eq(0).val();
            var endTime = $endTime.eq(0).val();
            refresh( startTime, endTime,area);
        }
    })
})

//点击按钮查询
$("#query").click(function() {
    var area = $area.eq(0).attr("index");
    var startTime = $startTime.eq(0).val();
    var endTime = $endTime.eq(0).val();
    refresh( startTime, endTime,area);
});

//请求后台刷新数据
function refresh(startTime,endTime,area) {
    var i;
    $.ajax({
        url:'/pqs9200/area/onlineRate',
        data:{
            startTime:startTime,
            endTime:endTime,
            area:area
        },
        type:'post',
        dataType:'json',
        beforeSend: function () {
            i = ityzl_SHOW_LOAD_LAYER();
        },
        success:function (data) {
            if (data.code===500|data.body===null){
                companyResult=null;
                areaResult=null;
            }else{
                areLength = data.body.area===null?0:data.body.area.length;
                companyLength = data.body.interval===null?0:data.body.interval.length;
                companyResult=data.body.interval;
                areaResult=data.body.area;
            }
            startQuery();
            //***********关闭loading
            ityzl_CLOSE_LOAD_LAYER(i);
        }
    })
}
//描绘区域图
function drawAreaPic(area,intervals) {
    var  xTip='地区\n(终端数)\n';
    $("#areaDepts").css("height",picHeight);
    var areaOption = echarts.init($("#areaDepts")[0]);
    var rate=[];
    var areas=[];
    if(null!=area){
        for(var i=0;i<area.length;i++){
            var onlineRate;
            areas[i]=area[i].name+"\n("+area[i].amounts+")";
            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'
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            },
            formatter: function (params) {
                var color=params[0].color;
                var tips="";
                tips+=params[0].name;
                if(color===noMonitor){
                    tips+='<br/>'+params[0].seriesName+' : /';
                }else if(color===noData){
                    tips+='<br/>'+params[0].seriesName+' : （暂无数据）';
                }else{
                    if (params[0].data.itemStyle.actual !== undefined) {
                        tips += '<br/>' + params[0].seriesName + ' : ' + params[0].data.itemStyle.actual;
                    } else {
                        tips += '<br/>' + params[0].seriesName + ' : ' + params[0].value;
                    }
                }
                return tips;
            }
        },
        //控制图标在dataroom中的位置大小
        grid: {
            left: '1%',
            right: '10%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: [{
            type: 'category',
            data: areas,
            name: xTip,
            splitLine: {
                show: false
            },
            axisLabel : {
                show:true,
                interval: intervals
            }
        }],
        yAxis: [{
            type: 'value',
            name: '%',
            min:'0',
            max:'100'
        }],
        series: [{
            name: '在线率',
            type: 'bar',
            barMaxWidth: barMax,
            data: rate
        }]
    };
    areaOption.setOption(option);
    areaImage=areaOption.getDataURL();
}

//填充区域表格
function initAreaTable(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;
        area.online="/";
        data.push(area);
        data.reverse();
    }
    $("#areaTable").DataTable({
        data: data,
        autoWidth:false,
        order:[1,"desc"],
        columnDefs : [
            { "width": "33%", "targets": 0 },
            { "width": "33%", "targets": 1 },
            { "width": "33%", "targets": 2 },
            { orderable: false, targets: [0,2] }
        ],
        paging:false,
        lengthChange: false,
        searching:false,
        destroy : true,
        scrollY: height,
        info:false,
        language : {
            url:'/pqs9200/json/chine.json',
        },
        columns: [
            { data: 'name' },
            { data: 'amounts'},
            { data:'online',render:function (data, type, full, meta) {
                    data=full.online;
                    if(Number(data)===3.1415){
                        return "/";
                    }else if(Number(data)===3.14159){
                        return "（暂无数据）";
                    }else{
                        return data;
                    }
                }}
        ],
    })
}

//描绘终端厂家图
function drawCompanyPic(company,intervals) {
    var xTip='终端厂家\n(终端数)\n';
    $("#company").css("height",picHeight);
    var comOption = echarts.init($("#company")[0]);
    var rate=[];
    var areas=[];
    if(null!=company){
        for(var i=0;i<company.length;i++){
            var onlineRate;
            areas[i]=company[i].name+"\n("+company[i].amounts+")";
            onlineRate=Number(company[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'
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            },
            formatter: function (params) {
                var color=params[0].color;
                var tips="";
                tips+=params[0].name;
                if(color===noMonitor){
                    tips+='<br/>'+params[0].seriesName+' : /';
                }else if(color===noData){
                    tips+='<br/>'+params[0].seriesName+' : （暂无数据）';
                }else{
                    if (params[0].data.itemStyle.actual !== undefined) {
                        tips += '<br/>' + params[0].seriesName + ' : ' + params[0].data.itemStyle.actual;
                    } else {
                        tips += '<br/>' + params[0].seriesName + ' : ' + params[0].value;
                    }
                }
                return tips;
            }
        },
        //控制图标在dataroom中的位置大小
        grid: {
            left: '1%',
            right: '10%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: [{
            type: 'category',
            data: areas,
            name:xTip,
            splitLine: {
                show: false
            },
            axisLabel : {
                show:true,
                interval: intervals
            }
        }],
        yAxis: [{
            type: 'value',
            name: '%',
            min:'0',
            max:'100'
        }],
        series: [{
            name: '在线率',
            type: 'bar',
            barMaxWidth: barMax,
            data: rate
        }]
    };
    comOption.setOption(option);
    companyImage=comOption.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 company={};
        company.name=name;
        company.amounts=amounts;
        company.online="/";
        data.push(company);
        data.reverse();
    }
    $("#companyTable").DataTable({
        data: data,
        autoWidth:false,
        order:[1,"desc"],
        columnDefs : [
            { "width": "33%", "targets": 0 },
            { "width": "33%", "targets": 1 },
            { "width": "33%", "targets": 2 },
            { orderable: false, targets: [0,2] }
        ],
        paging:false,
        lengthChange: false,
        searching:false,
        destroy : true,
        scrollY: height,
        info:false,
        language : {
            url:'/pqs9200/json/chine.json',
        },
        columns: [
            { data: 'name' },
            { data: 'amounts'},
            { data:'online',render:function (data, type, full, meta) {
                    data=full.online;
                    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=$("#areaT").width();
    if(width>100){
        if(parseInt(areLength)>parseInt(barspaclength)){
            drawAreaPic(areaResult,1);
        }else {
            drawAreaPic(areaResult,0);
        }
        if(parseInt(companyLength)>parseInt(barspaclength)){
            drawCompanyPic(companyResult,1);
        }else {
            drawCompanyPic(companyResult,0);
        }
        initAreaTable(areaResult);
        initCompanyTable(companyResult);
        window.clearInterval(it)
    }
}
//特殊处理，表头紧缩问题--end


//根据在线率获取颜色
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;
    }
}


//点击保存图片
$('#saveImage').on('click', function () {
    var area = $area.find("option:selected").text();
    var name = area+"终端在线率";
    drawOnCanvas(areaImage, companyImage, name);
});

//点击导出报表数据
$("#exportData").on("click",function () {
    var xhr = new XMLHttpRequest();
    var area = $area.eq(0).attr("index");
    var name = $area.eq(0).val();
    xhr.open('post', '/pqs9200/area/downloadOnlineRateData', true);
    xhr.responseType = 'blob';
    xhr.setRequestHeader('Content-Type', 'application/json;charset=utf-8');
    var commontParamter={};
    commontParamter.area=area;
    commontParamter.startTime= $startTime.eq(0).val();
    commontParamter.endTime=$endTime.eq(0).val();
    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 = name+'终端在线率.xlsx';
            a.click();
            a.remove();
        }
        //***********关闭loading
        ityzl_CLOSE_LOAD_LAYER(i);
    }

})