var picHeight, endTime, startTime, cityName;
var powerLength = 0;// 长度
var loading;
$(document).ready(function () {
    picHeight = ($(window).height() - 51);
    $("#map").css("height", picHeight);
    $("#bar").css("height", picHeight * 0.5);
    endTime = getEndTime();
    startTime = getStartTime(endTime);
    getDevmap(startTime, endTime);
})

// 点击ul切换页面表格数据
$("#qualifiedTab a").on('click', function () {
    var html = $(this).html();
    if (html == "监测网分布") {
        $("#table").hide();
        $("#table3").hide();
        $("#table4").hide();
        $("#table2").show();
        getDevmap(startTime, endTime);
    } else if (html == "暂降热力图") {
        $("#table").hide();
        $("#table2").hide();
        $("#table4").hide();
        $("#table3").show();
        getEventmap(startTime, endTime);
    } else if (html == "区域暂降评估") {
        $("#table").hide();
        $("#table2").hide();
        $("#table3").hide();
        $("#table4").show();
        getbalance(startTime, endTime);
    } else if (html == "暂降严重度展示") {
        $("#table2").hide();
        $("#table3").hide();
        $("#table4").hide();
        $("#table").show();
        getMapevent(startTime, endTime);
    }
})

function getDevmap(startTime, endTime) {
    var loading;
    $.ajax({
        type: "POST",
        url: "/pqs9200/area/getDevMap",
        dataType: "text",
        data: {
            startTime: startTime,
            endTime: endTime
        },
        beforeSend: function () {
            loading = ityzl_SHOW_LOAD_LAYER_PARENT();
        },
        success: function (data) {
            var info = $.parseJSON(data);
            if (info.code == 500) {
                initDevMap(null);
            } else {
                initDevMap(info.body.maps);
                var barData = info.body.online;
                var initT2Length = barData === null ? 0 : barData.length;
                if (parseInt(initT2Length) > parseInt(barUpperLimit6)) {
                    initTable2(barData, noLineFeed, barRouteIncline);
                } else {
                    initTable2(barData, lineFeed, barRouteZero);
                }
            }
            //***********关闭loading
            ityzl_CLOSE_LOAD_LAYER_PARENT(loading);
        }
    });
}

function initDevMap(data) {
    var mapnor = [];
    var mapbre = [];
    var tmpmap = {};
    for (var i = 0; i < data.length; i++) {
        // 获取变电站名称（key，由变电站名称，经度，纬度组成：事例：变电站1,123.00,135.00）
        var key = data[i].subname + "," + data[i].longitude + ","
            + data[i].latitude;
        // 假如key已经存在了
        if (tmpmap[key]) {
            var tmpdata = tmpmap[key];
            tmpdata.push(data[i]);
        } else {
            var tmpdata = [];
            tmpdata.push(data[i]);
            tmpmap[key] = tmpdata;
        }
    }

    // 根据分组后的监测点进行偏移算法
    var r = 0.035;
    for (tmpkey in tmpmap) {
        var arr = tmpmap[tmpkey];
        var tmplength = arr.length;
        var norarr = [];
        var brearr = [];
        for (var i = 0; i < tmplength; i++) {
            var info = arr[i];
            var datatmp = [];
            info.longitude = (info.longitude + r
                * Math.cos(2 * Math.PI * (i) / tmplength)).toFixed(3);
            info.latitude = (info.latitude + r
                * Math.sin(2 * Math.PI * (i) / tmplength)).toFixed(3);
            if (info.status == 1) {
                datatmp = [info.longitude, info.latitude, info.subname,
                    info.linename, "正常"];
                mapnor.push({
                    value: datatmp,
                    itemStyle: {
                        normal: {
                            color: green
                        }
                    }
                });
            } else {
                datatmp = [info.longitude, info.latitude, info.subname,
                    info.linename, "中断"];
                mapbre.push({
                    value: datatmp,
                    itemStyle: {
                        normal: {
                            color: red
                        }
                    }
                });
            }
        }
    }

    echarts.dispose($("#map")[0]);
    var dom = document.getElementById("map");
    var devmapChart = echarts.init(dom);
    $.ajaxSettings.async = false;
    var pNode, node;
    var loadingMap;
    $.ajax({
        url: '/pqs9200/area/getMapInfo',
        type: 'post',
        data: {
            area: "overview"
        },
        beforeSend: function () {
            loadingMap = ityzl_SHOW_LOAD_LAYER_PARENT();
        },
        async: false,
        dataType: 'json',
        success: function (data) {
            pNode = data.body.name;
            node = data.body.subName;
            cityName = data.body.name;
            //***********关闭loading
            ityzl_CLOSE_LOAD_LAYER_PARENT(loadingMap);
        }
    })
    var geoJson = getFullMapData(pNode, node);
    echarts.registerMap('监测网分布', geoJson);
    var option = {
        itemStyle: {
            normal: {
                areaColor: '#CCCCCC',
                borderColor: 'dodgerblue'
            },
            emphasis: {
                areaColor: '#B6B5B5'
            }
        },
        title: {
            text: '监测网分布',
            left: 'center'
        },
        tooltip: {
            trigger: 'item',
            formatter: function (a) {
                var relVal = "";
                relVal = '<font style=\'color:' + white + '\'>变电站名称：'
                    + a.value[2] + '</font><br/>';
                relVal += '<font style=\'color:' + white + '\'>监测点名称：'
                    + a.value[3] + '</font><br/>';
                relVal += '<font style=\'color:' + white + '\'>通讯状态：'
                    + a.value[4] + '</font><br/>';
                return relVal;
            }
        },
        legend: {
            data: ['正常', '中断'],
            x: 'left',
            y: 'bottom',
            orient: 'vertical',
            show: true
        },
        geo: {
            map: '监测网分布',
            itemStyle: {
                normal: {
                    areaColor: '#CCCCCC',
                    borderColor: 'dodgerblue'
                }
            },
            label: {
                normal: {
                    show: true,
                    textStyle: {
                        color: 'black',
                        fontSize: 10
                    }
                }
            },
            roam: true
        },
        series: [{
            name: '正常',
            type: 'scatter',
            coordinateSystem: 'geo',
            data: mapnor,
            symbolSize: 5
        }, {
            name: '中断',
            type: 'scatter',
            coordinateSystem: 'geo',
            data: mapbre,
            symbolSize: 5
        }],
        color: [green, red]
    };
    devmapChart.dispatchAction({
        type: 'restore'
    })
    devmapChart.setOption(option, true);
}

