var picHeight;
var tabs;
var $area = $("#area");
var $startTime = $("#startTime");
var $endTime = $("#endTime");
var areaResult = null;
var companyResult = null;
var tiggleValue = "系统";
var areLength;//区域的个数
var companyLength;//厂家个数
$("#interval").val("月份");
// 新增tab页
function addTab(url, label) {
    tabs.add({url: url, label: label});
}

$(function () {
    $(".checkbox").bootstrapSwitch({
        onText: "冀北",      // 设置ON文本
        offText: "国网",    // 设置OFF文本
        onColor: "primary",// 设置ON文本颜色     (info/success/warning/danger/primary)
        offColor: "primary",  // 设置OFF文本颜色        (info/success/warning/danger/primary)
        size: "small",    // 设置控件大小,从小到大  (mini/small/normal/large)
        handleWidth: "60",//设置控件宽度
        // 当开关状态改变时触发
        onSwitchChange: function (event, state) {
            if (state === true) {
                tiggleValue = "冀北";
            } else {
                tiggleValue = "国网";
            }
            //重新画图
            reDrawAllPic();
        }
    });
    picHeight = $(window).height() - 90;
    tabs = $('#tabs').cleverTabs();
    $.ajax({
        type: "POST",
        url: "/pqs9000/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: '/pqs9000/area/deviceStatus',
        type: 'post',
        data: {
            startTime: startTime,
            endTime: endTime,
            area: area
        },
        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) {
    //给div指定宽高
    $("#areaDepts").css("height", picHeight);
    var normal = [];
    var breaks = [];
    var shutdown = [];
    var areas = [];
    var rate=[];
    if (null != area) {
        for (var i = 0; i < area.length; i++) {
            var monitors;
            var onlineRate;
            if (tiggleValue === "系统") {
                monitors=area[i].amounts;
                areas[i] = area[i].name + "\n(" + area[i].amounts + ")";
                onlineRate = Number(area[i].online);
                normal[i] = area[i].status.normal;
                breaks[i] = area[i].status.breaks;
                shutdown[i] = area[i].status.shutdown;
            } else {
                monitors=area[i].gwamounts;
                areas[i] = area[i].name + "\n(" + area[i].gwamounts + ")";
                onlineRate = Number(area[i].gwonline);
                if(null!==area[i].gdStatus){
                    normal[i] = area[i].gdStatus.normal;
                    breaks[i] = area[i].gdStatus.breaks;
                    shutdown[i] = area[i].gdStatus.shutdown;
                }else{
                    var singleData = {};
                    var item = {};
                    singleData.value = 3.1415;
                    item.color = noMonitor;
                    singleData.itemStyle = item;
                    normal[i] = singleData;
                    breaks[i] = 0;
                    shutdown[i] = 0;
                }
            }
            if (Number(monitors) === 0) {
                var singleData = {};
                var item = {};
                singleData.value = 3.1415;
                item.color = noMonitor;
                singleData.itemStyle = item;
                normal[i] = singleData;
                rate[i]=singleData;
                breaks[i] = 0;
                shutdown[i] = 0;
            } else {
                var singleData = {};
                var normalData = {};
                var itemStyle = {};
                normalData.color = getColor(onlineRate);
                if (onlineRate < 3.1414) {
                    singleData.value = 3.1415;
                    normalData.actual = onlineRate;
                } else {
                    singleData.value = onlineRate;
                }
                itemStyle.normal = normalData;
                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 color = params[0].color;
                if (color === noMonitor) {
                    tips += '<br/>投运 : /';
                    tips += '<br/>检修 : /';
                    tips += '<br/>退运 : /';
                    tips+='<br/>在线率 : /';
                } else {
                    for (var i = 0; i < params.length; i++) {
                        var tempValue="";
                        if(params[i].seriesName==="在线率"&params[i].value==3.14159){
                            tempValue="暂无数据";
                        }else if(params[i].seriesName==="在线率"&params[i].value==3.1415){
                            if (params[i].data.itemStyle.actual !== undefined) {
                                tempValue =  params[i].data.itemStyle.actual;
                            } else {
                                tempValue="/";
                            }
                        }else{
                            tempValue= params[i].value;
                        }
                        tips += '<br/>' + params[i].seriesName + ' : ' +tempValue;
                    }
                }
                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: normal
        }, {
            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('areaDepts'));
    district.setOption(option);
    district.on('click', function (params) {
        if (getRole("/pqs9000/business/runtime") == 1) {
            window.top.addTab('runtime', '终端运行情况')
        }
    });
}

//填充区域表格
function initAreaTable(data) {
    var height = picHeight - 50;
    if (data == null) {
        data = [];
    }
    $("#areaTable").DataTable({
        data: data,
        autoWidth: false,
        order: [2, "desc"],
        paging: false,
        lengthChange: false,
        searching: false,
        destroy: true,
        scrollY: height,
        info: false,
        language: {
            url: '/pqs9000/json/chine.json',
        },
        columns: [
            {data: 'name'},
            {data: 'amounts', render: function (data, type, full, meta) {
                    if (tiggleValue === "系统") {
                        if(full.amounts==0){
                            return "/";
                        }
                        return full.amounts;
                    } else {
                        if(full.gwamounts==0){
                            return "/";
                        }
                        return full.gwamounts;
                    }
                }},
            {
                data: 'status.normalData', render: function (data, type, full, meta) {
                    if (tiggleValue === "系统") {
                        if(full.amounts==0){
                            return "/";
                        }
                        return full.status.normalData;
                    } else {
                        if(full.gwamounts==0){
                            return "/";
                        }
                        if(null===full.gdStatus){
                            return "0"
                        }
                        return full.gdStatus.normalData;
                    }
                }
            },
            {
                data: 'status.breaksData', render: function (data, type, full, meta) {
                    if (tiggleValue === "系统") {
                        if(full.amounts==0){
                            return "/";
                        }
                        return full.status.breaksData;
                    } else {
                        if(full.gwamounts==0){
                            return "/";
                        }
                        if(null===full.gdStatus){
                            return "0"
                        }
                        return full.gdStatus.breaksData;
                    }
                }
            },
            {
                data: 'status.shutdownData', render: function (data, type, full, meta) {
                    if (tiggleValue === "系统") {
                        if(full.amounts==0){
                            return "/";
                        }
                        return full.status.shutdownData;
                    } else {
                        if(full.gwamounts==0){
                            return "/";
                        }
                        if(null===full.gdStatus){
                            return "0"
                        }
                        return full.gdStatus.shutdownData;
                    }
                }
            }, {data:'online', render:function (data, type, full, meta) {
                    if (tiggleValue === "系统") {
                        data = full.online;
                    } else {
                        data = full.gwonline;
                    }
                    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 rate=[];
    var areas = [];
    if (null != companys) {
        for(var i=0;i<companys.length;i++){
            var monitors;
            var onlineRate;
            if (tiggleValue === "系统") {
                monitors=companys[i].amounts;
                areas[i] = companys[i].name + "\n(" + companys[i].amounts + ")";
                onlineRate = Number(companys[i].online);
                run[i]=companys[i].status.normal;
                breaks[i]=companys[i].status.breaks;
                shutdown[i]=companys[i].status.shutdown;
            } else {
                monitors=companys[i].gwamounts;
                areas[i] = companys[i].name + "\n(" + companys[i].gwamounts + ")";
                onlineRate = Number(companys[i].gwonline);
                if(null!==companys[i].gdStatus){
                    run[i] = companys[i].gdStatus.normal;
                    breaks[i] = companys[i].gdStatus.breaks;
                    shutdown[i] = companys[i].gdStatus.shutdown;
                }else{
                    var singleData = {};
                    var item = {};
                    singleData.value = 3.1415;
                    item.color = noMonitor;
                    singleData.itemStyle = item;
                    run[i] = singleData;
                    breaks[i] = 0;
                    shutdown[i] = 0;
                }
            }
            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{
                var singleData={};
                var normal={};
                var itemStyle={};
                normal.color = getColor(onlineRate);
                if(onlineRate<3.1414){
                    singleData.value = 3.1415;
                    normal.actual = onlineRate;
                }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++) {
                        var tempValue="";
                        if(params[i].seriesName==="在线率"&params[i].value==3.14159){
                            tempValue="暂无数据";
                        }else if(params[i].seriesName==="在线率"&params[i].value==3.1415){
                            if (params[i].data.itemStyle.actual !== undefined) {
                                tempValue =  params[i].data.itemStyle.actual;
                            } else {
                                tempValue="/";
                            }
                        }else{
                            tempValue= params[i].value;
                        }
                        tips += '<br/>' + params[i].seriesName + ' : ' +tempValue;
                    }
                }
                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: '%',
            min: '0',
            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);
    factory.on('click', function () {
        if (getRole("/pqs9000/business/runtime") == 1) {
            window.top.addTab('runtime', '终端运行情况')
        }
    });
}

//填充终端厂家表格
function initCompanyTable(data) {
    var height = picHeight - 50;
    if (data == null) {
        data = [];
    }
    $("#companyTable").DataTable({
        data: data,
        autoWidth: false,
        order: [2, "desc"],
        paging: false,
        lengthChange: false,
        searching: false,
        destroy: true,
        scrollY: height,
        info: false,
        language: {
            url: '/pqs9000/json/chine.json',
        },
        columns: [
            {data: 'name'},
            {data: 'amounts', render: function (data, type, full, meta) {
                    if (tiggleValue === "系统") {
                        if(full.amounts==0){
                            return "/";
                        }
                        return full.amounts;
                    } else {
                        if(full.gwamounts==0){
                            return "/";
                        }
                        return full.gwamounts;
                    }
                }},
            {
                data: 'status.normalData', render: function (data, type, full, meta) {
                    if (tiggleValue === "系统") {
                        if(full.amounts==0){
                            return "/";
                        }
                        return full.status.normalData;
                    } else {
                        if(full.gwamounts==0){
                            return "/";
                        }
                        if(null===full.gdStatus){
                            return "0"
                        }
                        return full.gdStatus.normalData;
                    }
                }
            },
            {
                data: 'status.breaksData', render: function (data, type, full, meta) {
                    if (tiggleValue === "系统") {
                        if(full.amounts==0){
                            return "/";
                        }
                        return full.status.breaksData;
                    } else {
                        if(full.gwamounts==0){
                            return "/";
                        }
                        if(null===full.gdStatus){
                            return "0"
                        }
                        return full.gdStatus.breaksData;
                    }
                }
            },
            {
                data: 'status.shutdownData', render: function (data, type, full, meta) {
                    if (tiggleValue === "系统") {
                        if(full.amounts==0){
                            return "/";
                        }
                        return full.status.shutdownData;
                    } else {
                        if(full.gwamounts==0){
                            return "/";
                        }
                        if(null===full.gdStatus){
                            return "0"
                        }
                        return full.gdStatus.shutdownData;
                    }
                }
            },
            {data:'online', render:function (data, type, full, meta) {
                    if (tiggleValue === "系统") {
                        data = full.online;
                    } else {
                        data = full.gwonline;
                    }
                    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) {
//        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)
//    }
}

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


//开关触发图片更新
function reDrawAllPic() {
    if (areaResult === null) {
        drawAreaPic(null);
        initAreaTable(null);
    } else {
        if (parseInt(areLength) > parseInt(barspaclength)) {
            drawAreaPic(areaResult, 1);
        } else {
            drawAreaPic(areaResult, 0);
        }
        initAreaTable(areaResult);
    }
    if (companyResult === null) {
        drawCompanyPic(null);
        initCompanyTable(null);
    } else {
        if (parseInt(companyLength) > parseInt(barspaclength)) {
            drawCompanyPic(companyResult, 1);
        } else {
            drawCompanyPic(companyResult, 0);
        }
        initCompanyTable(companyResult);
    }
}
