var map = new BMap.Map("container")
var dataArr;
var markers = [];//需要聚合的监测点
var monitors = []

//添加地图类型控件
map.addControl(new BMap.MapTypeControl({
    mapTypes: [
        BMAP_NORMAL_MAP,
        BMAP_HYBRID_MAP,

    ]
}));
var point = new BMap.Point(120.753092, 31.631542); // 创建点坐标
map.centerAndZoom(point, 15); // 初始化地图，设置中心点坐标和地图级别
map.setCurrentCity("常熟"); // 设置地图显示的城市 此项是必须设置的
map.enableScrollWheelZoom(true); //开启鼠标滚轮缩放
//单击获取点击的经纬度
/*map.addEventListener("click", function (e) {
    alert(e.point.lng + "," + e.point.lat);


})*/


function rightBox() {
    $('#leftT').animate({'left': '-240'}, 2000);
    $("#rightIcon").hide()
    $("#leftIcon").show()
}

function leftBox() {
    $('#leftT').animate({'left': '0'}, 2000);
    $("#rightIcon").show()
    $("#leftIcon").hide()
}


var color;
$(function () {

    $.ajax({
        type: "POST",
        url: "/pqs9000/theme/getThemeInfo",
        async: false,
        dataType: 'json',
        success: function (data) {
            color = data.body.value;
        }
    })
    getMonitorMap()

    $('#leftT').on('click', '#monitorInfo', function () {

        layer.open({
            id: 'monitorMap',
            type: 2,
            title: '监测点详情',
            maxmin: false,
            resize: false,
            shadeClose: true, //点击遮罩关闭层
            area: ['100%', '100%'],
            content: '/pqs9000/business/lineledger',
            scrollbar: false
        });
    })

    $('#leftT').on('click', '#eventInfo', function () {

        layer.open({
            id: 'monitorMap',
            type: 2,
            title: '暂态事件详情',
            maxmin: false,
            resize: false,
            shadeClose: true, //点击遮罩关闭层
            area: ['100%', '100%'],
            content: '/pqs9000/area/vdlist',
            scrollbar: false
        });
    })


})


let loading;

