var picHeight, endTime, startTime, steadyData;
$(function () {
    picHeight = ($(window).height() - 51) * 0.5;
    $("#helper").css("margin-top", 53 - $(window).height());
    $("#helper").css("margin-left", ($(window).width()) / 2 + 20);
    endTime = getEndTime();
    startTime = getMonthStartTime(endTime);
    //获取频率偏差
    getFrequencyDeviation(startTime, endTime);
});

$("#qualifiedTab a").on('click', function () {
    var html = $(this).html();
    parent.$("#target").text(html);
    //执行查询操作并画图
    var urlPart = $(this).prop("id");
    if (urlPart === "allData") {
        changeClass();
        initTable(steadyData);
        drawAllArea(steadyData);
        $("#helper").css("display", "inline-block");
    } else {
        changeClass(1);
        drawAreaPic(steadyData, urlPart);
        drawVoltagePic(steadyData, urlPart);
        drawLoadTypePic(steadyData, urlPart);
        $("#helper").css("display", "none");
    }
});


//获取频率偏差数据并画图
function getFrequencyDeviation(startTime, endTime) {
    var i;
    $.ajax({
        url: '/pqs9000/overview/frequencyDeviation',
        data: {
            startTime: startTime,
            endTime: endTime
        },
        type: 'post',
        dataType: 'json',
        beforeSend: function () {
            i = ityzl_SHOW_LOAD_LAYER();
        },
        success: function (data) {
            changeClass();
            if (data.code === 500 | data.body === null) {
                steadyData = null;
                initTable(steadyData)
                drawAllArea(steadyData)
            } else {
                steadyData = data.body;
                initTable(steadyData)
                drawAllArea(steadyData)
            }
            //***********关闭loading
            ityzl_CLOSE_LOAD_LAYER(i);
        }
    })
}

