var picHeight, powerQualityData;
var $area = $("#area");
var $startTime = $("#startTime");
var $endTime = $("#endTime");
var powerName = "综合";
$("#interval").val("月份");
var powerLength = 0;//长度

//去后台请求当前用户的部门（区域）信息
$(function () {
    picHeight=($(window).height()-88);
    $.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(area, startTime, endTime);
        }
    })
})

//查询电能质量数据
function refresh(area, startTime, endTime) {
    $("li").removeClass("active");
    $("ul li:first-child").addClass("active")
    var i;
    $.ajax({
        url: '/pqs9000/area/powerQualityVol',
        type: 'post',
        data: {
            area: area,
            startTime: startTime,
            endTime: endTime
        },
        beforeSend: function () {
            i = ityzl_SHOW_LOAD_LAYER();
        },
        dataType: 'json',
        success: function (data) {
            if (data.body === null) {
                powerQualityData = null;
            } else {
                powerLength = data.body===null?0:data.body.length;
                powerQualityData = data.body;
            }
            startQuery()
            //***********关闭loading
            ityzl_CLOSE_LOAD_LAYER(i);
        }
    })
}


function initMap(quentityData, name, max, temp, unit,lineFeed,route) {
    var $map = $("#map");
    $map.css("height", picHeight);
    var $bar = $("#bar");
    $bar.css("height", picHeight * 0.5);
    powerName = name;
    $("#norm").html(name + unit)
    //地图容器
    mapEvent = echarts.init(document.getElementById('map'));
    //绘制地图前，获取当前应该绘制的图形父节点 当前节点
    var area = $area.eq(0).attr("index");
    var pNode,node;
    $.ajax({
        url:'/pqs9000/area/getMapInfo',
        type:'post',
        data:{
            area:area
        },
        async:false,
        dataType:'json',
        success:function (data) {
            pNode=data.body.name;
            node=data.body.subName;
        }
    })

    if (quentityData == null) {
        //获取地图数据
        var geoJson = getFullMapData(pNode,node);
        d = [];
        //注册地图
        echarts.registerMap('电能质量', geoJson);
        //绘制地图
        drawMap(d, name);
    } else {
        if (quentityData.length > 1) {
            var geoJson = getFullMapData(pNode,node);
            var d = [];
            for (var i = 0; i < quentityData.length; i++) {
                //根据level获取等级颜色
                var color;
                if (name === "综合评估") {
                    color = getColorByLevelAllData(quentityData[i].level);
                } else {
                    color = getColorByLevel(quentityData[i].level);
                }
                var dataTemp;
                if (quentityData[i].data === 3.1415) {
                    dataTemp = "/";
                } else if (quentityData[i].data === 3.14159) {
                    dataTemp = "（暂无数据）";
                } else {
                    dataTemp = quentityData[i].data
                }
                d.push({
                    name: quentityData[i].name,
                    value: dataTemp,
                    emphasis: {itemStyle: {areaColor: color, borderColor: "white", borderWidth: "1"}}
                })
            }
            //注册地图
            echarts.registerMap('电能质量', geoJson);
            drawMap(d, name);
        } else {
            var d = [];
            var color;
            var dataTemp;
            if (name === "综合评估") {
                color = getColorByLevelAllData(quentityData[0].level);
            } else {
                color = getColorByLevel(quentityData[0].level);
            }
            if (quentityData[0].data === 3.1415) {
                dataTemp = "/";
            } else if (quentityData[0].data === 3.14159) {
                dataTemp = "（暂无数据）";
            } else {
                dataTemp = quentityData[0].data
            }
            var data = getFullMapData(pNode,node);
            if (data !== null) {
                d.push({
                    name: quentityData[0].name,
                    value: dataTemp,
                    emphasis: {itemStyle: {areaColor: color, borderColor: "white", borderWidth: "1"}}
                });
                //获取地图数据
                //注册地图
                echarts.registerMap('电能质量', data);
                drawMap(d, name);
            }
        }
    }

    //绘制柱状图
    var barOption = echarts.init($("#bar")[0]);
    var inte = [];
    var areas = [];
    var interval;
    if (null != quentityData) {
        //判断内部数据有没有大于max的，重新赋值max
        max = getMaxValue(max, quentityData, temp);
        //具体情况具体分析，分析出间隔区间interval
        var intTemp = max / 5;
        if (intTemp > 1) {
            interval = intTemp.toFixed(0);
            if (interval < intTemp) {
                interval = Number(interval) + 1;
            }
            max = interval * 5;
            max = max.toFixed(0);
        } else if (intTemp > 0.1) {
            interval = intTemp.toFixed(1);
            if (interval < intTemp) {
                interval = Number(interval) + 0.1;
            }
            max = interval * 5;
            max = max.toFixed(1);
        } else {
            interval = intTemp.toFixed(2);
            if (interval < intTemp) {
                interval = Number(interval) + 0.01;
            }
            max = interval * 5;
            max = max.toFixed(2);
        }
        for (var i = 0; i < quentityData.length; i++) {
            areas[i] = quentityData[i].name + lineFeed+"(" + quentityData[i].monitor + ")";
            var dataTemp = 0;
            var singleData = {};
            var item = {};
            if (quentityData[i].data === 3.1415) {
                dataTemp = max * 0.03;
                singleData.value = dataTemp;
                item.color = noMonitor;
                singleData.itemStyle = item;
            } else if (quentityData[i].data === 3.14159) {
                dataTemp = max * 0.03;
                singleData.value = dataTemp;
                item.color = noData;
                singleData.itemStyle = item;
            } else if (quentityData[i].data < max * 0.03) {
                dataTemp = max * 0.03;
                singleData.value = dataTemp;
                item.color = "#2E8B57";
                item.actual = quentityData[i].data;
                singleData.itemStyle = item;
            } else {
                singleData.value = quentityData[i].data;
                var level = quentityData[i].level;
                if (name === "综合评估") {
                    item.color = getColorByLevelAllData(level);
                } else {
                    item.color = getColorByLevel(level);
                }
                singleData.itemStyle = item;
            }
            singleData.areaIndex = quentityData[i].deptsIndex;
            inte[i] = singleData;
        }
    }
    var option = {
        backgroundColor: canvasBG,//背景色
        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: {
            top:'12%',
            left: '4%',
            right: '10%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: [{
            type: 'category',
            data: areas,
            splitLine: {
                show: false
            },
            name: '地区\n(监测点数)',
            axisLabel: {
                interval: 0,
                show: true,
                rotate:route,
                fontSize:10
            },
            boundaryGap:true

        }],
        yAxis: [{
            type: 'value',
            min: '0',
            nameLocation:'center',
            nameTextStyle:{
                padding:[3, 7, 19, 1]
            },
            name: unit,
            max: max,
        }],
        series: [{
            name: name,
            type: 'bar',
            barMaxWidth: barMax,
            data: inte
        }]
    };
    barOption.setOption(option);
    barOption.on('click', function (params) {
        var city = params.data.areaIndex;
        var startTime = $startTime.eq(0).val();
        var endTime = $endTime.eq(0).val();
        var interval = $("#interval").val();
        onContent(city, startTime, endTime,interval);
    });
    //填充表格
    var height = picHeight * 0.5 - 40;
    if (quentityData == null) {
        quentityData = [];
    }
    $("#areaTable").DataTable({
        data: quentityData,
        autoWidth: false,
        order: [],
        columnDefs: [
            {"width": "33%", "targets": 0},
            {"width": "33%", "targets": 1},
            {"width": "33%", "targets": 2}
        ],
        paging: false,
        lengthChange: false,
        searching: false,
        destroy: true,
        scrollY: height,
        info: false,
        pageLength: 100,
        language: {
            url: '/pqs9000/json/chine.json',
        },
        columns: [
            {data: 'name'},
            {
                data: 'data', render: function (data, type, full, meta) {
                    if (data === 3.1415) {
                        return "/";
                    } else if (data === 3.14159) {
                        return "（暂无数据）";
                    } else {
                        return data;
                    }
                }
            },
            {data: 'level'}
        ],
    })
}
function onContent(city, startTime, endTime,interval) {
    layer.open({
        id: 'overview',
        type: 2,
        title: "电能质量评估列表",
        maxmin: false,
        resize: false,
        shadeClose: true, //点击遮罩关闭层
        area: ['100%', '100%'],
        content: "/pqs9000/overview/assesTable?starttime="+startTime+"&endtime="+endTime+"&area="+city+"&interval="+interval,
        scrollbar: false
    });
}
function renderMapEvent(data, f1, f2, f3, f4, f5, f6, f7, f8) {
    //初始化绘制全国地图配置
    var optionEvent = {
        backgroundColor: canvasBG,
        title: {
            text: powerName + '评估',
            left: 'center'
        },
        animationDuration: 1000,
        animationEasing: 'cubicOut',
        animationDurationUpdate: 1000,
        tooltip: {
            trigger: 'item',
            formatter: function (params) {
                var tips = "";
                if (isNaN(params.value)) {
                    if (params.data === undefined || params.data.value === undefined) {
                        tips += '<font style=\'color:' + white + '\'>暂无数据</font><br/>';
                    } else if (params.data.value === "/" | params.data.value === "（暂无数据）") {
                        tips += '<font style=\'color:' + white + '\'>' + params.name + '</font></br>';
                        tips += powerName + '<font style=\'color:' + white + '\'>：' + params.data.value + '</font><br/>';
                    }
                } else {
                    tips += '<font style=\'color:' + white + '\'>' + params.name + '</font></br>';
                    tips += powerName + '<font style=\'color:' + white + '\'>：' + params.value + '</font><br/>';
                }
                return tips;
            }
        }
    };
    optionEvent.visualMap = {
        type: 'piecewise',
        pieces: [
            {gt: f8, label: '极度污染'},
            {gt: f7, lte: f8, label: '重度污染'},
            {gt: f6, lte: f7, label: '中度污染'},
            {gt: f5, lte: f6, label: '轻度污染'},
            {gt: f4, lte: f5, label: '良好'},
            {gt: f3, lte: f4, label: '优良'},
            {gt: f2, lte: f3, label: '优质'},
            {gte: f1, lte: f2, label: '特质'}
        ],
        color: [red, yellow, green],
        inverse: true
    };
    optionEvent.series = [
        {
            // name: map,
            type: 'map',
            mapType: '电能质量',
            roam: true,
            label: {
                normal: {
                    show: true,
                    textStyle: {
                        color: 'black',
                        fontSize: 10
                    }
                },
                emphasis: {
                    show: true,
                    textStyle: {
                        color: 'black',
                        fontSize: 10
                    }
                }
            },
            itemStyle: {
                normal: {
                    areaColor: '#CCCCCC',
                    borderColor: 'dodgerblue'
                },
                emphasis: {
                    areaColor: '#B6B5B5'
                }
            },
            data: data
        }
    ];
    mapEvent.dispatchAction({
        type: 'restore'
    });
    //渲染地图
    mapEvent.setOption(optionEvent);
}

