
// var BASE_URL = "http://192.168.10.102:9023";
var BASE_URL = window.BASE_URL;
var APP_URL = window.APP_URL;
for (var i = 0; i < xianjie.features.length; i++) {
    xianjie.features[i].id = i + 1;
}

var present_Township = "";
// console.log(xianjie);
var townshipCaseCount = [];
var newsReportDataGeoJsonArr = []
var historyCaseGeoJsonArr = []
var townshipCaseCountArr = [];
var colorSelect = [];

function loadMainMap() {
    $.ajax({
        type: "GET",
        url: BASE_URL + "/api/DroneScreenDisplay/GetDroneOrgCount",
        dataType: "json",
        headers: { "X-Token": localStorage.getItem("X-Token") },
        async: false,
        data: {},
        beforeSend: function (xhr) { },
        success: function (data) {
            townshipCaseCount = data.result;
            // console.log("townshipCaseCount",townshipCaseCount);
        }
    });

    townshipCaseCount.forEach((item, index) => {
        townshipCaseCountArr[index] = item.reportCount;
    })

    var bigCount = 0;
    var smallCount = 9999;
    for (var i = 0; i < townshipCaseCountArr.length; i++) {
        if (townshipCaseCountArr[i] > bigCount) {
            bigCount = townshipCaseCountArr[i]
        }
        if (townshipCaseCountArr[i] < smallCount) {
            smallCount = townshipCaseCountArr[i]
        }
    }

    let unit = (bigCount - smallCount) / 12;

    colorSelect = ['interpolate', ['linear'], ['get', 'count'],
        smallCount, '#43E1F8',
        smallCount + unit * 2, '#49B0F9',
        smallCount + unit * 3, '#3EABFA',
        smallCount + unit * 4, '#27A2FB',
        smallCount + unit * 5, '#34E6B1',
        smallCount + unit * 6, '#1099FB',
        smallCount + unit * 7, '#0695FB',
        smallCount + unit * 8, '#058DEE',
        smallCount + unit * 9, '#09C78E',
        smallCount + unit * 10, '#047DD4',
        smallCount + unit * 11, '#94D515',
        smallCount + unit * 12, '#0568B0',
    ]
    // console.log(colorSelect);
    xianjie.features.forEach(function (item, index) {
        var towninfo = townshipCaseCount.filter(function (it, idx) {
            return it.name == item.properties.name
        })
        xianjie.features[index].properties.count = towninfo[0].reportCount;
        xianjie.features[index].properties.newestCount = towninfo[0].todayCount;
    })
}

// 获取乡镇等数据
loadMainMap();
//console.log("xianjie",xianjie);

var worldMapContainer1 = document.getElementById('distribution_map');
worldMapContainer1.style.height = "610px";
worldMapContainer1.style.width = "970px";
worldMapContainer1.style.position = "relative";
worldMapContainer1.style.left = "30px";

mapboxgl.accessToken = 'pk.eyJ1Ijoic2hpY2hhbzEyMyIsImEiOiJja3FobnI1aDEwNGF6Mm9vOXVhNnBzZmFhIn0.2fZKiMqCQHxVY74QShMEGQ';
let map = new mapboxgl.Map({
    container: 'distribution_map',
    style: {
        glyphs: "mapbox://fonts/mapbox/{fontstack}/{range}.pbf",
        "version": 8,
        "sources": {
            // "raster-tiles": {
            //     "type": "raster",
            //     "tiles": ['http://t0.tianditu.gov.cn/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=ed82a9d17a463c1c604f7e1f40293f25'],
            //     "tileSize": 256,
            //   }
        },
        "layers": [
            // {
            //     "id": "tdt-img-tiles",
            //     "type": "raster",
            //     "source": "raster-tiles",
            //     "minzoom": 0,
            //     "maxzoom": 22
            // },
        ]
    },
    zoom: 7.6,
    center: [118.284576,35.199955],
});
var size = 200;

var pulsingDot = {
    width: size,
    height: size,
    data: new Uint8Array(size * size * 4),

    onAdd: function () {
        var canvas = document.createElement('canvas');
        canvas.width = this.width;
        canvas.height = this.height;
        this.context = canvas.getContext('2d');
    },

    render: function () {
        var duration = 1000;
        var t = (performance.now() % duration) / duration;
        var radius = size / 2 * 0.3;
        var outerRadius = size / 2 * 0.7 * t + radius;
        var context = this.context;
        context.clearRect(0, 0, this.width, this.height);
        context.beginPath();
        context.arc(this.width / 2, this.height / 2, outerRadius, 0, Math.PI * 2);
        context.fillStyle = 'rgba(255, 200, 200,' + (1 - t) + ')';
        context.fill();
        context.beginPath();
        context.arc(this.width / 2, this.height / 2, radius, 0, Math.PI * 2);
        context.fillStyle = 'rgba(255, 100, 100, 1)';
        context.strokeStyle = 'white';
        context.lineWidth = 2 + 4 * (1 - t);
        context.fill();
        context.stroke();
        this.data = context.getImageData(0, 0, this.width, this.height).data;
        map.triggerRepaint();

        return true;
    }
};


var UAVMarkerArray = [];
var flvMarkerArray = []
var flvDataArray = []
var DroneMarkerArray = [];
var UAVInfo = [];
var getUAVMarkersTimer = null;

var newestCountMarkerArray = [];
var historyCountMarkerArray = [];