//画全部地区的数据图
function drawAllArea(steadyData) {
    var area;
    if (null == steadyData) {
        area = null;
    } else {
        area = steadyData.area;
    }
    $("#allArea").css("height", picHeight);
    var areaOption = echarts.init($("#allArea")[0]);
    var areas = [];
    var frequency = [], uBalance = [], voltageDeviation = [], flicker = [], harmVol = [], harmEle = [], iNeg = [],
        inUharm = [];
    var route;
    if (area.length > barUpperLimit12) {
        route = barRouteIncline;
    } else {
        route = barRouteZero;
    }
    if (null != area) {
        for (var i = 0; i < area.length; i++) {
            areas[i] = area[i].name;

            var harmVolValue = Number(area[i].harmVoltage);
            var harmVolSingleData = {};
            harmVolSingleData.areaIndex = area[i].areaIndex;
            var harmVolItem = {};
            harmVolItem.color = getColor(harmVolValue);
            if (harmVolValue < 3.1414) {
                harmVolSingleData.value = 3.1415;
                harmVolItem.actual = harmVolValue;
            } else {
                harmVolSingleData.value = harmVolValue;
            }
            harmVolSingleData.itemStyle = harmVolItem;
            harmVol[i] = harmVolSingleData;

            var harmEleValue = Number(area[i].harmElec);
            var harmEleSingleData = {};
            harmEleSingleData.areaIndex = area[i].areaIndex;
            var harmEleItem = {};
            harmEleItem.color = getColor(harmEleValue);
            if (harmEleValue < 3.1414) {
                harmEleSingleData.value = 3.1415;
                harmEleItem.actual = harmEleValue;
            } else {
                harmEleSingleData.value = harmEleValue;
            }
            harmEleSingleData.itemStyle = harmEleItem;
            harmEle[i] = harmEleSingleData;

            var iNegValue = Number(area[i].iNeg);
            var iNegSingleData = {};
            iNegSingleData.areaIndex = area[i].areaIndex;
            var iNegItem = {};
            iNegItem.color = getColor(iNegValue);
            if (iNegValue < 3.1414) {
                iNegSingleData.value = 3.1415;
                iNegItem.actual = iNegValue;
            } else {
                iNegSingleData.value = iNegValue;
            }
            iNegSingleData.itemStyle = iNegItem;
            iNeg[i] = iNegSingleData;

            var inUharmValue = Number(area[i].inUharm);
            var inUharmSingleData = {};
            inUharmSingleData.areaIndex = area[i].areaIndex;
            var inUharmItem = {};
            inUharmItem.color = getColor(inUharmValue);
            if (inUharmValue < 3.1414) {
                inUharmSingleData.value = 3.1415;
                inUharmItem.actual = inUharmValue;
            } else {
                inUharmSingleData.value = inUharmValue;
            }
            inUharmSingleData.itemStyle = inUharmItem;
            inUharm[i] = inUharmSingleData;


            var flValue = Number(area[i].flicker);
            var flSingleData = {};
            flSingleData.areaIndex = area[i].areaIndex;
            var flItem = {};
            flItem.color = getColor(flValue);
            if (flValue < 3.1414) {
                flSingleData.value = 3.1415;
                flItem.actual = flValue;
            } else {
                flSingleData.value = flValue;
            }
            flSingleData.itemStyle = flItem;
            flicker[i] = flSingleData;

            var ubValue = Number(area[i].uBalance);
            var ubSingleData = {};
            ubSingleData.areaIndex = area[i].areaIndex;
            var ubItem = {};
            ubItem.color = getColor(ubValue);
            if (ubValue < 3.1414) {
                ubSingleData.value = 3.1415;
                ubItem.actual = ubValue;
            } else {
                ubSingleData.value = ubValue;
            }
            ubSingleData.itemStyle = ubItem;
            uBalance[i] = ubSingleData;

            var freValue = Number(area[i].frequency);
            var freSingleData = {};
            freSingleData.areaIndex = area[i].areaIndex;
            var freItem = {};
            freItem.color = getColor(freValue);
            if (freValue < 3.1414) {
                freSingleData.value = 3.1415;
                freItem.actual = freValue;
            } else {
                freSingleData.value = freValue;
            }
            freSingleData.itemStyle = freItem;
            frequency[i] = freSingleData;


            var volValue = Number(area[i].voltageDeviation);
            var volSingleData = {};
            volSingleData.areaIndex = area[i].areaIndex;
            var valItem = {};
            valItem.color = getColor(volValue);
            if (volValue < 3.1414) {
                volSingleData.value = 3.1415;
                valItem.actual = volValue;
            } else {
                volSingleData.value = volValue;
            }
            volSingleData.itemStyle = valItem;
            voltageDeviation[i] = volSingleData;
        }
    }
    var labelOption = {
        normal: {
            show: false,
            position: 'insideBottom',
            distance: 15,
            align: 'left',
            verticalAlign: 'middle',
            rotate: 90,
            formatter: '{c}  {name|{a}}',
            fontSize: 16,
            rich: {
                name: {
                    textBorderColor: '#fff'
                }
            }
        }
    };

    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;
                for (var i = 0; i < params.length; i++) {
                    if (color === noMonitor) {
                        tips += '<br/>' + params[i].seriesName + ' : /';
                    } else if (color === noData) {
                        tips += '<br/>' + params[i].seriesName + ' : （暂无数据）';
                    } else {
                        if (params[i].data.itemStyle.actual !== undefined) {
                            tips += '<br/>' + params[i].seriesName + ' : ' + params[i].data.itemStyle.actual;
                        } else {
                            tips += '<br/>' + params[i].seriesName + ' : ' + params[i].value;
                        }
                    }
                }
                return tips;
            }
        },
        //控制图标在dataroom中的位置大小
        grid: {
            left: '3%',
            right: '7%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: [{
            type: 'category',
            data: areas,
            name: '地区',
            axisLabel: {
                interval: 0,
                show: true,
                rotate: route,
                fontSize: 10
            }
        }],
        yAxis: [{
            type: 'value',
            name: '%',
            min: '0',
            max: '100'
        }],
        series: [{
            name: '频率偏差',
            type: 'bar',
            barGap: 0.2,
            label: labelOption,
            barMaxWidth: barMax,
            data: frequency
        }, {
            name: '闪变',
            type: 'bar',
            label: labelOption,
            barMaxWidth: barMax,
            data: flicker
        },
            {
                name: '电压不平衡',
                type: 'bar',
                label: labelOption,
                barMaxWidth: barMax,
                data: uBalance
            }, {
                name: '谐波电压',
                type: 'bar',
                label: labelOption,
                barMaxWidth: barMax,
                data: harmVol
            }, {
                name: '电压偏差',
                type: 'bar',
                label: labelOption,
                barMaxWidth: barMax,
                data: voltageDeviation
            }, {
                name: '谐波电流',
                type: 'bar',
                label: labelOption,
                barMaxWidth: barMax,
                data: harmEle
            }, {
                name: '负序电流',
                type: 'bar',
                label: labelOption,
                barMaxWidth: barMax,
                data: iNeg
            }, {
                name: '间谐波电压含有率',
                type: 'bar',
                label: labelOption,
                barMaxWidth: barMax,
                data: inUharm
            }
        ]
    };
    areaOption.setOption(option);
    endTime = getEndTime();
    startTime = getMonthStartTime(endTime);
    areaOption.on('click', function (params) {
        if (getRole("/pqs9000/area/steadytable") === 1) {
            window.top.addTab('/pqs9000/area/steadytable?startTime=' + startTime + '&endTime=' + endTime + '&area=' + params.data.areaIndex + '&interval=月份', '稳态合格率列表')
        }
    });
}