function renderMapEventAll(data, f1, f2, f3, f4, f5, f6) {
    //初始化绘制全国地图配置
    var optionEvent = {
        backgroundColor: canvasBG,
        title: {
            text: powerName,
            left: 'center'
        },
        animationDuration: 1000,
        animationEasing: 'cubicOut',
        animationDurationUpdate: 1000,
        tooltip: {
            trigger: 'item',
            formatter: function (params) {
                var tips = "";
                if (isNaN(params.value)) {
                    if (params.data === undefined || params.data.value === undefined) {
                        tips += '<font style=\'color:' + white + '\'>暂无数据</font><br/>';
                    } else if (params.data.value === "/" | params.data.value === "（暂无数据）") {
                        tips += '<font style=\'color:' + white + '\'>' + params.name + '</font></br>';
                        tips += powerName + '<font style=\'color:' + white + '\'>：' + params.data.value + '</font><br/>';
                    }
                } else {
                    tips += '<font style=\'color:' + white + '\'>' + params.name + '</font></br>';
                    tips += powerName + '<font style=\'color:' + white + '\'>：' + params.value + '</font><br/>';
                }
                return tips;
            }
        }
    };
    optionEvent.visualMap = {
        type: 'piecewise',
        pieces: [
            {gte: f5, lte: f6, label: '优质'},
            {gte: f4, lt: f5, label: '良好'},
            {gte: f3, lt: f4, label: '合格'},
            {gte: f2, lt: f3, label: '较差'},
            {gte: f1, lt: f2, label: '极差'}
        ],
        color: [green, yellow, red],
        inverse: false
    };
    optionEvent.series = [
        {
            // name: map,
            type: 'map',
            mapType: '电能质量',
            roam: true,
            label: {
                normal: {
                    show: true,
                    textStyle: {
                        color: 'black',
                        fontSize: 10
                    }
                },
                emphasis: {
                    show: true,
                    textStyle: {
                        color: 'black',
                        fontSize: 10
                    }
                }
            },
            itemStyle: {
                normal: {
                    areaColor: '#CCCCCC',
                    borderColor: 'dodgerblue'
                },
                emphasis: {
                    areaColor: '#B6B5B5'
                }
            },
            data: data
        }
    ];
    mapEvent.dispatchAction({
        type: 'restore'
    })
    //渲染地图
    mapEvent.setOption(optionEvent);
}