function getMonitorMap() {
    let date = new Date(); // 获取当前日期时间
    let myyear = date.getFullYear();
    let mymonth = date.getMonth() + 1;
    let myweekday = date.getDate();
    mymonth < 10 ? mymonth = "0" + mymonth : mymonth;
    myweekday < 10 ? myweekday = "0" + myweekday : myweekday;
    let startTime = myyear + "-" + mymonth + "-01"
    let endTime = myyear + "-" + mymonth + "-" + myweekday

    $.ajax({
        type: "get",
        url: "/pqs9000/monitorScope/getAreaLineMap",
        data: {
            startTime: startTime,
            endTime: endTime
        },
        beforeSend: function () {
            loading = ityzl_SHOW_LOAD_LAYER();
        },
        dataType: 'json',
        success: function (data) {
            if (data.code == 200) {
                dataArr = data.body;

                let key = []
                let lngArr = []
                let ltgArr = []
                for(let i=0;i<dataArr.length;i++){
                    lngArr.push(dataArr[i].lng)
                    ltgArr.push(dataArr[i].lat)
                    if(key.includes(dataArr[i].subName)){
                        dataArr[i].lng = dataArr[i].lng+0.001
                    }else {
                        key.push(dataArr[i].subName)
                    }
                }

                /*
                                let lngMin = Math.min(...lngArr)-0.009
                                let lngMax = Math.max(...lngArr)+0.009

                                let ltgMin = Math.min(...ltgArr)-0.004
                                let ltgMax = Math.max(...ltgArr)+0.004

                                console.log(lngMin,lngMax)
                                console.log(ltgMin,ltgMax)

                                let aaaa = []
                                var point1 = new BMap.Point(lngMin, ltgMin);
                                var point2 = new BMap.Point(lngMin, ltgMax);
                                var point3 = new BMap.Point(lngMax, ltgMax);
                                var point4 = new BMap.Point(lngMax, ltgMin);
                                var point5 = new BMap.Point(lngMin, ltgMin);
                                aaaa = [point1,point2,point3,point4,point5]



                                var polyline = new BMap.Polyline(aaaa, {strokeColor: color, strokeWeight: 3, strokeOpacity: 1});
                                polyline.setStrokeStyle("dashed");
                                map.addOverlay(polyline)*/

                //自定义区域范围


                var point1 = new BMap.Point(118.744404,33.68198);
                var point1h = new BMap.Point(  118.746775,33.674469);

                var point2 = new BMap.Point(118.751518,33.665635);
                var point2h = new BMap.Point(118.75928,33.660858);
                var point3 = new BMap.Point(118.763376,33.656771);

                var point4 = new BMap.Point(118.76873,33.658875);
                var point5 = new BMap.Point(118.775359,33.661182);

                var point5h = new BMap.Point(118.776617,33.661693);


                var point6 = new BMap.Point(118.78154,33.665449);
                var point6h = new BMap.Point(118.782761,33.667252);

                var point7 = new BMap.Point(118.783642,33.669812);
                var point8 = new BMap.Point(118.783606,33.669511);


                //var point8h = new BMap.Point(118.782914,33.690001);
                //var point8h = new BMap.Point(118.786399,33.692187);

                var point9 = new BMap.Point(118.786399,33.692187);

                var point9h = new BMap.Point(118.768514,33.692134);


                var point10 = new BMap.Point(118.764813,33.688799);
                var point11 = new BMap.Point(118.759531,33.688078);
                var point12 = new BMap.Point(118.744404,33.68198);

                let customArea = [point1,point1h,point2,point2h,point3,point4,point5,point5h,point6,point6h,point7,point8,point9,point9h,point10,point11,point12]
                var polyline = new BMap.Polyline(customArea, {strokeColor: color, strokeWeight: 5, strokeOpacity:1});
                polyline.setStrokeStyle("dashed");
                map.addOverlay(polyline)


                let temArr = dataArr.filter(item => item.hangLine != null)
                let max = Math.max(...temArr.map(line => line.eventCount));
                console.log("==========")

                let arr = []
                if(max === 0){
                    //没有最大暂降数，展示最多挂接线路
                   let group =  arrayGroupBy(dataArr,'hangLine')
                    let tem = group.reduce((prev,next)=>{return prev.length > next.length ? prev:next})
                    tem.forEach(it => {
                        var point1 = new BMap.Point(it.lng, it.lat);
                        arr.push(point1)
                    })

                }else {
                    let maxLine = dataArr.find(line => line.eventCount === max);

                    let newTemArr = dataArr.filter(item => item.hangLine === maxLine.hangLine)

                    newTemArr.forEach(it => {
                        var point1 = new BMap.Point(it.lng, it.lat);
                        arr.push(point1)
                    })


                }

                arr.sort((a, b) => a.lng - b.lng)


                var polyline = new BMap.Polyline(arr, {strokeColor: color, strokeWeight: 3, strokeOpacity: 1});
                polyline.setStrokeStyle("dashed");
                map.addOverlay(polyline)


                drawElement(dataArr, map)


                var view = map.getViewport(eval(monitors));
                var mapZoom = view.zoom;
                var centerPoint = view.center;
                map.centerAndZoom(centerPoint, mapZoom);


                initSelect()


                // var strictBounds=new Bmap.Bounds(new BMap.Point(116.3645,39.9673),new BMap.Point(116.3646,39.9685));//sw西南,ne东北
                var strictBounds = map.getBounds();

                map.addEventListener("dragend", function () {
                    if (strictBounds.containsPoint(map.getCenter())) return;
                    var view = map.getViewport(eval(monitors));
                    var mapZoom = view.zoom;

                    let tem = mapZoom;
                    var now = map.getZoom();

                    if (now >= mapZoom) {
                        tem = now
                    }
                    var centerPoint = view.center;
                    map.centerAndZoom(centerPoint, tem);
                })

                map.addEventListener("zoomstart", function () {

                    if (strictBounds.containsPoint(map.getCenter())) return;
                    var view = map.getViewport(eval(monitors));


                    var mapZoom = view.zoom;


                    let tem = mapZoom;

                    var now = map.getZoom();

                    if (now >= mapZoom) {
                        tem = now
                    }
                    var centerPoint = view.center;
                    map.centerAndZoom(centerPoint, tem);
                })


            } else {
                layer.msg(data.message, {icon: 2, time: 2000});
            }

            //***********关闭loading
            ityzl_CLOSE_LOAD_LAYER(loading);


        }
    })

    getAreaLineEventCount(startTime, endTime)
}