//画指定指标的区域图
function drawAreaPic(steadyData, urlPart) {
    var area;
    if (steadyData === null) {
        area = null;
    } else {
        area = steadyData.area;
    }
    $("#area").css("height", picHeight);
    var areaOption = echarts.init($("#area")[0]);
    var inte = [];
    var areas = [];
    var route;
    var lineFeedBar;
    if (area.length > barUpperLimit12) {
        route = barRouteIncline;
        lineFeedBar = noLineFeed;
    } else {
        route = barRouteZero;
        lineFeedBar = lineFeed;
    }
    if (null != area) {
        for (var i = 0; i < area.length; i++) {
            areas[i] = area[i].name + lineFeedBar + "(" + area[i].monitors + ")";
            var integralityRate = getSteady(area[i], urlPart);
            var singleData = {};
            var item = {};
            item.color = getColor(integralityRate);
            if (integralityRate < 3.1414) {
                singleData.value = 3.1415;
                item.actual = integralityRate;
            } else {
                singleData.value = integralityRate;
            }
            singleData.itemStyle = item;
            inte[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;
                for (var i = 0; i < params.length; i++) {
                    if (color === noMonitor) {
                        tips += '<br/>' + params[i].seriesName + ' : /';
                    } else if (color === noData) {
                        tips += '<br/>' + params[i].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: '7%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: [{
            type: 'category',
            data: areas,
            name: '地区\n(监测点数)\n',
            axisLabel: {
                interval: 0,
                show: true,
                rotate: route,
                fontSize: 10
            }
        }],
        yAxis: [{
            type: 'value',
            name: '%',
            min: '0',
            max: '100'
        }],
        series: [{
            name: '合格率',
            type: 'bar',
            barMaxWidth: barMax,
            data: inte
        }]
    };
    areaOption.setOption(option);
}

//画指定指标的电压等级图
function drawVoltagePic(steadyData, urlPart) {
    var vol;
    if (steadyData === null) {
        vol = null;
    } else {
        vol = steadyData.vol;
    }
    $("#voltage").css("height", picHeight);
    var volOption = echarts.init($("#voltage")[0]);
    var inte = [];
    var areas = [];
    if (null != vol) {
        for (var i = 0; i < vol.length; i++) {
            areas[i] = vol[i].name + "\n(" + vol[i].monitors + ")";
            var integralityRate = getSteady(vol[i], urlPart);
            var singleData = {};
            var item = {};
            item.color = getColor(integralityRate);
            if (integralityRate < 3.1414) {
                singleData.value = 3.1415;
                item.actual = integralityRate;
            } else {
                singleData.value = integralityRate;
            }
            singleData.itemStyle = item;
            inte[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;
                for (var i = 0; i < params.length; i++) {
                    if (color === noMonitor) {
                        tips += '<br/>' + params[i].seriesName + ' : /';
                    } else if (color === noData) {
                        tips += '<br/>' + params[i].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: '3%',
            right: '13%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: [{
            type: 'category',
            data: areas,
            name: '电压等级\n(监测点数)\n',
            axisLabel: {
                interval: 0,
                show: true,
                fontSize: 10
            }
        }],
        yAxis: [{
            type: 'value',
            name: '%',
            min: '0',
            max: '100'
        }],
        series: [{
            name: '合格率',
            type: 'bar',
            barMaxWidth: barMax,
            data: inte
        }]
    };
    volOption.setOption(option);
}

//画指定指标的监测点对象类型图
function drawLoadTypePic(steadyData, urlPart) {
    var loadType;
    if (steadyData === null) {
        loadType = null;
    } else {
        loadType = steadyData.loadType;
    }
    $("#loadType").css("height", picHeight);
    var comOption = echarts.init($("#loadType")[0]);
    var inte = [];
    var areas = [];
    if (null != loadType) {
        for (var i = 0; i < loadType.length; i++) {
            areas[i] = loadType[i].name + "\n(" + loadType[i].monitors + ")";
            var integralityRate = getSteady(loadType[i], urlPart);
            var singleData = {};
            var item = {};
            item.color = getColor(integralityRate);
            if (integralityRate < 3.1414) {
                singleData.value = 3.1415;
                item.actual = integralityRate;
            } else {
                singleData.value = integralityRate;
            }
            singleData.itemStyle = item;
            inte[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;
                for (var i = 0; i < params.length; i++) {
                    if (color === noMonitor) {
                        tips += '<br/>' + params[i].seriesName + ' : /';
                    } else if (color === noData) {
                        tips += '<br/>' + params[i].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: '3%',
            right: '13%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: [{
            type: 'category',
            data: areas,
            name: '干扰源类型\n(监测点数)\n',
            axisLabel: {
                interval: 0,
                show: true,
                fontSize: 10
            }
        }],
        yAxis: [{
            type: 'value',
            name: '%',
            min: '0',
            max: '100'
        }],
        series: [{
            name: '合格率',
            type: 'bar',
            barMaxWidth: barMax,
            data: inte
        }]
    };
    comOption.setOption(option);

}

//初始化表格
function initTable(data) {
    var area;
    if (null == data) {
        area = null;
    } else {
        area = data.area;
    }
    var height = picHeight - 40;
    $("#areaTable").DataTable({
        data: area,
        autoWidth: false,
        columnDefs: [{
            orderable: false,
            targets: [0]
        }],
        order: [1, "desc"],
        paging: false,
        lengthChange: false,
        searching: false,
        destroy: true,
        scrollY: height,
        info: false,
        pageLength: 100,
        language: {
            url: '/pqs9000/json/chine.json',
        },
        columns: [
            {
                data: 'name'
            },
            {
                data: 'frequency', type: "special-fate", render: function (data, type, full, meta) {
                    return getValue(data);
                }
            },
            {
                data: 'flicker', type: "special-fate", render: function (data, type, full, meta) {
                    return getValue(data);
                }
            },
            {
                data: 'uBalance', type: "special-fate", render: function (data, type, full, meta) {
                    return getValue(data);
                }
            },
            {
                data: 'harmVoltage', type: "special-fate", render: function (data, type, full, meta) {
                    return getValue(data);
                }
            },
            {
                data: 'voltageDeviation', type: "special-fate", render: function (data, type, full, meta) {
                    return getValue(data);
                }
            },

            {
                data: 'harmElec', type: "special-fate", render: function (data, type, full, meta) {
                    return getValue(data);
                }
            },
            {
                data: 'iNeg', type: "special-fate", render: function (data, type, full, meta) {
                    return getValue(data);
                }
            },
            {
                data: 'inUharm', type: "special-fate", render: function (data, type, full, meta) {
                    return getValue(data);
                }
            },
            {
                data: 'inUharm', render: function (data, type, full, meta) {
                    var innerContent = getValue(data);
                    var button;
                    if (innerContent === "（暂无数据）" | innerContent === "/") {
                        button = "<button type='button' class='btn themeBGDisableColor' style='margin-right:10px;' href='javascript:void(0);' disabled='disabled'  >越限详情</button>";
                    } else {
                        button = "<button type='button' class='btn themeBGColor' style='margin-right:10px;' onclick='viewDetailData(\"" + full.areaIndex + "\",\"" + full.name + "\")'  >越限详情</button>";
                    }
                    return button;
                }
            },
        ],
    })
}

//获取layer打开新页面后，在标题添加内容并向右浮动
function getTitleInfo(startTime, endTime, target, name) {
    startTime = startTime.replace(/-/g, '/');
    endTime = endTime.replace(/-/g, '/');
    return "<span  class='fr font12' ><span class='info'><span  class='inB bg-info smallBlock'></span> 合格率≥90%</span><span class='warn''> <span class='inB bg-warn smallBlock'></span> 60%≤合格率<90% </span><span class='error'> <span class='inB bg-error smallBlock'></span> 合格率<60%</span></span><span class='fr font25'>&nbsp;&nbsp;|&nbsp;&nbsp;  </span><span class='fr font12'>统计时间：<span class='fontBold' >" + startTime + "-" + endTime + "</span></span><span class='fr font12'>&nbsp;&nbsp;统计区域：<span class='fontBold '  id='target' style='cursor:pointer;margin-right: 10px !important;' >" + name + "</span></span>";
}


//查看越线详情
function viewDetailData(areaIndex, name) {
    endTime = getEndTime();
    startTime = getMonthStartTime(endTime);
    var title = getTitleInfo(startTime, endTime, "稳态越限详情", name);
    parent.layer.open({
        id: 'steady',
        type: 2,
        title: "稳态越限详情" + title,
        maxmin: false,
        resize: false,
        shadeClose: true, //点击遮罩关闭层
        area: ['100%', '100%'],
        content: '/pqs9000/area/outOfLimitDetailView?startTime=' + startTime + "&endTime=" + endTime + "&areaIndex=" + areaIndex,
        scrollbar: false
    })
}


//根据值返回需要的数据
function getValue(value) {
    if (value === 3.14159) {
        return "（暂无数据）";
    } else if (value === 3.1415) {
        return "/";
    } else {
        return value;
    }
}

//根据url获取指标合格率
function getSteady(data, urlPart) {
    var integralityRate;
    if (urlPart === "frequency") {
        integralityRate = Number(data.frequency);
    } else if (urlPart === "flicker") {
        integralityRate = Number(data.flicker);
    } else if (urlPart === "uBalance") {
        integralityRate = Number(data.uBalance);
    } else if (urlPart === "harmVoltage") {
        integralityRate = Number(data.harmVoltage);
    } else if (urlPart === "voltageDeviation") {
        integralityRate = Number(data.voltageDeviation);
    } else if (urlPart === "harmElec") {
        integralityRate = Number(data.harmElec);
    } else if (urlPart === "iNeg") {
        integralityRate = Number(data.iNeg);
    } else if (urlPart === "inUharm") {
        integralityRate = Number(data.inUharm);
    }
    return integralityRate;
}