// 无人机
function loadUAVBox(data) {
    // var data = {
        // "account": "17853305026",
        // "createtime": "2023-11-08 09:58:16",
        // "height": 185,
        // "ip": "192.168.10.101",
        // "lat": 35.264007,
        // "lng": 118.130002,
        // "model": "airPlaneModel"
    // }
    if (flvMarkerArray.length > 0) {
        $('#UAVView').attr("data-isActive", "true")
        $('#UAVView').css("color", "#FFF726")
        $("#UAVView").find(".centerimg").css('display', 'none')
        $("#UAVView").find(".centerimgActive").css('display', 'inline-block')
        for (var i = 0; i < window.flvMarkerArray.length; i++) {
            window.flvMarkerArray[i].remove(map);
        }
    }
    if (data && data.account) {
        $('#UAVView').attr("data-isActive", "true")
        $('#UAVView').css("color", "#FFF726")
        $("#UAVView").find(".centerimg").css('display', 'none')
        $("#UAVView").find(".centerimgActive").css('display', 'inline-block')
        // console.log('loadUAVBox')
        if (flvDataArray.find(info => info.account === data.account)) {
            // console.log('已存在')
            info = data
        } else {
            flvDataArray.push(data)
        }
        flvMarkerArray = []
        flvDataArray.forEach(element => {
            var arr = []
            arr.push(element.lng)
            arr.push(element.lat)
            let coordinate = arr
            let el = document.createElement('img')
            el.id = 'markerId'
            el.src = 'images/unmanned.png'
            el.setAttribute("phone", element.account);
            // console.log(coordinate)
            let marker = new mapboxgl.Marker(el).setLngLat(coordinate).addTo(map) // 将标记添加到地图上
            window.flvMarkerArray.push(marker);
            el.addEventListener('click', (e) => {
                $('.bgPop5,.pop5').show();
                var phone = el.getAttribute("phone")
                if(phone == '17853305026'){
                    vm.flvStr = "17853305026"
                    localStorage.setItem('flvStr', vm.flvStr)
                    childFlv.window.childFunction()
                }else{
                    vm.flvStr = "http://live.hopetrytech.com/live/" + phone + ".flv"
                    // console.log(vm.flvStr)
                    // var player = TCPlayer('player-container-id', {}); // player-container-id 为播放器容器 ID，必须与 html 中一致
                    // player.src(vm.flvStr); // url 播放地址
                    localStorage.setItem('flvStr', vm.flvStr)
                    myWebSocket.send(data.account)
                    childFlv.window.childFunction()
                }
            })
        });
        for (var i = 0; i < window.flvMarkerArray.length; i++) {
            window.flvMarkerArray[i].addTo(map);
        }

    }
}