function getAreaLineEventCount(startTime, endTime) {
    $.ajax({
        type: 'get',
        url: '/pqs9000/monitorScope/getAreaLineEventCount',
        data: {
            startTime: startTime,
            endTime: endTime
        },
        success: function (data) {
            if (data.code === 200) {
                $("#leftContent").empty()
                let da = data.body;

                let html =
                    '<label style=\"color:' + color + ';font-size: 13px;font-weight: bold;\">统计时间: ' + startTime + '至' + endTime + '</label><br>' +
                    '<label style=\"color:' + color + ';font-size: 13px;font-weight: bold; \">监测点统计:</label><button id="monitorInfo" class="btn btn-primary" style="float: right;margin-right: 20px">监测点详情</button><br>' +
                    '<label style=color:' + color + '>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;总数: ' + da.monitorAllCount + '  (个)</label><br>' +
                    '<label style=color:' + color + '>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;在线: ' + da.onlineMonitorCount + '  (个)</label><br>' +
                    '<label style=color:' + color + '>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;离线: ' + (da.monitorAllCount - da.onlineMonitorCount) + '  (个)</label><br>' +
                    '<label style=\"color:' + color + ';font-size: 13px;font-weight: bold;\">暂降事件:</label><button id="eventInfo" style="float: right;margin-right: 20px" class="btn btn-primary">暂态事件详情</button><br>' +
                    '<label style=color:' + color + '>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;暂态事件个数: ' + da.eventCount + '  (个)</label><br>'+
                    '<label style=\"color:' + color + ';font-size: 13px;font-weight: bold;\">一次接线图:</label><button class="btn btn-primary" style="float: right;margin-right: 20px" id="oneImag" onclick="openmonitorImg()">一次接线图</button><br>'

                $("#leftContent").html(html)

            } else {
                layer.msg(data.message, {icon: 2, time: 2000});
            }
        }
    })
}


//初始化下拉框数据
function initSelect() {
    $('.selectpicker').selectpicker('val', '');
    $('.selectpicker').selectpicker('refresh');

    let html = "<option value='0'>---请选择监测点---</option>";
    for (var i = 0; i < dataArr.length; i++) {
        html += "<option  value='" + dataArr[i].lineId + "'data-name='" + dataArr[i].lineName + "'>" + dataArr[i].subName + "  #" + dataArr[i].lineName + "</option>";
    }
    $("#select_article").html(html);
    $('.selectpicker').selectpicker('refresh');//加载select框选择器


    $("#select_article").change(function () {
        searchPoint()
    })
}