$("#query").click(function () {
    var area = $area.eq(0).attr("index");
    var startTime = $startTime.eq(0).val();
    var endTime = $endTime.eq(0).val();
    refresh(area, startTime, endTime);
});

function divdangerMouseOver() {
    var tab = $("#qualifiedTab .active a").text()
    if (tab === "综合评估") {
        initTipTableAll([["等级", "1", "2", "3", "4", "5"], ["综合评估", "[1,2]", "(2,3]", "(3,4]", "(4,4.5]", "(4.5,5]"]]);
        $("#tipsAll").css("display", "block");
    } else {
        if (tab === "电压偏差") {
            initTipTable([["等级", "1", "2", "3", "4", "5", "6", "7", "8"], ["电压偏差（≤10%）", "[0,2.5]", "(2.5,5]", "(5,7.5]", "(7.5,10]", "(10,12.5]", "(12.5,15]", "(15,17.5]", "(17.5,+∞)"]]);
        } else if (tab === "电压闪变") {
            initTipTable([["等级", "1", "2", "3", "4", "5", "6", "7", "8"], ["电压闪变（≤0.6）", "[0,0.15]", "(0.15,0.3]", "(0.3,0.45]", "(0.45,0.60]", "(0.6,0.75]", "(0.75,0.90]", "(0.90,1.05]", "(1.05,+∞)"]]);
        } else if (tab === "谐波含量") {
            initTipTable([["等级", "1", "2", "3", "4", "5", "6", "7", "8"], ["谐波含量(≤2.00%)", "[0,0.5]", "(0.5,1]", "(1,1.5]", "(1.5,2]", "(2,2.5]", "(2.5,3]", "(3,3.5]", "(3.5,+∞)"]]);
        } else if (tab === "频率偏差") {
            initTipTable([["等级", "1", "2", "3", "4", "5", "6", "7", "8"], ["频率偏差（≤±0.2Hz）", "[0,0.05]", "(0.05,0.10]", "(0.10,0.15]", "(0.15,0.20]", "(0.20,0.25]", "(0.25,0.30]", "(0.30,0.35]", "(0.35,+∞)"]]);
        } else if (tab === "三相电压不平衡度") {
            initTipTable([["等级", "1", "2", "3", "4", "5", "6", "7", "8"], ["三相电压不平衡度（≤2.0%）", "[0,0.5]", "(0.5,1]", "(1,1.5]", "(1.5,2]", "(2,2.5]", "(2.5,3]", "(3,3.5]", "(3.5,+∞)"]]);
        }
        $("#tips").css("display", "block");
    }
}