function initTable2(data, lineFeed, route) {
    // 绘制柱状图
    echarts.dispose($("#bar")[0]);
    var barOption = echarts.init($("#bar")[0]);
    var inte = [];
    var colorList = [];
    var area = [];
    if (null != data) {
        var ymax = 0;
        for (var n = 0; n < data.length; n++) {
            if (data[n].amounts > ymax) {
                ymax = data[n].amounts;
            }
        }
        for (var i = 0; i < data.length; i++) {
            if (data[i].name == '总计') {

            } else {
                area.push(data[i].name);
                var singleData = [];
                if (data[i].amounts == 0) {
                    singleData = [data[i].name, ymax * 0.025, 0];
                    colorList.push(grey);
                } else {
                    singleData = [data[i].name, data[i].amounts,
                        data[i].amounts];
                    colorList.push(orange);
                }
                inte.push({
                    value: singleData
                });
            }
        }
    }
    var option = {
        backgroundColor: canvasBG,// 背景色
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            },
            formatter: function (params) {
                var tips = "";
                tips += '<font>区域:' + params[0].value[0] + '</font><br/>';
                tips += '<font>监测点数:' + params[0].value[2] + '</font>';
                return tips;
            }
        },
        title: {
            text: cityName,
            x: 'center'
        },
        // 控制图标在dataroom中的位置大小
        grid: {
            top: '18%',
            left: '1%',
            right: '10%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: [{
            type: 'category',
            data: area,
            name: '区域',
            splitLine: {
                show: false
            },
            axisLabel: {
                interval: 0,
                show: true,
                rotate: route,
                fontSize: 10
            }

        }],
        yAxis: [{
            name: '监测点数',
            type: 'value'
        }],
        series: [{
            name: '区域',
            type: 'bar',
            barMaxWidth: barMax,
            data: inte,
            itemStyle: {
                normal: {
                    color: function (params) {
                        return colorList[params.dataIndex];
                    }
                }
            }
        }]
    };
    barOption.setOption(option);

    // 填充表格
    var height = picHeight * 0.5 - 45;
    if (data == null) {
        data = [];
    }
    if (data == null) {
        data = [];
    }
    $("#areaTable2").DataTable({
        data: data,
        autoWidth: false,
        columnDefs: [{
            "width": "25%",
            "targets": 0
        }, {
            "width": "25%",
            "targets": 1
        }, {
            "width": "25%",
            "targets": 2
        }, {
            "width": "25%",
            "targets": 3
        }],
        order: [],
        paging: false,
        lengthChange: false,
        searching: false,
        destroy: true,
        scrollY: height,
        info: false,
        pageLength: 100,
        language: {
            url: '/pqs9200/json/chine.json',
        },
        columns: [{
            data: 'name'
        }, {
            data: 'amounts'
        }, {
            data: 'oncount'
        }, {
            data: 'offcount'
        }],
    })
}