function getPoint(lineMap, map) {
    var point = new BMap.Point(lineMap.lng, lineMap.lat);
    if (lineMap.lng > 0 && lineMap.lat > 0) {
        monitors.push(point)
    }

    //监测点点位信息;终端状态;终端状态颜色
    var marker, strState = '退运', fontState = '#808080';
    //通讯状态,通讯状态颜色
    var strStatus = '中断', fontStatus = '#FF0000';
    /********************************
     终端状态：  2退运    灰色 128,128,128  #808080
     1检修   金色 255,215,0   #FFD700
     0投运（正常的则判断通讯状态）
     通讯状态：  0正常    绿色  0,128,0   #08CF5A
     1中断    红色  255,0,0   #FF0000
     **********************************/
    switch (lineMap.runFlag) {
        case 0:
            strState = '投运';
            fontState = '#08CF5A';
            //终端通讯状态（0：中断；1：正常）
            switch (lineMap.comFlag) {
                case 0:
                    strStatus = '中断';
                    fontStatus = '#FF0000';
                    if (lineMap.eventCount > 0)
                        marker = new BMap.Marker(point, wingreenMarkerOptions);//假如终端出现了暂降事件
                    else
                        marker = new BMap.Marker(point, redMarkerOptions);
                    break;
                case 1:
                    strStatus = '正常';
                    fontStatus = '#08CF5A';
                    if (lineMap.eventCount > 0)
                        marker = new BMap.Marker(point, wingreenMarkerOptions);//假如终端出现了暂降事件
                    else
                        marker = new BMap.Marker(point, greenMarkerOptions);
                    break;
            }
            break;
        case 1:
            strState = '检修';
            fontState = '#FFD700';
            if (lineMap.eventCount > 0)
                marker = new BMap.Marker(point, yellowMarkerOptions);//假如终端出现了暂降事件
            else
                marker = new BMap.Marker(point, yellowMarkerOptions);
            break;
        case 2:
            strState = '退运';
            fontState = '#808080';
            if (lineMap.eventCount > 0)
                marker = new BMap.Marker(point, grayMarkerOptions);
            else
                marker = new BMap.Marker(point, grayMarkerOptions);
            break;
    }
    //设置marker其他属性
    marker.lineId = lineMap.lineId;//存储监测点的id
    marker.lineName = lineMap.lineName;//存储监测点的名称
    marker.runFlag = lineMap.runFlag;//存储监测点的状态
    marker.eventCount = lineMap.eventCount;//存储未处理事件

    marker.lineMap = lineMap;//所存储的监测点信息


    let hang = lineMap.hangLine == null ? "/" : lineMap.hangLine
    var strTitle = '监测点名称: ' + lineMap.subName + "_" + lineMap.lineName;
    strTitle += '\n' + '挂接线路: ' + hang;
    if (lineMap.eventCount > 0) {
        strTitle += '\n' + '暂降事件发生次数：' + lineMap.eventCount + '(次)';
    }


    marker.setTitle(strTitle);//设置标注的标题，当鼠标移至标注上时显示此标题
    /************************************
     设置弹出框相关内容
     ************************************/

        //监测点界面
        //组装TIP
    var showInfo = '<div class="mystyle" style="margin:0;line-height:19px;padding:2px;font-size:12px;font-family:"微软雅黑";font-weight:bold;">' +
            '<label>&nbsp;&nbsp;&nbsp;所属企业&nbsp;&nbsp;&nbsp;</label>&nbsp;' + lineMap.subName + '<br/>' +
            '<label>&nbsp;&nbsp;&nbsp;&nbsp;母线&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</label>&nbsp;' + lineMap.busBarName + '<br/>' +
            '<label>&nbsp;&nbsp;&nbsp;挂接线路&nbsp;&nbsp;&nbsp;</label>&nbsp;' + hang + '<br/>' +
            '<label>&nbsp;&nbsp;&nbsp;IP地址&nbsp;&nbsp;&nbsp;</label>&nbsp;' + lineMap.ip + '<br/>' +
            '<label>&nbsp;&nbsp;PT变比&nbsp;&nbsp;</label>&nbsp;' + lineMap.pt1 / 1000 + '/' + lineMap.pt2 / 1000 + '<br/>' +
            '<label>&nbsp;&nbsp;CT变比&nbsp;&nbsp;</label>&nbsp;' + lineMap.ct1 + '/' + lineMap.ct2 + '<br/>' +
            '<label>&nbsp;生产厂家&nbsp;</label>&nbsp;' + lineMap.manufacturer + '<br/>' +
            '<label>&nbsp;终端状态&nbsp;</label>&nbsp;<font color="' + fontState + '">' + strState + '</font><br/>' +
            '<label>&nbsp;通讯状态&nbsp;</label>&nbsp;<font color="' + fontStatus + '">' + strStatus + '</font><br/>' +
            '<label style="float: right;"><button onclick="toMonitorPage()" class="btn btn-primary">监测点详细信息</button></label>&nbsp;<br/>' +

            '<div class="form-inline fr" style="margin:5px 0px 1px 2px;">' +
            '</div>';

    var searchInfoWindow = new BMapLib.SearchInfoWindow(map, showInfo, {
        title: '监测点名称：' + lineMap.lineName, //标题
        width: 250, //宽度
        height: 260, //高度
        searchTypes: [],
        enableSendToPhone: false
    });

    marker.searchInfoWindow = searchInfoWindow;
    marker.addEventListener("click", function () {
        searchInfoWindow.open(point);
        var allOverlay = map.getOverlays();
        let index = 0
        for (var i = 0; i < allOverlay.length; i++) {

            if (allOverlay[i].toString().indexOf("Polyline") > 0) {//删除折线
                if(index>0){
                    map.removeOverlay(allOverlay[i]);
                }
                index++;
            }

        }

        if (lineMap.hangLine !== null) {
            let temArr = dataArr.filter(item => item.hangLine === lineMap.hangLine)
            let arr = []
            temArr.forEach(it => {
                var point1 = new BMap.Point(it.lng, it.lat);
                arr.push(point1)
            })

            arr.sort((a, b) => a.lng - b.lng)

            var polyline = new BMap.Polyline(arr, {strokeColor: color, strokeWeight: 3, strokeOpacity: 1});
            polyline.setStrokeStyle("dashed");
            map.addOverlay(polyline)
        }
    });
    return marker;
}