function divdangerMouseOut() {
    $("#tips").css("display", "none");
    $("#tipsAll").css("display", "none");
}

function initTipTable(data) {
    $("#tipTable").DataTable({
        data: data,
        autoWidth: false,
        ordering: false,
        paging: false,
        lengthChange: false,
        searching: false,
        destroy: true,
        info: false,
        language: {
            url: '/pqs9000/json/chine.json',
        }
    })
}

function initTipTableAll(data) {
    $("#tipTableAll").DataTable({
        data: data,
        autoWidth: false,
        ordering: false,
        paging: false,
        lengthChange: false,
        searching: false,
        destroy: true,
        info: false,
        language: {
            url: '/pqs9000/json/chine.json',
        }
    })
}


//特殊处理，表头紧缩问题--start
var it = null;

function startQuery() {
    //实时刷新时间单位为毫秒
    it = setInterval('refreshQuery()', 100);

}

/* 刷新查询 */
function refreshQuery() {
    var width = $("#table").width();
    if (width > 100) {
        if (powerQualityData === null) {
            initMap(null, '综合评估', 5, 1, '',lineFeed,barRouteZero)
        } else {
            var powerLength=powerQualityData.synData==null?0:powerQualityData.synData.length;
            if(parseInt(powerLength)>parseInt(barUpperLimit6)){
                initMap(powerQualityData.synData,'综合评估',5,1,'',noLineFeed,barRouteIncline)
            }else {
                initMap(powerQualityData.synData,'综合评估',5,1,'',lineFeed,barRouteZero)
            }
        }
        window.clearInterval(it)
    }
}

//特殊处理，表头紧缩问题--end