function getEventmap(startTime, endTime) {
    var i;
    $.ajax({
        type: "POST",
        url: "/pqs9200/area/getEventMap",
        dataType: "text",
        data: {
            startTime: startTime,
            endTime: endTime
        },
        beforeSend: function () {
            i = ityzl_SHOW_LOAD_LAYER_PARENT();
        },
        success: function (data) {
            var info = $.parseJSON(data);
            if (info.code == 500) {
                initeventMap(null);
                initTable3();
            } else {
                initeventMap(info.body);
                initTable3();
            }

            //***********关闭loading
            ityzl_CLOSE_LOAD_LAYER_PARENT(i);
        }
    });
}

function initeventMap(data) {
    var maxt = 0;
    var map = [];
    var tmpmap = {};
    if (data != null) {
        for (var i = 0; i < data.length; i++) {
            if (data[i].gdName == '总计') {

            } else {
                // 获取变电站名称（key，由变电站名称，经度，纬度组成：事例：变电站1,123.00,135.00）
                var key = data[i].subName + "," + data[i].longitude + ","
                    + data[i].latitude;
                // 假如key已经存在了
                if (tmpmap[key]) {
                    var tmpdata = tmpmap[key];
                    tmpdata.push(data[i]);
                } else {
                    var tmpdata = [];
                    tmpdata.push(data[i]);
                    tmpmap[key] = tmpdata;
                }
            }
        }
    }

    // 根据分组后的监测点进行偏移算法
    var r = 0.035;
    for (tmpkey in tmpmap) {
        var arr = tmpmap[tmpkey];
        var tmplength = arr.length;
        var norarr = [];
        var brearr = [];
        for (var i = 0; i < tmplength; i++) {
            var info = arr[i];
            var datatmp = [];
            if (maxt < info.eventcount) {
                maxt = info.eventcount;
            }
            info.longitude = (info.longitude + r
                * Math.cos(2 * Math.PI * (i) / tmplength)).toFixed(3);
            info.latitude = (info.latitude + r
                * Math.sin(2 * Math.PI * (i) / tmplength)).toFixed(3);
            datatmp = [info.longitude, info.latitude];
            if (info.eventcount > 0) {
                datatmp = datatmp.concat(info.eventcount);
                map.push(datatmp);
            }

        }
    }

    var interval = 0;
    if (maxt <= 10) {
        interval = 1;
    } else if (maxt <= 20) {
        interval = 2;
    } else {
        interval = 5;
    }
    echarts.dispose($("#map")[0]);
    var dom = document.getElementById("map");
    var eventmapChart = echarts.init(dom);
    $.ajaxSettings.async = false;
    var pNode, node;
    var i;
    $.ajax({
        url: '/pqs9200/area/getMapInfo',
        type: 'post',
        data: {
            area: "overview"
        },
        beforeSend: function () {
            i = ityzl_SHOW_LOAD_LAYER_PARENT();
        },
        async: false,
        dataType: 'json',
        success: function (data) {
            pNode = data.body.name;
            node = data.body.subName;
            cityName = data.body.name;
            //***********关闭loading
            ityzl_CLOSE_LOAD_LAYER_PARENT(i);
        }
    })
    var geoJson = getFullMapData(pNode, node);
    echarts.registerMap('暂降热力图', geoJson);
    var option = {
        title: {
            text: '暂降热力图',
            left: 'center',
        },
        grid: {
            left: '1%',
            right: '2%'
        },
        visualMap: {
            min: 1,
            max: maxt,
            splitNumber: interval,
            inRange: {
                color: ['#d94e5d', '#eac736', '#50a3ba'].reverse()
            },
            textStyle: {
                color: '#000'
            }
        },
        geo: {
            map: '暂降热力图',
            itemStyle: {
                normal: {
                    areaColor: '#CCCCCC',
                    borderColor: 'dodgerblue'
                }
            },
            label: {
                normal: {
                    show: true,
                    textStyle: {
                        color: 'black',
                        fontSize: 10
                    }
                }
            },
            roam: true
        },
        series: [{
            color: '#eac736',
            name: '监测点',
            type: 'heatmap',
            coordinateSystem: 'geo',
            data: map,
            pointSize: 5,
            blurSize: 6,
            roam: true
        }]
    };
    eventmapChart.dispatchAction({
        type: 'restore'
    })
    eventmapChart.setOption(option, true);
}