// 加载最新上报的数据点
function loadLastReportPoint(caseId, isFirst) {
    if (UAVMarkerArray.length > 0) {
        for (var i = 0; i < window.UAVMarkerArray.length; i++) {
            window.UAVMarkerArray[i].remove(map);
        }
    }

    UAVMarkerArray = [];

    $.ajax({
        type: "GET",
        url: BASE_URL + "/api/DroneScreenDisplay/GetCaseInfo?id=" + caseId,
        dataType: "json",
        headers: { "X-Token": localStorage.getItem("X-Token") },
        async: false,
        data: {},
        beforeSend: function (xhr) { },
        success: function (data) {
            UAVInfo[0] = data.result;
            console.log(!isFirst)
            if (!isFirst) {
                if (audio != null) {
                    audio.pause();
                    audio = null;
                }
                audio = "./audio/" + data.result.info.streetname + ".mp3";
                console.log(audio);
                audio = new Audio(audio);
                audio.play();
            }

        }
    });

    for (var i = 0; i < 1; i++) {
        var el = document.createElement('div');
        el.className = 'marker';
        el.style.backgroundSize = '100%';

        var point = document.createElement("div");
        point.className = 'point';

        el.appendChild(point);
        el.setAttribute("data-caseId", UAVInfo[i].info.id);

        var uavimg = document.createElement("div");
        // uavimg.className="UAVImg";

        var uavimgCon = document.createElement("div");
        uavimgCon.className = "uavimgCon";

        uavimgCon.appendChild(el);
        uavimgCon.append(uavimg);

        el.className = "uavmarker";
        $(document).on("click", '.uavmarker', function (e) {
            console.log($(this).attr("data-caseId"))
            var caseid = $(this).attr("data-caseId")
            var IMAGE_BASE_URL = "http://60.213.14.14:6070";
            $.ajax({
                type: "GET",
                url: BASE_URL + "/api/DroneScreenDisplay/GetCaseInfo",
                dataType: "json",
                headers: { "X-Token": localStorage.getItem("X-Token") },
                data: { id: caseid },
                async: false,
                beforeSend: function (xhr) { },
                success: function (data) {
                    if (data.code == 200) {
                        $('.caseinfoNo').text(data.result.info.case_no);
                        $('.caseinfoDesc').text(data.result.info.case_description);
                        $('.caseinfoZoing').text(data.result.info.countyname + "/" + data.result.info.streetname + "/" + data.result.info.communityname);
                        $('.caseinfoType').text(data.result.info.typename);
                        $('.caseinfoMarker').text(data.result.info.remark);
                        $(".caseinfoAddress").text(data.result.info.address);
                        $(".caseinfoTime").text(data.result.info.createtime);
                        $(".caseinfoArea").text(data.result.info.area);
                        $(".caseinfoImages").empty();
                        for (var i = 0; i < data.result.pic_list.length; i++) {
                            var url = IMAGE_BASE_URL + "/" + data.result.pic_list[i];
                            var appendStr = "<img src='" + IMAGE_BASE_URL + "/S_" + data.result.pic_list[i] + "' class='caseInfoImg' data-imgSrc='" + url + "'   style='width:230px;height:100px;margin-right:15px;'/>";
                            $(".caseinfoImages").append(appendStr);
                        }
                        getkmcamera(data.result)
                    }
                    $(".caseInfoImg").click(function () {
                        $(".imgContainers").empty();
                        $(".imgDetail").show()
                        $(".imgDetail").css({ "display": "flex" });
                        var imgPath = $(this).attr("data-imgSrc");
                        var appendStrPath = "<img src='" + imgPath + "' style='width:100%;height:100%;'/>";
                        $(".imgContainers").append(appendStrPath);
                    })
                }
            });
            //console.log($(this).attr("data-caseId"));
            $('.bgPop2,.pop2').show();
        })
        // document.getElementsByClassName('uavmarker').addEventListener('click', (e) => {
        //     // console.log(e.path[1].getAttribute("data-caseId"));
        //     console.log(e)
        //     console.log($(this))
        //     console.log($(this).getAttribute("data-caseId"))
        //     // window.alert(marker.properties.message);
        //     var IMAGE_BASE_URL = "http://60.213.14.14:6070";
        //     $.ajax({
        //         type: "GET",
        //         url: BASE_URL + "/api/DroneScreenDisplay/GetCaseInfo",
        //         dataType: "json",
        //         headers: { "X-Token": localStorage.getItem("X-Token") },
        //         data: { id: e.path[1].getAttribute("data-caseId") },
        //         async: false,
        //         beforeSend: function (xhr) { },
        //         success: function (data) {
        //             if (data.code == 200) {
        //                 $('.caseinfoNo').text(data.result.info.case_no);
        //                 $('.caseinfoDesc').text(data.result.info.case_description);
        //                 $('.caseinfoZoing').text(data.result.info.countyname + "/" + data.result.info.streetname + "/" + data.result.info.communityname);
        //                 $('.caseinfoType').text(data.result.info.typename);
        //                 $('.caseinfoMarker').text(data.result.info.remark);
        //                 $(".caseinfoAddress").text(data.result.info.address);
        //                 $(".caseinfoTime").text(data.result.info.createtime);
        //                 $(".caseinfoArea").text(data.result.info.area);
        //                 $(".caseinfoImages").empty();
        //                 for (var i = 0; i < data.result.pic_list.length; i++) {
        //                     var url = IMAGE_BASE_URL + "/" + data.result.pic_list[i];
        //                     var appendStr = "<img src='" + IMAGE_BASE_URL + "/S_" + data.result.pic_list[i] + "' class='caseInfoImg' data-imgSrc='" + url + "'   style='width:230px;height:100px;margin-right:15px;'/>";
        //                     $(".caseinfoImages").append(appendStr);
        //                 }
        //             }
        //             $(".caseInfoImg").click(function () {
        //                 $(".imgContainers").empty();
        //                 $(".imgDetail").show()
        //                 $(".imgDetail").css({ "display": "flex" });
        //                 var imgPath = $(this).attr("data-imgSrc");
        //                 var appendStrPath = "<img src='" + imgPath + "' style='width:100%;height:100%;'/>";
        //                 $(".imgContainers").append(appendStrPath);
        //             })
        //         }
        //     });
        //     //console.log($(this).attr("data-caseId"));
        //     $('.bgPop2,.pop2').show();
        // });
        console.log(UAVInfo[i])
        var coordinate = [UAVInfo[i].lng, UAVInfo[i].lat];
        // var UAVmarker =  new mapboxgl.Marker(uavimgCon).setLngLat(coordinate).addTo(map);
        var UAVmarker = new mapboxgl.Marker(uavimgCon).setLngLat(coordinate);

        // var UAVmarker2 =  new mapboxgl.Marker(uavimgCon).setLngLat([117.72339712649222,35.05450202665419]).addTo(map);
        window.UAVMarkerArray.push(UAVmarker);

        for (var i = 0; i < window.UAVMarkerArray.length; i++) {
            window.UAVMarkerArray[i].addTo(map);
        }

        // console.log(UAVMarkerArray);

    }
}
function loadNewestReportPoint() {
    // console.log("load++");
    // 加载最新数据
    loadMainMap();

    if (newestCountMarkerArray.length > 0) {
        for (var i = 0; i < newestCountMarkerArray.length; i++) {
            newestCountMarkerArray[i].remove(map);
        }
    }

    if (historyCountMarkerArray.length > 0) {
        for (var i = 0; i < historyCountMarkerArray.length; i++) {
            historyCountMarkerArray[i].remove(map);
        }
    }

    newestCountMarkerArray = [];
    historyCountMarkerArray = [];

    // console.log("townshipCaseCount111",townshipCaseCount);
    let townships = [
        {
            name: "临沭县",
            coordinate: [118.648379,34.917062]
        }, {
            name: "郯城县",
            coordinate: [118.342963,34.614741],
        }, {
            name: "费县",
            coordinate: [117.968869,35.269174],
        }, {
            name: "河东区",
            coordinate: [118.398296,35.085004],
        }, {
            name: "兰山区",
            coordinate: [118.327667,35.061631],
        }, {
            name: "罗庄区",
            coordinate: [118.284795,34.997204],
        }, {
            name: "沂南县",
            coordinate: [118.455395,35.547002],
        }, {
            name: "沂水县",
            coordinate: [118.634543,35.787029],
        }, {
            name: "兰陵县",
            coordinate: [118.049968,34.855573],
        }, {
            name: "平邑县",
            coordinate: [117.631884,35.511519],
        }, {
            name: "莒南县",
            coordinate: [118.838322,35.175911],
        }, {
            name: "蒙阴县",
            coordinate: [117.943271,35.712435],
        }
    ];

    for (var j = 0; j < townships.length; j++) {
        var arr = townshipCaseCount.filter((item, index) => {
            // console.log(item.name);
            if (item.name == townships[j].name) {
                townships[j].newestCount = item.todayCount;
                townships[j].historyCount = item.historyCount;
            }
            return item.name == townships[j].name;
        })
    }

    for (var t = 0; t < townships.length; t++) {
        var townshipContainer = document.createElement('div');
        townshipContainer.className = 'townshipParent';


        var townshipChildren = document.createElement("div");
        townshipChildren.className = 'townshipChildren';

        var townshipName = document.createElement("div");
        townshipName.className = 'townshipName';
        var mytext = document.createTextNode("历史案件：" + townships[t].historyCount);
        townshipName.appendChild(mytext);


        townshipChildren.appendChild(townshipName);
        townshipContainer.appendChild(townshipChildren);

        var township = new mapboxgl.Marker(townshipContainer).setLngLat([townships[t].coordinate[0], townships[t].coordinate[1] - 0.001]);
        historyCountMarkerArray.push(township);

    }

    for (var t = 0; t < townships.length; t++) {
        var newestParent = document.createElement('div');
        newestParent.className = 'newestParent';


        var newestChildren = document.createElement("div");
        newestChildren.className = 'newestChildren';

        var newestName = document.createElement("div");
        newestName.className = 'newestName';
        var mytext = document.createTextNode("最新案件：" + townships[t].newestCount);
        newestName.appendChild(mytext);


        newestChildren.appendChild(newestName);
        newestParent.appendChild(newestChildren);


        var township = new mapboxgl.Marker(newestParent).setLngLat([townships[t].coordinate[0], townships[t].coordinate[1]]);

        newestCountMarkerArray.push(township);

    }



}
function loadDroneMarker() {
    if (DroneMarkerArray.length > 0) {
        for (var i = 0; i < DroneMarkerArray.length; i++) {
            DroneMarkerArray[i].remove(map);
        }
    }
    DroneMarkerArray = [];

    $.ajax({
        type: "GET",
        url: BASE_URL + "/api/DroneScreenDisplay/GetDroneLocationPointsFalse",
        dataType: "json",
        headers: { "X-Token": localStorage.getItem("X-Token") },
        async: false,
        data: {},
        beforeSend: function (xhr) { },
        success: function (data) {
            if (data.code == 200) {
                let results = data.result;
                for (var i = 0; i < results.length; i++) {
                    var el = document.createElement('div');
                    el.className = 'marker';
                    el.style.backgroundSize = '100%';

                    var point = document.createElement("div");
                    point.className = 'point';

                    el.appendChild(point);
                    // el.setAttribute("data-caseId",UAVInfo[i].info.id);

                    var uavimg = document.createElement("div");
                    // uavimg.className="UAVImg";

                    var uavimgCon = document.createElement("div");
                    uavimgCon.className = "uavimgCon";

                    uavimgCon.appendChild(el);
                    uavimgCon.append(uavimg);

                    el.className = "uavmarker";

                    var coordinate = results[i].point[0].point.split(",");
                    console.log("coordinate", coordinate);
                    var DroneMarker = new mapboxgl.Marker(uavimgCon).setLngLat(coordinate).addTo(map);
                    DroneMarkerArray.push(DroneMarkerArray);
                    // var DroneMarker =  new mapboxgl.Marker(uavimgCon).setLngLat(coordinate);

                    // var UAVmarker2 =  new mapboxgl.Marker(uavimgCon).setLngLat([117.72339712649222,35.05450202665419]).addTo(map);
                    // DroneMarkerArray.push(DroneMarker);

                    // for(var i=0;i<DroneMarkerArray.length;i++){
                    // DroneMarkerArray[i].addTo(map);
                    // }
                }
            }
        }
    });

}
map.on('load', function () {
    // loadLastReportPoint(news_report[0].id, true);

    loadNewestReportPoint();

    // loadDroneMarker();
    // 马庄镇
    // var data = {
    //     "account": "17853305026",
    //     "createtime": "2023-11-08 09:58:16",
    //     "height": 185,
    //     "ip": "192.168.10.101",
    //     "lat": 35.104007,
    //     "lng": 118.01002,
    //     "model": "airPlaneModel"
    // }
    // loadUAVBox(data)

    map.loadImage(
        'images/position.png',
        (error, image) => {
            if (error) throw error;

            // Add the image to the map style.
            map.addImage('cat', image);
        }
    );
    map.loadImage(
        'images/history.png',
        (error, image) => {
            if (error) throw error;

            // Add the image to the map style.
            map.addImage('history-icon', image);
        }
    );
    map.loadImage(
        'images/unmanned.png',
        (error, image) => {
            if (error) throw error;

            // Add the image to the map style.
            map.addImage('uav-icon', image);
        }
    );
    map.loadImage(
        'images/camera.png',
        (error, image) => {
            if (error) throw error;

            // Add the image to the map style.
            map.addImage('monitor-icon', image);
        }
    );
    // 背景图层
    map.addLayer({
        "id": "background-id", // 唯一 id （必填）
        "type": "background", // 类型（必填）
        "minzoom": 0, // 最小层级（可选，取值范围为 0 ~ 24。当 style 的 zoom 小于此 minzoom 时，layer 将被隐藏）
        "maxzoom": 24, // 最大层级（可选，取值范围为 0 ~ 24。当 style 的 zoom 大于此 maxzoom 时，layer 将被隐藏）
        "paint": { // 绘制类属性
            "background-color": "#0B122E", // 背景颜色（可选，默认值为 #000000。如果设置了 background-pattern，则 background-color 将无效）
            "background-opacity": 1 // 背景不透明度（可选，取值范围为 0 ~ 1，默认值为 1）
        }
    }
    );
    map.addImage('pulsing-dot', pulsingDot, { pixelRatio: 4 });

    //卫星地图
    map.addLayer({
        'id': 'weixingditu',
        'type': 'raster',
        'source': {
            "type": "raster",
            "tiles": ['https://t0.tianditu.gov.cn/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=ff98577d147820843ec2d04da3c5bad4'],
            "tileSize": 256,
        },
        'paint': {

        },
        'layout': {
            "visibility": "none"
        },
        "metadata": {
            "zIndex": 1
        }
    });
    // 添加影像图
    map.addLayer({
        'id': 'yingxiang',
        'type': 'raster',
        'source': {
            "type": "raster",
            "tiles": ['https://t0.tianditu.gov.cn/DataServer?T=cia_w&x={x}&y={y}&l={z}&tk=ff98577d147820843ec2d04da3c5bad4'],
            "tileSize": 256,
        },
        'paint': {

        },
        'layout': {
            "visibility": "none"
        },
        "metadata": {
            "zIndex": 2
        }
    });

    // 县界图层
    map.addLayer({
        'id': 'countyLayer',
        'type': 'fill',
        'source': {
            'type': 'geojson',
            'data': countygeojson,
        },
        'layout': {
            "visibility": "none"
        },
        'paint': {
            'fill-color': "#1f3cb1",
            'fill-opacity': 0.8,
        },
        "metadata": {
            "zIndex": 3
        }
    });

    // 镇界图层面
    map.addSource("townshipSource", {
        'type': 'geojson',
        'data': xianjie
    });
    map.addSource("townshipSource1", {
        'type': 'geojson',
        'data': xianjie
    });
    map.addLayer({
        'id': 'townshipLayer',
        'type': 'fill',
        'source': 'townshipSource',
        'layout': {
            "visibility": "none"
        },
        'paint': {
            'fill-color': colorSelect,
            'fill-opacity': 1,
        }
    });


    // 镇界图层线
    map.addLayer({
        'id': 'townshipLayerLine',
        'type': 'line',
        'source': 'townshipSource',
        'layout': {
            "visibility": "none"
        },
        'paint': {
            'line-color': "#3f52be",
            'line-width': 1,
            // 'line-pattern':1
        }
    });



    map.addSource("states", {
        "type": "geojson",
        "data": xianjie
    });

    // The feature-state dependent fill-opacity expression will render the hover effect
    // when a feature's hover state is set to true.
    map.addLayer({
        "id": "state-fills",
        "type": "fill",
        "source": "states",
        "layout": {},
        "paint": {
            "fill-color": colorSelect,
            "fill-opacity": ["case",
                ["boolean", ["feature-state", "hover"], false],
                1,
                0.6
            ]
        }
    });

    // 村界
    map.addLayer({
        'id': 'villageLayer',
        'type': 'fill',
        'source': {
            'type': 'geojson',
            'data': villageGeoJson
        },
        'layout': {
            "visibility": "none"
        },
        'paint': {
            'fill-color': [
                'interpolate',
                ['linear'],
                ['get', 'OBJECTID'],
                0,
                '#0234fb',
                3,
                '#0937ef',
                6,
                '#0f39e2',
                9,
                '#143ad4',
                12,
                '#1a3abd',
                15,
                '#1f3cb1',
                18,
                '#233b9e',
                21,
                '#364686',
                24,
                '#6e81ca',
                27,
                '#0234fb',
                30,
                '#0937ef',
                33,
                '#0f39e2',
                36,
                '#143ad4',
                39,
                '#1a3abd',
                42,
                '#1f3cb1',
                45,
                '#233b9e',
                48,
                '#364686',
                51,
                '#6e81ca'
            ],
            'fill-opacity': 1,
        }
    });
    // 历史案件数量
    map.addLayer({
        id: `historyCaseLayer`,
        type: 'symbol',
        source: 'townshipSource',
        filter: ['!', ['has', 'point_count']],
        layout: {
            'icon-image': '',
            visibility: 'none',
            'text-field': '历史案件：{count}',//此属性为需要显示的字段
            'text-size': 12,
            'text-offset': [0, 1],
            'text-allow-overlap': false, // 是否允许文本重叠（可选，默认值为 false。
            'text-anchor': 'top',

        },
        paint: {
            // 绘制类属性
            // 文本类属性（需要设置 text-field）样式才生效
            'text-color': '#ffffff', // 文本的颜色
            'text-translate': [0, 0], // 文本的平移（可选，通过平移 [x, y] 达到一定的偏移量。默认值为 [0, 0]
            'text-translate-anchor': 'map', // 文本的平移锚点，即相对的参考物（可选，可选值为 map、viewport，默认为 map）
        },
    })
    // 最新案件数量
    map.addLayer({
        id: `newCaseLayer`,
        type: 'symbol',
        source: 'townshipSource',
        filter: ['!', ['has', 'point_count']],
        layout: {
            'icon-image': '',
            visibility: 'none',
            'text-field': '最新案件：{newestCount}',//此属性为需要显示的字段
            'text-size': 12,
            'text-offset': [0, -1],
            'text-allow-overlap': false, // 是否允许文本重叠（可选，默认值为 false。
            'text-anchor': 'top',

        },
        paint: {
            // 绘制类属性
            // 文本类属性（需要设置 text-field）样式才生效
            'text-color': '#ffffff', // 文本的颜色
            'text-translate': [0, 0], // 文本的平移（可选，通过平移 [x, y] 达到一定的偏移量。默认值为 [0, 0]
            'text-translate-anchor': 'map', // 文本的平移锚点，即相对的参考物（可选，可选值为 map、viewport，默认为 map）

        },
    })

    // 监控图层
    map.addLayer({
        "id": "monitorLayer",
        "type": "symbol",
        "source": {
            "type": "geojson",
            "data": {
                "type": "FeatureCollection",
                "features": [{
                    "type": "Feature",
                    "geometry": {
                        "type": "Point",
                        "coordinates": [117.7917792737033, 35.13858050971585]
                    }
                }, {
                    "type": "Feature",
                    "geometry": {
                        "type": "Point",
                        "coordinates": [117.72339712649222, 35.05450202665419]
                    }
                }, {
                    "type": "Feature",
                    "geometry": {
                        "type": "Point",
                        "coordinates": [117.95926374172524, 35.08209724883]
                    }
                }]
            }
        },
        "layout": {
            "visibility": "none",
            "icon-image": "monitor-icon"
        }
    });
    // 监控图层
    map.addLayer({
        "id": "monitorTwoLayer",
        "type": "symbol",
        "source": {
            "type": "geojson",
            // "data": shexiangtouJSON
            "data": jiankongJson
        },
        "layout": {
            "visibility": "none",
            "icon-image": "monitor-icon"
        }
    });
    // 无人机
    map.addLayer({
        "id": "UAVView",
        "type": "symbol",
        "source": {
            "type": "geojson",
            "data": {
                "type": "FeatureCollection",
                // "features": [{
                //     "type": "Feature",
                //     "geometry": {
                //         "type": "Point",
                //         "coordinates": [118.130002, 35.264007]
                //     }
                // }, {
                //     "type": "Feature",
                //     "geometry": {
                //         "type": "Point",
                //         "coordinates": [118.01002, 35.104007]
                //     }
                // }, {
                //     "type": "Feature",
                //     "geometry": {
                //         "type": "Point",
                //         "coordinates": [118.030002, 35.204007]
                //     }
                // }]
                features: []
            }
        },
        "layout": {
            "visibility": "none",
            "icon-image": "monitor-icon"
        }
    });

    // 无人机图层
    // map.addLayer({
    //     "id": "uavLayer1",
    //     "type": "symbol",
    //     "source": {
    //         "type": "geojson",
    //         "data": {
    //             "type": "FeatureCollection",
    //             "features": [{
    //                 "type": "Feature",
    //                 "geometry": {
    //                     "type": "Point",
    //                     "coordinates": [118.130002, 35.264007]
    //                 }
    //             },{
    //                 "type": "Feature",
    //                 "geometry": {
    //                     "type": "Point",
    //                     "coordinates": [118.01002, 35.104007]
    //                 }
    //             },{
    //                 "type": "Feature",
    //                 "geometry": {
    //                     "type": "Point",
    //                     "coordinates": [118.030002, 35.204007]
    //                 }
    //             }]
    //         }
    //     },
    //     "layout": {
    //         "visibility":"none",
    //         "icon-image": "pulsing-dot"
    //     }
    // });


    // $.ajax({
    //     type: "GET",
    //     url: BASE_URL + "/api/DroneScreenDisplay/GetDroneLocationPointsFalse",
    //     dataType: "json",
    //     async:false,
    //     data:{},
    //     beforeSend: function(xhr) {},
    //     success: function(data){
    //         let UAVArray = [];
    //         data.result.forEach(function(item,index){
    //             let UAVObj = {
    //                 marker: new mapboxgl.Marker(),
    //                 UAVFly:function(lng,lat){
    //                     this.marker.setLngLat([lng,lat]).addTo(map)
    //                 }
    //             }

    //             UAVArray[index] = marker;
    //         })
    //     }
    // });  


    // 最新上报图层
    //最新上报
    var newsReportData = [];
    var newsReportDataGeoJson = [];
    $.ajax({
        type: "GET",
        url: BASE_URL + "/api/DroneScreenDisplay/LoadDroneCase",
        dataType: "json",
        headers: { "X-Token": localStorage.getItem("X-Token") },
        async: false,
        data: {},
        beforeSend: function (xhr) { },
        success: function (data) {
            newsReportData = data.result;
            newsReportData.forEach(function (item, index) {
                if (item.lng && item.lat) {
                    var reportCase = {
                        "id": item.id,
                        "type": "Feature",
                        "geometry": {
                            "type": "Point",
                            "coordinates": [item.lng, item.lat],
                        },
                        "properties": {
                            "id": item.id
                        },
                    }
                    // newsReportDataGeoJson.features.push(reportCase);
                    var uavimg = document.createElement("div");
                    uavimg.className = "POSIRIONImg";
                    var uavimgCon = document.createElement("div");
                    uavimgCon.className = "uavimgCon";
                    uavimgCon.append(uavimg);
                    var coordinate = [item.lng, item.lat];
                    // var UAVmarker =  new mapboxgl.Marker(uavimgCon).setLngLat(coordinate).addTo(map);
                    var UAVmarker = new mapboxgl.Marker(uavimgCon).setLngLat(coordinate);
                    newsReportDataGeoJson.push(UAVmarker);
                    newsReportDataGeoJsonArr.push(UAVmarker)
                }
                if (index == newsReportData.length - 1) {

                }
            });


        }
    });
    newsReportDataGeoJsonArr.forEach(item => {
        // item.addTo(map);
    })
    // map.addLayer({
    //     "id": "newCaseLayer",
    //     "type": "symbol",
    //     "source": {
    //         "type":"geojson",
    //         "data":newsReportDataGeoJson
    //     },
    //     "layout": {
    //         "visibility":"none",
    //         "icon-image": "cat"
    //     }
    // });
    //历史案件
    function getPolygonCenter(pList) {  //获取多边形中心点
        var area = 0;
        var x = 0;
        var y = 0;
        for (var i = 1; i <= pList.length; i++) {
            var lat = pList[i % pList.length][0];
            var lng = pList[i % pList.length][1];
            var nextLat = pList[i - 1][0];
            var nextLng = pList[i - 1][1];
            var temp = (lat * nextLng - lng * nextLat) / 2;
            area += temp;
            x += (temp * (lat + nextLat)) / 3;
            y += (temp * (lng + nextLng)) / 3;
        }
        x = x / area;
        y = y / area;
        return [x, y];
    };
    var historyCaseGeoJson = {};

    $.ajax({
        type: "GET",
        url: "http://175.27.168.120:8080/geoserver/hangfei/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=hangfei%3Aanjianjilu&maxFeatures=1000000000&outputFormat=application%2Fjson",
        dataType: "json",
        headers: { "X-Token": localStorage.getItem("X-Token") },
        async: false,
        data: {},
        beforeSend: function (xhr) { },
        success: function (data) {
            data.features.forEach(function (item, index) {
                // data.features[index].geometry.type="Point";
                // data.features[index].geometry.coordinates=getPolygonCenter(item.geometry.coordinates[0][0]);
                var uavimg = document.createElement("div");
                uavimg.className = "HISTORyImg";
                var uavimgCon = document.createElement("div");
                uavimgCon.className = "uavimgCon";
                uavimgCon.append(uavimg);
                var coordinate = getPolygonCenter(item.geometry.coordinates[0][0])
                var UAVmarker = new mapboxgl.Marker(uavimgCon).setLngLat(coordinate);
                historyCaseGeoJsonArr.push(UAVmarker);
            })
            historyCaseGeoJson = data;
            //console.log(data);
            // getPolygonCenter(data.features.geometry.coordinates[0][0])
        }
    });
    // map.addLayer({
    //     "id": "historyCaseLayer",
    //     "type": "symbol",
    //     "source": {
    //         "type": "geojson",
    //         "data": historyCaseGeoJson,
    //     },
    //     "layout": {
    //         "visibility":"none",
    //         "icon-image": "history-icon"
    //     }
    // });




    // map.addLayer({
    // "id": "state-borders",
    // "type": "line",
    // "source": "states",
    // "layout": {},
    // "paint": {
    // "line-color": "#627BC1",
    // "line-width": 2
    // }
    // });

    // map.addSource('wms-test-source', {
    //     'type': 'raster',
    //     // use the tiles option to specify a WMS tile source URL
    //     // https://docs.mapbox.com/mapbox-gl-js/style-spec/sources/
    //     'tiles': [
    //         'http://175.27.168.120:8080/geoserver/feixian/wms?service=WMS&version=1.1.0&request=GetMap&layers=feixian%3Ayingxiang&bbox=581713.2990911475%2C3882682.1443521073%2C610409.5371911475%2C3916536.5138721075&width=650&height=768&srs=EPSG%3A4509&format=application/openlayers'
    //     ],
    //     'tileSize': 256
    //     });
    // map.addLayer(
    //     {
    //     'id': 'wms-test-layer',
    //     'type': 'raster',
    //     'source': 'wms-test-source',
    //     'paint': {}
    //     },
    //     // 'aeroway-line'
    // );


    var popup = new mapboxgl.Popup({
        closeButton: false,
        closeOnClick: false,

    });

    map.on('mousemove', 'townshipLayer', (e) => {
        // e.preventDefault();
        console.log(e)
        map.getCanvas().style.cursor = 'pointer';
        // var coordinates = e.features[0].geometry.coordinates.slice();
        // const description = e.features[0].properties.description;
        var townshipInfo = townshipCaseCount.filter(item => {
            return item.name == e.features[0].properties.XZQMC;
        })

        var str = "乡镇名称：" + e.features[0].properties.XZQMC + "<br> &nbsp;<br>案件数量：" + townshipInfo[0].reportCount;
        popup.setLngLat([e.lngLat.lng, e.lngLat.lat]).setHTML("<p style='color:#333;font-weight:bold;'>" + str + "</p>").addTo(map);

    });

    var hoveredStateId = null;
    map.on("click", function (e) {
        // console.log(e);
    })
    map.on("mousemove", "townshipLayer", function (e) {
        if (e.features.length > 0) {
            if (hoveredStateId) {
                map.setFeatureState({ source: 'townshipSource', id: hoveredStateId }, { hover: false });
            }
            hoveredStateId = e.features[0].id;
            map.setFeatureState({ source: 'townshipSource', id: hoveredStateId }, { hover: true });
        }
    });

    // When the mouse leaves the state-fill layer, update the feature state of the
    // previously hovered feature.
    map.on("mouseleave", "townshipLayer", function () {
        if (hoveredStateId) {
            map.setFeatureState({ source: 'townshipSource', id: hoveredStateId }, { hover: false });
        }
        hoveredStateId = null;
    });



    map.on("click", "townshipLayer", (e) => {
        //console.log(e.lngLat.lng,e.lngLat.lat);
    })

    map.on("click", "historyCaseLayer", (e) => {

        var currentHistoryCaseId = e.features[0].properties.Id;
        //console.log(currentHistoryCaseId);

    })


    map.on("mousemove", "state-fills", function (e) {
        map.getCanvas().style.cursor = 'pointer';


        var townshipInfo = townshipCaseCount.filter(item => {
            return item.name == e.features[0].properties.name;
        })

        let jrajs = townshipInfo[0].todayCount || ''
        let lsajs = townshipInfo[0].historyCount || ''
        var str = "区域名称：" + e.features[0].properties.name + "<br> &nbsp;<br>案件数量：" + townshipInfo[0].reportCount;
        popup.setLngLat([e.lngLat.lng, e.lngLat.lat]).setHTML("<p style='color:#333;font-weight:bold;'>" + str + "</p>").addTo(map);

        if (e.features.length > 0) {
            if (hoveredStateId) {
                map.setFeatureState({ source: 'states', id: hoveredStateId }, { hover: false });
            }
            hoveredStateId = e.features[0].id;
            map.setFeatureState({ source: 'states', id: hoveredStateId }, { hover: true });
        }
    });

    // When the mouse leaves the state-fill layer, update the feature state of the
    // previously hovered feature.
    map.on("mouseleave", "state-fills", function () {
        if (hoveredStateId) {
            map.setFeatureState({ source: 'states', id: hoveredStateId }, { hover: false });
        }
        hoveredStateId = null;
        popup.remove();
    });

    map.on("click", "newCaseLayer", (e) => {
        // //console.log("helloVue",e.features[0]);
        var currentHistoryCaseId = e.features[0].properties.id;
        $.ajax({
            type: "GET",
            url: BASE_URL + "/api/DroneScreenDisplay/GetCaseInfo",
            dataType: "json",
            headers: { "X-Token": localStorage.getItem("X-Token") },
            data: { id: currentHistoryCaseId },
            async: false,
            beforeSend: function (xhr) { },
            success: function (data) {
                if (data.code == 200) {
                    $('.caseinfoNo').text(data.result.info.case_no);
                    $('.caseinfoDesc').text(data.result.info.case_description);
                    $('.caseinfoZoing').text(data.result.info.countyname + "/" + data.result.info.streetname + "/" + data.result.info.communityname);
                    $('.caseinfoType').text(data.result.info.typename);
                    $('.caseinfoMarker').text(data.result.info.remark);
                    $(".caseinfoAddress").text(data.result.info.address);
                    $(".caseinfoTime").text(data.result.info.createtime);
                    $(".caseinfoArea").text(data.result.info.area);
                    $(".caseinfoImages").empty();
                    for (var i = 0; i < data.result.pic_list.length; i++) {
                        var appendStr = "<img src='" + IMAGE_BASE_URL + "/" + data.result.pic_list[i] + "' class='caseInfoImg'  style='width:230px;height:100px;margin-right:15px;'/>";
                        $(".caseinfoImages").append(appendStr);
                    }
                }
                $(".caseInfoImg").click(function () {
                    $(".imgContainers").empty();
                    $(".imgDetail").show()
                    $(".imgDetail").css({ "display": "flex" });
                    var imgPath = $(this).context.currentSrc
                    var appendStrPath = "<img src='" + imgPath + "' style='width:100%;height:100%;'/>";
                    $(".imgContainers").append(appendStrPath);
                })
            }
        });
        $('.bgPop2,.pop2').show();
    })
    map.on("click", "monitorTwoLayer", (e) => {
        // cameraindexcode 监控ID；channelno 设备通道；
        console.log(e.features[0].properties)
        $('.bgPop4,.pop4').show();
        vm.iframeVisble = true
        localStorage.setItem("monitorTwoLayerData", JSON.stringify(e.features[0].properties))
        child.window.childFunction();
    })
    map.on('click', 'markerId', (e) => {
        console.log(e.features[0].properties)

    })
    map.on("click", "UAVLayer", (e) => {
        $('.bgPop5,.pop5').show();
    })
});


