var picHeight, endTime, startTime;
var tiggleValue = "系统";
var areaResult = null;
var companyResult = null;
var areLength;//区域的个数
var companyLength;//厂家个数
$(function () {
    //开关初始化
    $(".wanzheng").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: "40",//设置控件宽度
        // 当开关状态改变时触发
        onSwitchChange: function (event, state) {
            if (state == true) {
                tiggleValue = "系统";
            } else {
                tiggleValue = "网公司";
            }
            //重新画图
            reDrawAllPic();
        }
    });
    var i;
    picHeight = $(window).height() * 0.5 - 5;
    endTime = getEndTime();
    startTime = getMonthStartTime(endTime);
    $.ajax({
        url: '/pqs9000/overview/onlineRate',
        data: {
            startTime: startTime,
            endTime: endTime
        },
        type: 'post',
        dataType: 'json',
        beforeSend: function () {
            i = ityzl_SHOW_LOAD_LAYER();
        },
        success: function (data) {
            if (data.code === 500 | data.body === null) {
                drawAreaPic(null);
                drawCompanyPic(null);
                initAreaTable(null);
                initCompanyTable(null);
            } else {
                areLength = data.body.area === null ? 0 : data.body.area.length;
                companyLength = data.body.interval === null ? 0 : data.body.interval.length;
                if (parseInt(areLength) > parseInt(barspaclength)) {
                    drawAreaPic(data.body.area, 1);
                } else {
                    drawAreaPic(data.body.area, 0);
                }
                if (parseInt(companyLength) > parseInt(barspaclength)) {
                    drawCompanyPic(data.body.interval, 1);
                } else {
                    drawCompanyPic(data.body.interval, 0);
                }
                companyResult = data.body.interval;
                areaResult = data.body.area;

                initAreaTable(data.body.area);
                initCompanyTable(data.body.interval);
            }
            //***********关闭loading
            ityzl_CLOSE_LOAD_LAYER(i);
        }
    })
})

//描绘区域图
function drawAreaPic(area, intervals) {
    var xTip;
    if (tiggleValue === "系统") {
        xTip = '地区\n(终端数)\n';
    } else {
        xTip = '地区\n(监测点数)\n';
    }
    $("#area").css("height", picHeight);
    var areaOption = echarts.init($("#area")[0]);
    var rate = [];
    var areas = [];
    if (null != area) {
        for (var i = 0; i < area.length; i++) {
            var onlineRate;
            if (tiggleValue === "系统") {
                areas[i] = area[i].name + "\n(" + area[i].amounts + ")";
                onlineRate = Number(area[i].online);
            } else {
                areas[i] = area[i].name + "\n(" + area[i].gwamounts + ")";
                onlineRate = Number(area[i].gwonline);
            }
            var singleData = {};
            var item = {};
            item.color = getColor(onlineRate);
            if (onlineRate < 3.1414) {
                singleData.value = 3.1415;
                item.actual = onlineRate;
            } else {
                singleData.value = onlineRate;
            }
            singleData.areaIndex = area[i].deptsIndex;
            singleData.itemStyle = item;
            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);
    areaOption.on('click', function (params) {
        if (getRole("/pqs9000/area/onlineratetable") == 1) {
            var city = params.data.areaIndex;
            window.top.addTab('/pqs9000/area/onlineratetable?startTime=' + startTime + '&endTime=' + endTime + '&area=' + city + '&interval=月份', '在线率列表')
        }
    });
}

//填充区域表格
function initAreaTable(data) {
    var height = picHeight - 50;
    if (data == null) {
        data = [];
    }
    $("#areaTable").DataTable({
        data: data,
        autoWidth: false,
        columnDefs: [
            {"width": "33%", "targets": 0},
            {"width": "33%", "targets": 1},
            {"width": "33%", "targets": 2}
        ],
        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 === "系统") {
                        return full.amounts;
                    } else {
                        return full.gwamounts;
                    }
                }
            },
            {
                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(company, intervals) {
    var xTip;
    if (tiggleValue === "系统") {
        xTip = '终端厂家\n(终端数)\n';
    } else {
        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;
            if (tiggleValue === "系统") {
                areas[i] = company[i].name + "\n(" + company[i].amounts + ")";
                onlineRate = Number(company[i].online);
            } else {
                areas[i] = company[i].name + "\n(" + company[i].gwamounts + ")";
                onlineRate = Number(company[i].gwonline);
            }
            var singleData = {};
            var item = {};
            item.color = getColor(onlineRate);
            if (onlineRate < 3.1414) {
                singleData.value = 3.1415;
                item.actual = onlineRate;
            } else {
                singleData.value = onlineRate;
            }
            singleData.itemStyle = item;
            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);
    comOption.on('click', function (params) {
        if (getRole("/pqs9000/area/onlineratetable") == 1) {
            window.top.addTab('/pqs9000/area/onlineratetable?startTime=' + startTime + '&endTime=' + endTime + '&interval=月份', '在线率列表')
        }
    });
}

//填充终端厂家表格
function initCompanyTable(data) {
    var height = picHeight - 50;
    if (data == null) {
        data = [];
    }
    $("#companyTable").DataTable({
        data: data,
        autoWidth: false,
        columnDefs: [
            {"width": "33%", "targets": 0},
            {"width": "33%", "targets": 1},
            {"width": "33%", "targets": 2}
        ],
        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 === "系统") {
                        return full.amounts;
                    } else {
                        return full.gwamounts;
                    }
                }
            },
            {
                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;
                    }
                }
            }
        ],
    })
}

/**
 * 获取指定区域下终端的在线率具体数据（最多10条）
 */
function showDetailData(content, title) {
    layer.open({
        type: 2,
        title: title + '终端在线率详情（前10）',
        shadeClose: true,
        resize: false,
        area: '650px',
        scrollbar: false,
        content: content
    })
}

//开关触发图片更新
function reDrawAllPic() {
    if (tiggleValue === "系统") {
        $("#typeTitle").html("终端数");
        $("#typeTitle1").html("终端数");
    } else {
        $("#typeTitle").html("监测点数");
        $("#typeTitle1").html("监测点数");
    }

    if (areaResult === null) {
        drawAreaPic(null);
        initAreaTable(null);
    } else {
        drawAreaPic(areaResult);
        initAreaTable(areaResult);
    }
    if (companyResult === null) {
        drawCompanyPic(null);
        initCompanyTable(null);
    } else {
        drawCompanyPic(companyResult);
        initCompanyTable(companyResult);
    }

}

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