function initTable3() {
    var areaList;
    var lineFeed, route;
    var i;
    $.ajax({
        type: "POST",
        url: "/pqs9200/area/getMapData",
        dataType: "text",
        async: false,
        beforeSend: function () {
            i = ityzl_SHOW_LOAD_LAYER_PARENT();
        },
        data: {
            startTime: startTime,
            endTime: endTime
        },
        success: function (data) {
            var info = $.parseJSON(data);
            if (info.code === 500) {

            } else {
                areaList = info.body.areaList;
                monitorList = info.body.monitorList;
            }

            // ***********关闭loading
            ityzl_CLOSE_LOAD_LAYER_PARENT(i);
        }
    });

    var initTLength = areaList === null ? 0 : areaList.length;
    if (parseInt(initTLength) > parseInt(barUpperLimit6)) {
        lineFeed = noLineFeed;
        route = barRouteIncline;
    } else {
        lineFeed = "\n";
        route = barRouteZero;
    }

    echarts.dispose($("#bar")[0]);
    var barOption = echarts.init($("#bar")[0]);
    var inte = [];
    var colorList = [];
    var area = [];
    if (null != areaList) {
        var ymax = 1;
        for (var n = 0; n < areaList.length; n++) {
            if (Number(areaList[n].value) > ymax
                && Number(areaList[n].value) !== 3.1415
                && Number(areaList[n].value) !== 3.14159) {
                ymax = areaList[n].value;
            }
        }
        for (var i = 0; i < areaList.length; i++) {
            if (areaList[i].name === '总计') {

            } else {
                area.push(areaList[i].name + lineFeed + "(" + areaList[i].node
                    + ")");
                var singleData = [];
                var value;
                if (Number(areaList[i].value) === 3.1415) {
                    value = "/";
                    singleData = [
                        areaList[i].name + lineFeed + "("
                        + areaList[i].node + ")", 0.03, value];
                    colorList.push(noMonitor);
                } else if (Number(areaList[i].value) === 3.14159) {
                    value = "0";
                    singleData = [
                        areaList[i].name + lineFeed + "("
                        + areaList[i].node + ")", 0.03, value];
                    colorList.push(noData);
                } else {
                    value = areaList[i].value;
                    singleData = [
                        areaList[i].name + lineFeed + "("
                        + areaList[i].node + ")", value, value];
                    colorList.push(orange);
                }
                inte.push({
                    value: singleData
                });
            }
        }
    }
    var option = {
        backgroundColor: canvasBG,// 背景色
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            },
            formatter: function (params) {
                var tips = "";
                tips += '<font>区域:' + params[0].value[0] + '</font><br/>';
                tips += '<font>暂降次数:' + params[0].value[2] + '</font>';
                return tips;
            }
        },
        title: {
            text: cityName,
            x: 'center'
        },
        // 控制图标在dataroom中的位置大小
        grid: {
            top: '18%',
            left: '3%',
            right: '14%',
            bottom: '1%',
            containLabel: true
        },
        xAxis: [{
            type: 'category',
            data: area,
            name: '区域\n(监测点数)',
            splitLine: {
                show: false
            },
            axisLabel: {
                interval: 0,
                show: true,
                rotate: route,
                fontSize: 10
            }
        }],
        yAxis: [{
            name: '暂降次数',
            type: 'value',
            minInterval: 1
        }],
        series: [{
            name: '区域',
            type: 'bar',
            barMaxWidth: barMax,
            data: inte,
            itemStyle: {
                normal: {
                    color: function (params) {
                        return colorList[params.dataIndex];
                    },
                    label: {
                        show: true,
                        formatter: function (params) {
                            return params.value[2];
                        }
                    }
                }
            }
        }]
    };
    barOption.setOption(option);

    var height = picHeight * 0.5 - 45;
    if (areaList == null) {
        areaList = [];
    }
    $("#areaTable3").DataTable({
        data: monitorList,
        autoWidth: false,
        order: [],
        columnDefs: [{
            "width": "25%",
            "targets": 0
        }, {
            "width": "25%",
            "targets": 1
        }, {
            "width": "25%",
            "targets": 2
        }, {
            "width": "25%",
            "targets": 3
        }],
        paging: false,
        lengthChange: false,
        searching: false,
        destroy: true,
        scrollY: height,
        info: false,
        pageLength: 100,
        language: {
            url: '/pqs9200/json/chine.json',
        },
        columns: [{
            data: 'gdName'
        }, {
            data: 'subName'
        }, {
            data: 'name'
        }, {
            data: 'value'
        }],
    })
}