var myWebSocket2 = null;
var lockReconnect2 = false
var myWebSocketTimer2 = null;

function websocketReconnect2() {
    if (lockReconnect2) {       // 是否已经执行重连
        return;
    };
    lockReconnect2 = true;
    // 没连接上会一直重连，设置延迟避免请求过多
    var tt = null;
    tt && clearTimeout(tt);

    var _this = this;
    tt = setTimeout(function () {
        initWebSocket2();
        lockReconnect2 = false;
        // console.log("正在发起2次WebSocket重连")
    }, 5000)
}



for (var i = 0; i < $(".center_top_con_but").length; i++) {
    if ($(".center_top_con_but").eq(i).attr("data-isActive") == "true") {
        $(".center_top_con_but").eq(i).css({ "color": "#FFF71E" });
    }
}

$(".center_top_con_but").click(function () {
    var layerName = $(this).attr("data-layerName");
    var isActive = $(this).attr("data-isActive");

    if (layerName == "uavLayer") {
        if (isActive == 'true') {
            for (var i = 0; i < window.UAVMarkerArray.length; i++) {
                window.UAVMarkerArray[i].remove(map);
            }
            $(this).attr("data-isActive", "false");
            $(this).css({ color: "#fff" });
            $(this).find(".centerimg").show()
            $(this).find(".centerimgActive").hide()
            if (getUAVMarkersTimer) {
                clearInterval(getUAVMarkersTimer);
                getUAVMarkersTimer = null;
            }
        } else {
            for (var i = 0; i < window.UAVMarkerArray.length; i++) {
                window.UAVMarkerArray[i].addTo(map);
            }
            $(this).css({ "color": "#FFF71E" });
            $(this).attr("data-isActive", "true");
            $(this).find(".centerimg").hide()
            $(this).find(".centerimgActive").show()
        }
        return;
    }
    if (layerName == "newCaseLayer") {

        if (isActive == 'true') {
            newestCountMarkerArray.forEach(item => {
                item.remove(map);
            })
            $(this).attr("data-isActive", "false");
            $(this).css({ color: "#fff" });
            $(this).find(".centerimg").show()
            $(this).find(".centerimgActive").hide()


        } else {
            if ($(".historyCaseLayer").attr("data-isActive") == "true") {

                historyCountMarkerArray.forEach(item => {
                    item.remove(map);
                })
                $(".historyCaseLayer").attr("data-isActive", "false");
                $(".historyCaseLayer").css({ color: "#fff" });
                $(".historyCaseLayer").find(".centerimg").show()
                $(".historyCaseLayer").find(".centerimgActive").hide()
            }
            loadNewestReportPoint();

            newestCountMarkerArray.forEach(item => {
                item.addTo(map);
            })
            $(this).css({ "color": "#FFF71E" });
            $(this).attr("data-isActive", "true");
            $(this).find(".centerimg").hide()
            $(this).find(".centerimgActive").show()
        }
        return;
    }


    if (layerName == "historyCaseLayer") {
        if (isActive == 'true') {
            historyCountMarkerArray.forEach(item => {
                item.remove(map);
            })
            $(this).attr("data-isActive", "false");
            $(this).css({ color: "#fff" });
            $(this).find(".centerimg").show()
            $(this).find(".centerimgActive").hide()
        } else {
            loadNewestReportPoint();
            if ($(".newCaseLayer").attr("data-isActive") == "true") {
                newestCountMarkerArray.forEach(item => {
                    item.remove(map);
                })
                $(".newCaseLayer").attr("data-isActive", "false");
                $(".newCaseLayer").css({ color: "#fff" });
                $(".newCaseLayer").find(".centerimg").show()
                $(".newCaseLayer").find(".centerimgActive").hide()
            }

            historyCountMarkerArray.forEach(item => {
                item.addTo(map);
            })
            $(this).css({ "color": "#FFF71E" });
            $(this).attr("data-isActive", "true");
            $(this).find(".centerimg").hide()
            $(this).find(".centerimgActive").show()
        }
        return;
    }

    var visibility = map.getLayoutProperty(layerName, "visibility");
    if (visibility === "visible") {
        map.setLayoutProperty(layerName, "visibility", "none");
        $(this).css({ color: "#fff" });
        $(this).find(".centerimg").show()
        $(this).find(".centerimgActive").hide()
    } else {
        map.setLayoutProperty(layerName, "visibility", "visible");
        $(this).css({ "color": "#FFF71E" });
        $(this).find(".centerimg").hide()
        $(this).find(".centerimgActive").show()
    }

})

// })