function searchPoint() {
    var searchPoint = document.getElementById('select_article');
    if (searchPoint.value != "") {
        var marker;
        for (var i = 0; i < markers.length; i++) {
            marker = markers[i];

            //先匹配是否有全名称的
            if (marker.lineId == searchPoint.value) {
                map.centerAndZoom(marker.getPosition(), 15);
                marker.searchInfoWindow.open(marker.getPosition());
                break;
            }
        }
    } else {
        parent.layer.msg("请输入监测点名称!", {icon: 5, time: 2000});
    }
}

//跳转到监测点页面
function toMonitorPage(lineId) {

    parent.addTab('monitor','在线监测点')

}

//查看监测点一次接线图
function openmonitorImg() {
    layer.open({
        type: 1,
        title: '一次接线图',
        maxmin: false,
        resize: false,
        shadeClose: true, //点击遮罩关闭层
        area: ['90%', '90%'],
        content: '<div style="padding: 10px;width: 100%;height: 100%;"><img style="width: 100%;height: 100%"; src="/cdf/oneConnect.png"></div>',
        scrollbar: false
    });
}


function drawElement(dataarr, map) {
    let colors = [];  // 存储已生成的颜色
    //解析Map
    for (key in dataarr) {
        //解析监测点信息
        let lineDetail = dataarr[key];
        let pointmarker = getPoint(lineDetail, map);
        map.addOverlay(pointmarker);
        markers.push(pointmarker);//把监测点信息放到集合中去
    }

    /* pLineArr.forEach(item=>{
         let arr= [];
         item.forEach(it=>{
             var point1 = new BMap.Point(it.lng, it.lat);
             arr.push(point1)
         })

         let color;
         do {
             // 生成随机颜色
             let r = Math.floor(Math.random() * 256);
             let g = Math.floor(Math.random() * 256);
             let b = Math.floor(Math.random() * 256);
             color = 'rgb(' + r + ',' + g + ',' + b + ')';
         } while (colors.includes(color) || isLightColor(color));  // 如果颜色已经存在，就重新生成

         colors.push(color);  // 将新颜色添加到数组中
         var polyline = new BMap.Polyline(arr, {strokeColor: color, strokeWeight: 3, strokeOpacity: 1});
         polyline.setStrokeStyle("dashed");
         map.addOverlay(polyline)
     })*/
}


const groupBy = (array, f) => {
    let groups = {};
    array.forEach(function (o) {
        var group = JSON.stringify(f(o));
        groups[group] = groups[group] || [];
        groups[group].push(o);
    });
    return Object.keys(groups).map(function (group) {
        return groups[group];
    });
};

const arrayGroupBy = (list, groupId) => {
    let sorted = groupBy(list, function (item) {
        return [item[groupId]];
    });
    return sorted;
};


//创建图标
var redIcon = new BMap.Icon("../images/img/pred.png", new BMap.Size(20, 20));
var greenIcon = new BMap.Icon("../images/img/pgreen.png", new BMap.Size(30, 30));
var yellowIcon = new BMap.Icon("../images/img/pyellow.png", new BMap.Size(20, 20));
var grayIcon = new BMap.Icon("../images/img/pgray.png", new BMap.Size(20, 20));
var stationIcon = new BMap.Icon("../images/img/station.png", new BMap.Size(25, 25));
var wingrayIcon = new BMap.Icon("../images/img/wingray.gif", new BMap.Size(40, 40));
var wingreenIcon = new BMap.Icon("../images/img/wingreen.gif", new BMap.Size(30, 30));
var winredIcon = new BMap.Icon("../images/img/winred.gif", new BMap.Size(30, 30));


var redMarkerOptions = {icon: redIcon, enableDragging: false}
var greenMarkerOptions = {icon: greenIcon, enableDragging: false}
var yellowMarkerOptions = {icon: yellowIcon, enableDragging: false}
var grayMarkerOptions = {icon: grayIcon, enableDragging: false}

var wingreenMarkerOptions = {icon: wingreenIcon, enableDragging: false}
var winredMarkerOptions = {icon: winredIcon, enableDragging: false}