var balanceData;
var balanceLength;// 个数
function getbalance(startTime, endTime) {
    var i;
    $.ajax({
        url: '/pqs9200/balance/getBalanceInfo',
        type: 'post',
        data: {
            startTime: startTime,
            endTime: endTime,
            area: "overview"
        },
        beforeSend: function () {
            i = ityzl_SHOW_LOAD_LAYER_PARENT();
        },
        dataType: 'json',
        success: function (data) {
            if (data.code === 500 || data.body === null || data.body == []) {
                balanceData = null;
            } else {
                balanceLength = data.body === null ? 0 : data.body.length;
                balanceData = packageData(data.body);
            }

            ityzl_CLOSE_LOAD_LAYER_PARENT(i);
            startQuery();
        }
    })
}

function packageData(data) {
    var result = [];

    for (var i = 0; i < data.length; i++) {
        var obj = new Object();
        obj.name = data[i].areaName;

        if (data[i].isCount == 1) {
            obj.data = data[i].ci.toFixed(2);
            obj.level = judgeLevel(obj.data).level;
        } else if (data[i].list == null) {
            obj.data = '/';
            obj.level = '/';
        } else {
            obj.data = '(暂无数据)';
            obj.level = '(暂无数据)';
        }

        obj.monitor = (data[i].list == null ? 0 : data[i].list.length);
        result.push(obj);
    }

    return result;
}

function judgeLevel(d) {
    var obj = new Object();
    var data = parseFloat(d);

    if (data <= 0.4 && data >= 0) {
        obj.level = 1;
        obj.color = "#2E8B56";
    } else if (data > 0.4 && data <= 0.8) {
        obj.level = 2;
        obj.color = "#919B38";
    } else if (data > 0.8 && data <= 1.2) {
        obj.level = 3;
        obj.color = "#D39320";
    } else if (data > 1.2) {
        obj.level = 4;
        obj.color = "#A52A2A";
    } else if (d == '/') {
        obj.color = noMonitor;
    } else {
        obj.color = noData;
    }

    return obj;
}

var it = null;

function startQuery() {
    it = setInterval('refreshQuery()', 100);
}

/* 刷新查询 */
function refreshQuery() {
    var width = $("#table").width();
    try {
        if (width > 100) {
            if (balanceData === null) {
                initbalanceMap(null, '区域暂降评估', lineFeed, barRouteZero);
            } else {
                if (parseInt(balanceLength) > parseInt(barUpperLimit6)) {
                    initbalanceMap(balanceData, '区域暂降评估', noLineFeed,
                        barRouteIncline);
                } else {
                    initbalanceMap(balanceData, '区域暂降评估', lineFeed,
                        barRouteZero);
                }
            }
        }
    } catch (e) {

    } finally {
        window.clearInterval(it);
    }
}

var mapEvent;

function initbalanceMap(quentityData, name, lineFeed, route) {
    powerName = name;
    echarts.dispose($("#map")[0]);
    mapEvent = echarts.init(document.getElementById('map'));
    var pNode, node;
    var i;
    $.ajax({
        url: '/pqs9200/area/getMapInfo',
        type: 'post',
        data: {
            area: "overview"
        },
        beforeSend: function () {
            i = ityzl_SHOW_LOAD_LAYER_PARENT();
        },
        async: false,
        dataType: 'json',
        success: function (data) {
            pNode = data.body.name;
            node = data.body.subName;
            cityName = data.body.name;
            //***********关闭loading
            ityzl_CLOSE_LOAD_LAYER_PARENT(i);
        }
    })
    if (quentityData == null || quentityData.length === 0) {
        var geoJson = getFullMapData(pNode, node);
        var d = [];
        echarts.registerMap('区域暂降评估', geoJson);
        renderMapEvent(d);
    } else {
        if (quentityData.length > 1) {
            var geoJson = getFullMapData(pNode, node);
            var d = [];
            for (var i = 0; i < quentityData.length; i++) {
                var color = judgeLevel(quentityData[i].data).color;
                var dataTemp = quentityData[i].data;
                d.push({
                    name: quentityData[i].name,
                    value: dataTemp,
                    emphasis: {
                        itemStyle: {
                            areaColor: color,
                            borderColor: "white",
                            borderWidth: "1"
                        }
                    }
                })
            }
            echarts.registerMap('区域暂降评估', geoJson);
            renderMapEvent(d);
        } else {
            var d = [];
            var color = judgeLevel(quentityData[0].data).color;
            var dataTemp = quentityData[0].data;
            d.push({
                name: quentityData[0].name,
                value: dataTemp,
                emphasis: {
                    itemStyle: {
                        areaColor: color,
                        borderColor: "white",
                        borderWidth: "1"
                    }
                }
            });
            var data = getFullMapData(pNode, node);
            echarts.registerMap('区域暂降评估', data);
            renderMapEvent(d);
        }
    }
    // 绘制柱状图
    echarts.dispose($("#bar")[0]);
    var barOption = echarts.init($("#bar")[0]);
    var inte = [];
    var areas = [];
    var colorList = [];
    if (null != quentityData) {
        for (var i = 0; i < quentityData.length; i++) {
            areas[i] = quentityData[i].name + lineFeed + "("
                + quentityData[i].monitor + ")";
            var singleData = {};
            singleData.value = isNaN(parseInt(quentityData[i].level)) ? 0.2
                : quentityData[i].level;
            singleData.des = quentityData[i].level;
            colorList.push(judgeLevel(quentityData[i].data).color);
            inte[i] = singleData;
        }
    }
    var option = {
        backgroundColor: canvasBG,// 背景色
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            },
            formatter: function (params) {
                return params[0].name + '<br/>区域暂降评估等级 : ' + params[0].data.des;
            }
        },
        title: {
            text: cityName,
            x: 'center'
        },
        // 控制图标在dataroom中的位置大小
        grid: {
            top: '18%',
            left: '3%',
            right: '12%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: [{
            type: 'category',
            data: areas,
            splitLine: {
                show: false
            },
            name: '地区\n(监测点数)',
            axisLabel: {
                interval: 0,
                show: true,
                rotate: route,
                fontSize: 10
            }

        }],
        yAxis: [{
            name: '(等级)',
            type: 'value',
            min: 0,
            max: 4
        }],
        series: [{
            name: name,
            type: 'bar',
            barMaxWidth: barMax,
            data: inte,
            itemStyle: {
                normal: {
                    color: function (params) {
                        return colorList[params.dataIndex];
                    }
                }
            }
        }]
    };
    barOption.setOption(option);
    // 填充表格
    var height = picHeight * 0.5 - 45;
    if (quentityData == null) {
        quentityData = [];
    }
    $("#areaTable4").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: '/pqs9200/json/chine.json',
        },
        columns: [{
            data: 'name'
        }, {
            data: 'data',
            render: function (data, type, full, meta) {
                return data;
            }
        }, {
            data: 'level'
        }],
    })
}

function renderMapEvent(data) {
    var optionEvent = {
        backgroundColor: canvasBG,
        title: {
            text: '区域暂降评估',
            left: 'center'
        },
        animationDuration: 1000,
        animationEasing: 'cubicOut',
        animationDurationUpdate: 1000,
        tooltip: {
            trigger: 'item',
            formatter: function (params) {
                var tips = "";

                if (params.data == undefined) {
                    tips = '<font style=\'color:' + white
                        + '\'>暂无数据</font><br/>';
                } else {
                    tips += '<font style=\'color:' + white + '\'>'
                        + params.data.name + '</font><br/>区域暂降评估'
                        + '<font style=\'color:' + white + '\'>：'
                        + params.data.value + '</font><br/>';
                }

                return tips;
            }
        }
    };
    optionEvent.visualMap = {
        type: 'piecewise',
        pieces: [{
            gt: 1.2,
            label: '4级'
        }, {
            gt: 0.8,
            lte: 1.2,
            label: '3级'
        }, {
            gt: 0.4,
            lte: 0.8,
            label: '2级'
        }, {
            gt: -1,
            lte: 0.4,
            label: '1级'
        }],
        color: [red, yellow, green],
        inverse: true
    };
    optionEvent.series = [{
        type: 'map',
        mapType: '区域暂降评估',
        roam: true,
        label: {
            normal: {
                show: true,
                textStyle: {
                    ccolor: 'black',
                    fontSize: 10
                }
            },
            emphasis: {
                show: true,
                textStyle: {
                    color: '#fff',
                    fontSize: 10
                }
            }
        },
        itemStyle: {
            normal: {
                areaColor: '#CCCCCC',
                borderColor: 'dodgerblue'
            },
            emphasis: {
                areaColor: '#B6B5B5'
            }
        },
        data: data
    }];
    mapEvent.dispatchAction({
        type: 'restore'
    })
    mapEvent.setOption(optionEvent);
}

var mapMonitor;

function getMapevent(startTime, endTime) {
    var i;
    var arealist;
    $.ajax({
        type: "POST",
        url: "/pqs9200/area/getMapData",
        dataType: "text",
        data: {
            startTime: startTime,
            endTime: endTime
        },
        async: false,
        beforeSend: function () {
            i = ityzl_SHOW_LOAD_LAYER_PARENT();
        },
        success: function (data) {
            var info = $.parseJSON(data);
            if (info.code === 500) {
                // 统计区域的监测点
                initEvents(null);
                initTable(null, lineFeed, barRouteZero);
            } else {
                arealist = info.body.areaList;
            }
            // ***********关闭loading
            ityzl_CLOSE_LOAD_LAYER_PARENT(i);
        }
    });

    // 统计区域的监测点
    initEvents(arealist);
    var initTLength = arealist === null ? 0 : arealist.length;
    if (parseInt(initTLength) > parseInt(barUpperLimit6)) {
        initTable(arealist, noLineFeed, barRouteIncline);
    } else {
        initTable(arealist, lineFeed, barRouteZero);
    }
}

/**
 * 表格数据填充
 */
function initTable(areaList, lineFeed, route) {
    echarts.dispose($("#bar")[0]);
    var barOption = echarts.init($("#bar")[0]);
    var inte = [];
    var colorList = [];
    var area = [];
    if (null != areaList) {
        var ymax = 1;
        for (var n = 0; n < areaList.length; n++) {
            if (Number(areaList[n].value) > ymax
                && Number(areaList[n].value) !== 3.1415
                && Number(areaList[n].value) !== 3.14159) {
                ymax = areaList[n].value;
            }
        }
        for (var i = 0; i < areaList.length; i++) {
            if (areaList[i].name === '总计') {

            } else {
                area.push(areaList[i].name + lineFeed + "(" + areaList[i].node
                    + ")");
                var singleData = [];
                var value;
                if (Number(areaList[i].value) === 3.1415) {
                    value = "/";
                    singleData = [
                        areaList[i].name + lineFeed + "("
                        + areaList[i].node + ")", 0.03, value];
                    colorList.push(noMonitor);
                } else if (Number(areaList[i].value) === 3.14159) {
                    value = "0";
                    singleData = [
                        areaList[i].name + lineFeed + "("
                        + areaList[i].node + ")", 0.03, value];
                    colorList.push(noData);
                } else {
                    value = areaList[i].value;
                    singleData = [
                        areaList[i].name + lineFeed + "("
                        + areaList[i].node + ")", value, value];
                    colorList.push(orange);
                }
                inte.push({
                    value: singleData
                });
            }
        }
    }
    var option = {
        backgroundColor: canvasBG,// 背景色
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            },
            formatter: function (params) {
                var tips = "";
                tips += '<font>区域:' + params[0].value[0] + '</font><br/>';
                tips += '<font>暂降次数:' + params[0].value[2] + '</font>';
                return tips;
            }
        },
        title: {
            text: cityName,
            x: 'center'
        },
        // 控制图标在dataroom中的位置大小
        grid: {
            top: '18%',
            left: '3%',
            right: '14%',
            bottom: '1%',
            containLabel: true
        },
        xAxis: [{
            type: 'category',
            data: area,
            name: '区域\n(监测点数)',
            splitLine: {
                show: false
            },
            axisLabel: {
                interval: 0,
                show: true,
                rotate: route,
                fontSize: 10
            }
        }],
        yAxis: [{
            name: '暂降次数',
            type: 'value',
            minInterval: 1
        }],
        series: [{
            name: '区域',
            type: 'bar',
            barMaxWidth: barMax,
            data: inte,
            itemStyle: {
                normal: {
                    color: function (params) {
                        return colorList[params.dataIndex];
                    },
                    label: {
                        show: true,
                        formatter: function (params) {
                            return params.value[2];
                        }
                    }
                }
            }
        }]
    };
    barOption.setOption(option);

    var height = picHeight * 0.5 - 45;
    if (areaList == null) {
        areaList = [];
    }
    $("#areaTable1").DataTable({
        data: areaList,
        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: '/pqs9200/json/chine.json',
        },
        columns: [{
            data: 'name'
        }, {
            data: 'value',
            render: function (data, type, full, meta) {
                if (Number(data) === 3.1415) {
                    return "/";
                } else if (Number(data) === 3.14159) {
                    return "暂无数据";
                } else {
                    return data;
                }
            }, type: "number-fate"
        }, {
            data: 'node'
        }],
    })
}

/**
 * 区域地图绘制
 */
function initEvents(eventData) {
    var i;
    // 地图容器
    echarts.dispose($("#map")[0]);
    mapMonitor = echarts.init(document.getElementById('map'));
    var pNode, node;
    $.ajax({
        url: '/pqs9200/area/getMapInfo',
        type: 'post',
        data: {
            area: "overview"
        },
        beforeSend: function () {
            i = ityzl_SHOW_LOAD_LAYER_PARENT();
        },
        async: false,
        dataType: 'json',
        success: function (data) {
            pNode = data.body.name;
            node = data.body.subName;
            cityName = data.body.name;
            //***********关闭loading
            ityzl_CLOSE_LOAD_LAYER_PARENT(i);
        }
    })
    if (eventData == null || eventData.length === 0) {
        // 获取地图数据
        var geoJson = getFullMapData(pNode, node);
        d = [];
        var max = 100;
        // 注册地图
        echarts.registerMap('严重度分析', geoJson);
        // 绘制地图
        renderMap(d, max);
    } else {
        if (eventData.length > 1) {
            // 获取地图数据
            var geoJson = getFullMapData(pNode, node);
            d = [];
            var max = 0;
            for (var i = 0; i < eventData.length; i++) {
                var name = eventData[i].name;
                if (name == "总计") {
                    continue;
                }
                var value = Number(eventData[i].value);
                if (value === 3.1415 || value === 3.14159) {
                    value = 0;
                }
                if (value > max) {
                    max = value;
                }
                d.push({
                    name: name,
                    value: value
                })
            }
            max = Math.ceil(Number(max) * 1.2);
            // 注册地图
            echarts.registerMap('严重度分析', geoJson);
            // 绘制地图
            renderMap(d, max);
        } else {
            var d = [];
            var name = eventData[0].name;
            var value = Number(eventData[0].value);
            if (value === 3.1415 || value === 3.14159) {
                value = 0;
            }
            var max = Math.ceil(value * 1.2);
            // 获取地图数据
            var data = getFullMapData(pNode, node);
            if (data !== null) {
                d.push({
                    name: name,
                    value: value
                });
                // 注册地图
                echarts.registerMap('严重度分析', data);
                // 绘制地图
                renderMap(d, max);
            }
        }
    }
}

var emphasisColor;
// 初始化绘制全国地图配置
var option = {
    backgroundColor: canvasBG,// 背景色
    title: {
        text: '区域严重度分析',
        left: 'center'
    },
    tooltip: {
        trigger: 'item',
        formatter: function (params) {
            var color;
            if (isNaN(params.value) || params.value === 0) {
                color = '#f9f9f9';
            } else {
                color = params.color;
            }
            emphasisColor = color;
            var tips = "";
            tips += '<font style=\'color:' + color + '\'>' + params.name
                + '</font><br/>';
            if (isNaN(params.value)) {
                tips += '<font style=\'color:' + color
                    + '\'>暂降事件数：0个</font><br/>';
            } else {
                tips += '<font style=\'color:' + color + '\'>暂降事件数：'
                    + params.value + '个</font><br/>';
            }
            return tips;
        }
    },
    animationDuration: 1000,
    animationEasing: 'cubicOut',
    animationDurationUpdate: 1000
};

function renderMap(data, max) {
    if (max == 0) {
        option.dataRange = {
            min: 0,
            max: max,
            color: ['#ccc'],
            text: ['高', '低'], // 文本，默认为数值文本
            calculable: true
        };
    } else if (max < 10000) {
        option.dataRange = {
            min: 0,
            max: max,
            color: ['darkorange', '#ccc'],
            text: ['高', '低'], // 文本，默认为数值文本
            calculable: true
        };
    } else {
        option.dataRange = {
            min: 0,
            max: max,
            color: ['darkorange', '#ccc'],
            text: ['高', '低'], // 文本，默认为数值文本
            calculable: true
        };
    }
    option.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: emphasisColor
            }
        },
        data: data
    }];
    mapMonitor.dispatchAction({
        type: 'restore'
    })
    // 渲染地图
    mapMonitor.setOption(option);
}

function getMax(max, data) {
    for (var n = 0; n < data.length; n++) {
        if (data[n].amounts > max) {
            max = data[n].amounts;
        }
    }
    return max * 0.025;
}

/**
 * 电压等级排序自定义start
 */
jQuery.fn.dataTableExt.oSort['number-fate-asc'] = function (s1, s2) {
    if (s1 === "/" || s1 === "暂无数据") {
        s1 = 0;
    }
    if (s2 === "/" || s2 === "暂无数据") {
        s2 = 0;
    }
    return Number(s1) - Number(s2);
};

jQuery.fn.dataTableExt.oSort['number-fate-desc'] = function (s1, s2) {
    if (s1 === "/" || s1 === "暂无数据") {
        s1 = 0;
    }
    if (s2 === "/" || s2 === "暂无数据") {
        s2 = 0;
    }
    return Number(s2) - Number(s1);
};
