<template>
  <div class="data-map" ref="datamap" id="mapbox"></div>
</template>

<script>
import { postMethodCommon, getMethodCommon } from "../../../../api/common";
import mapboxgl from "mapbox-gl";
import { waiData } from "../../../../assets/xianjiewai";
import * as turf from '@turf/turf';
import { parse } from '../../../home/lib/handleGeojson.js'
import axios from "axios";

mapboxgl.accessToken = "pk.eyJ1Ijoic2hpY2hhbzEyMyIsImEiOiJja3FobnI1aDEwNGF6Mm9vOXVhNnBzZmFhIn0.2fZKiMqCQHxVY74QShMEGQ";
export default {
  props: [ "flyCenter","trajectory","trajectoryIdRandom","rangePhone","rangePhoneRandom","listQuery","listUpdate","currentStreet"],
  data() {
    return {
      map: null,
      clockInList: [],
      markerArr:[],
      popup:null,
      startPoint:null,
      endPoint:null,
      trajectoryLayerCenter:null,
      clockInLayerGeoJson:{
        "type": "FeatureCollection",
        "features": [
            
        ]
      },
      trajectoryLayerGeoJson:{
          "type": "FeatureCollection",
          "features": 
            [
              {
                "type": "Feature",
                "geometry": {
                  "type": "MultiLineString",
                  "coordinates": [[]]
                },
                "properties": {}
              }
            ]
      },
      rangeGeoJson:{
          "type": "FeatureCollection",
          "features": []
      },
      properties:{},
      editFeature:null,
      saveEditPopup:null,
      saveInfo:{},
      maskingData:[],
      streetGeoJson:{},
    };
  },
  watch: {
    rowkey: function (e) {
      console.log('123',e)
      this.getClockInList()
    },
    lnglat: function (e) {},
    flyCenter: function (e) {
      this.flyTo(e);
    },
    // trajectoryId:function(e){
    //   if(e){
    //     this.getTrajectoryData();
    //   }
    // },
    trajectoryIdRandom:function(e){
      if(e){
        this.getTrajectoryData();
      }
    },
    // rangePhone:function(e){
    //   if(e){
    //     this.getRangeData(e);
    //   }
    // },
    rangePhoneRandom:function(e){
      if(e){
        this.getRangeData();
      }
    },
    listQuery:{
      handler(newVal,oldVal){
        this.getClockInList();
      },
      deep:true
    },
    listUpdate:function(e){
      this.getClockInList();
    }
  },
  created(){

    // 获取乡镇信息
    this.geoStreetData();

    window.addMapTask = this.addMapTask;
    window.editPosition = this.editPosition;
    window.editClockInData = this.editClockInData;
    window.lookClockInData = this.lookClockInData;
    window.saveEditPositon = this.saveEditPositon;
    window.calcleEditPosition = this.calcleEditPosition;
    
  },
  mounted() {
    let _this = this;
    setTimeout(function(){
      _this.getTrajectoryData();
    },5000);
  },
  destroyed(){
        this.map.remove();
        this.map = null;
    }, 
  methods: {
    getOnlineUserList(){  // 获取在线人员用户数据
      getMethodCommon("/FireManagement/GetPointByUserType?pageIndex=1&pageSize=12&type=2").then(res=>{
        if(res.code == 200){
          let geojson = this.handleOnlineUserGeoJson(res.data);
          console.log("geojson",geojson);
          this.addAndUpdateOnlineUserData(geojson);
        }
      })
    },
    handleOnlineUserGeoJson(data){ // 对在线人员数据进行处理，返回GeoJson数据
      let geojson = {
        "type": "FeatureCollection",
        "features": [],
        "crs": {
          "type": "name",
          "properties": {
            "name": "urn:ogc:def:crs:EPSG::4326"
          }
        }
      }
      data.forEach((item,index)=>{
        let obj = {
          "type": "Feature",
          "geometry": {
            "type": "Point",
            "coordinates": [parseFloat(item.lng), parseFloat(item.lat)]
          },
          "properties": item
        }
        geojson.features.push(obj);
      })
      return geojson
    },
    addAndUpdateOnlineUserData(geojson){ // 添加和更新再按人员位置数据
      if(this.map.getSource("onlineuserSource")){ // 如果已经添加，则更新Resource的Data值
        this.map.getSource("onlineuserSource").setData(geojson);
      }else{ // 加载图标、创建资源、创建图层
        // 加载Source
        this.map.addSource("onlineuserSource",{
          type:"geojson",
          data:geojson
        })

        // 加载Image
        let _this = this;
        this.map.loadImage("/img/gridman/onlineuser-in.png",
          function (error, image) {
            if (error) throw error;
            _this.map.addImage("onlineuserImage", image);
          }
        );
        // 加载Layer
        this.map.addLayer({
          id: "onlineuserLayer",
          type: "symbol",
          source: "onlineuserSource",
          layout: {
            "icon-image": "onlineuserImage", // 图标名称
            "icon-size": 0.6, // 图标大小
            "text-field":"{name}",
            "text-offset":[0,-2.5],
            "text-size":12,
            "visibility":"visible"
          },
          paint:{
            "text-color":"#fff"
          }
        });
      }
    },
    geoStreetData(){ // 获取乡镇数据
      let filter_options = this.currentStreet != '费县' ? "&cql_filter=xzqmc%20like%20%27%25"+this.currentStreet+"%25%27" : ''
      let url = "";
      if(this.currentStreet == '费县'){
        url = "http://175.27.168.120:8080/geoserver/feixian/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=feixian%3Axianjie&maxFeatures=50&outputFormat=application%2Fjson"
      } else{
        url = "http://221.2.83.254:9007/geoserver/ksp/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=ksp%3Ashp_1691822212"+filter_options+"&maxFeatures=50&outputFormat=application%2Fjson"

      }     
      axios({
        method:"get",
        url:url
      }).then(res=>{
        let geojson = res.data;
        this.streetGeoJson = geojson;
        // 创建地图
        this.$nextTick(function () {
          this.initMap(this.getPolygonCenter(geojson));
        });
        this.maskingData = this.getMaskingData(geojson);
      })
    },
    getPolygonCenter(geojson){ // 使用turf计算多边形质心
      var polygon = turf.polygon(geojson.features[0].geometry.coordinates[0]);
      var centerLnglat = turf.centroid(polygon);
      return centerLnglat.geometry.coordinates;
    },
    getMaskingData(geojson){ // 处理geojson边界数据，获取蒙版数据
      return geojson.features[0].geometry.coordinates[0][0];
    },
    editClockInData(){
      this.$emit("editClockInData",this.properties)
      
    },
    lookClockInData(){
      this.$emit("lookClockInData",this.properties)
    },
    editPosition(){
      if (this.popup) {
        this.popup.remove();
      }

      this.map.setLayoutProperty("clockInLayer","visibility","none");
      this.loadEditLayer();

      // let el = document.createElement("img"); //这里可以是任意标签
      // el.className = "marker";
      // el.src = "/img/xiangdao.png"; //图片路径赋值
      // el.style.width = "40px";
      // this.editMarker = new mapboxgl.Marker(el).setLngLat([this.properties.lng, this.properties.lat]).addTo(this.map);

    },
    drawEditMarker(){

    },
    loadEditLayer(){
      let _this = this;
      let isDraw = true;

      var jsonPoint = {
          'type': 'FeatureCollection',
          'features': [
            _this.editFeature
          ]
      };

      // 判断是否创建Source 并添加points layer
        var source = _this.map.getSource('editSource');

        if(source) {
            _this.map.getSource('editSource').setData(jsonPoint);
            _this.map.setLayoutProperty("editLayer","visibility","visible");
        }else{
            _this.map.addSource('editSource', {
                type: 'geojson',
                data: jsonPoint
            });
            _this.map.addLayer({
                id: 'editLayer',
                type: 'symbol',
                source: 'editSource',
                'layout': {
                  'icon-image':'clockInImage',
                  'icon-size': 0.4,
                  'visibility': 'visible'
                },		
            });
        }

        // _this.map.on("click","editLayer",function(e){
        //     _this.map.removeFeatureState({
        //         source: 'editSource',
        //         sourceLayer: 'editLayer',
        //         id: e.features[0].id
        //     });

        // })

        // // 鼠标移入points 图标放大 鼠标样式改为移动样式
        _this.map.on("mouseenter","editLayer",function(e){
          // _this.globalMap.setLayoutProperty('points', 'icon-size', 0.3);
          _this.map.getCanvas().style.cursor = 'move';
        })

        // 鼠标离开points 图标恢复 鼠标样式改为默认样式
        _this.map.on("mouseleave","editLayer",function(e){
          // _this.globalMap.setLayoutProperty('points', 'icon-size', 0.2);
          _this.map.getCanvas().style.cursor = '';
        })

        // 鼠标按下 points图层 
        _this.map.on('mousedown', 'editLayer', (e) => {
          e.preventDefault();
          // 鼠标样式设置为小手样式
          _this.map.getCanvas().style.cursor = 'grab';
          // 鼠标移动 执行图标移动函数
          _this.map.on('mousemove', _this.onMove);
          // 执行一次鼠标抬起函数
          _this.map.once('mouseup', _this.onUp);
        });

        // 点击地图 添加point
        // _this.map.on('click', function (_e) {
        //     if (isDraw) {
        //         _this.map.getCanvas().style.cursor = 'grab'
        //         isDraw=false;
        //         var endCoords=[_e.lngLat.lng, _e.lngLat.lat];
        //         jsonPoint.features.push({
        //             type: 'Feature',
        //             id:"123",
        //             geometry: {
        //                 type: 'Point',
        //                 coordinates: endCoords
        //             }
        //         });
        //         _this.currentLngLat = _e.lngLat.lng+" "+_e.lngLat.lat
        //         _this.map.getSource('editSource').setData(jsonPoint);
        //     }
        // })
    },
    // 图标移动函数
    onMove(e) {
      const coords = e.lngLat;
      this.map.getCanvas().style.cursor = 'grabbing';
      let geojson = {
          'type': 'FeatureCollection',
          'features': [
            {
              'type': 'Feature',
              'geometry': {
                'type': 'Point',
                'coordinates': [0, 0]
              }
            }
          ]
      }
      geojson.features[0].geometry.coordinates = [coords.lng, coords.lat];
      // this.currentLngLat = coords.lng+" "+coords.lat;
      this.map.getSource('editSource').setData(geojson);
    },
    // 鼠标抬起移除监听事件
    onUp(e) {
      let _this = this;
      // 获取坐标信息
      // const coords = e.lngLat;
      // coordinates.style.display = 'block';
      // coordinates.innerHTML = `Longitude: ${coords.lng}<br />Latitude: ${coords.lat}`;
      // 修改鼠标样式
      this.properties.lng = e.lngLat.lng;
      this.properties.lat = e.lngLat.lat;

      if (this.saveEditPopup) {
            if (this.saveEditPopup) {
              this.saveEditPopup.remove();
            }
          }
          this.saveEditPopup = new mapboxgl.Popup({
            closeButton: true,
            closeOnClick: true
          });
          // 设置 popup 的位置和内容
          this.saveEditPopup.setLngLat(e.lngLat).setHTML(`
          <div style="color:#333;padding:3px 12px;cursor:pointer;" type="primary" icon="el-icon-search" onclick='saveEditPositon()'>保存编辑</div>
          <div style="color:#333;padding:3px 12px;cursor:pointer;" type="primary" icon="el-icon-search" onclick='calcleEditPosition()'>取消编辑</div>
          `).setOffset([0,-18]).addTo(_this.map);

      this.map.getCanvas().style.cursor = 'move';
      // 移除鼠标事件
      this.map.off('mousemove', this.onMove);
      this.map.off('touchmove', this.onMove);
    },
    saveEditPositon(){
      // let param = {
      //   "id": this.properties.id,
      //   "lng": this.properties.lng,
      //   "lat": this.properties.lat,
      // }
      getMethodCommon("/FireGrid/GetSingleCheckPoint?id="+this.properties.id).then(res=>{
        if(res.code = 200){
          let param = res.result;
          param.lng = this.properties.lng;
          param.lat = this.properties.lat;
          postMethodCommon("/FireGrid/EditCheckPoint", param).then(response => {
          if (response.code == 200) {
            this.saveEditPopup.remove();
            this.map.setLayoutProperty("editLayer","visibility","none");
            this.getClockInList();
            this.map.setLayoutProperty("clockInLayer","visibility","visible");
              this.$message({
                  type: "success",
                  message: response.message
              })
          }
      })
        }
      })
      
      
    },
    calcleEditPosition(){
      this.saveEditPopup.remove();
      this.map.setLayoutProperty("editLayer","visibility","none");
      this.map.setLayoutProperty("clockInLayer","visibility","visible");
    },
    addMapTask(lng,lat){
      this.$emit("addClockInPoint",{lng:lng,lat:lat});
      console.log("lngLat",lng,lat);
    },  
    flyTo(e) {
      this.map.flyTo({
        center: e, //中心点
        zoom: 18, //缩放比例
        curve: 1,
      });
    },
    getClockInList() {
      getMethodCommon("/FireGrid/GetCheckPoint",this.listQuery).then((res) => {
        this.clockInList = res.data;
        // 处理打卡点GeoJson数据
        if(this.clockInList.length>0){
            this.clockInLayerGeoJson.features = [];
            this.clockInList.forEach((item,index)=>{
                let feature= {
                  "type": "Feature",
                  "geometry": {
                      "type": "Point",
                      "coordinates": [parseFloat(item.lng), parseFloat(item.lat)]
                  },
                  "properties": {
                    id:item.id,
                    lat:item.lat,
                    lng:item.lng,
                    createtime:item.createtime,
                    pointname:item.pointname,
                    userid:item.userid,
                    userinfo:item.userinfo,
                    usernames:item.usernames
                  }
                }
                this.clockInLayerGeoJson.features.push(feature);
            })
            this.loadClockInLayer();
        }
      });
    },
    addPointLayer() {
      let _this = this
      this.clockInList.forEach((item) => {
        console.log("iii", item);
        let el = document.createElement("img"); //这里可以是任意标签
        el.className = "marker";
        el.src = "/img/dakadian.png"; //图片路径赋值
        el.style.width = "40px";
        // el.onclick = function(){
 
        //   console.log('123item',item)
        //   _this.$emit("editClock",item)
        // }
        
        // 添加自定义标记点
        let marker = new mapboxgl.Marker(el).setLngLat([item.lng, item.lat]).addTo(this.map);
        this.markerArr.push(marker)

      });
    },
    initMap(center) {
      let _this = this;
      this.map = new mapboxgl.Map({
        container: this.$refs.datamap,
        style: "mapbox://styles/shichao123/clf3b1bxk007801moo0nnl87k",
        // style:"mapbox://styles/mapbox/streets-v10",
        center: center,
        zoom: 10,
        language: "zh-cmn",
        projection: "globe",
      });
      this.map.on("load", () => {
        this.loadGaoQingLayer();
        this.loadMengban();
        // this.loadZhenJieLayer();
        this.loadZhenJieGeoJsonLayer();

        // this.loadXianJieLayer();

        this.loadAllRangeLayer();
        
        // 获取所有打卡点并加载到图层
        // this.getClockInList();
        // 打卡点图层添加点击事件
        this.map.on("click","clockInLayer",function(e){
          console.log("event1111",e.features);
          let properties = e.features[0].properties;
          let feature = e.features[0];
          _this.properties = properties;
          _this.editFeature = feature;
          if (_this.popup) {
            _this.popup.remove();
          }
          _this.popup = new mapboxgl.Popup({
            closeButton: true,
            closeOnClick: true
          });

          // 设置 popup 的位置和内容
          _this.popup.setLngLat(e.lngLat).setHTML(`
          <div style="color:#333;padding:3px 12px;cursor:pointer;" type="primary" icon="el-icon-search" onclick='lookClockInData()'>查看信息</div>
          <div style="color:#333;padding:3px 12px;cursor:pointer;" type="primary" icon="el-icon-search" onclick='editClockInData()'>编辑信息</div>
          <div style="color:#333;padding:3px 12px;cursor:pointer;" type="primary" icon="el-icon-search" onclick="editPosition()">编辑位置</div>
          `).setOffset([0,-18]).addTo(_this.map);
        })

        // 添加地图右键事件
        this.map.on('contextmenu', function (e) {
          // 阻止默认的右键菜单
          e.preventDefault();

       
          if (_this.popup) {
            _this.popup.remove();
          }
       
          _this.popup = new mapboxgl.Popup({
            closeButton: true,
            closeOnClick: true
          });
          // 设置 popup 的位置和内容
          _this.popup.setLngLat(e.lngLat).setHTML(`<div style="color:#333;padding:3px 12px;cursor:pointer;" type="primary" icon="el-icon-search" onclick="addMapTask(${e.lngLat.lng},${e.lngLat.lat})">在此处添加打卡点</div>`).setOffset([0,-18]).addTo(_this.map);
        });

        // 添加地形数据
        this.map.addSource('mapbox-dem', {
            'type': 'raster-dem',
            'url': 'mapbox://mapbox.mapbox-terrain-dem-v1',
            'tileSize': 512,
            'maxzoom': 14,
        });
        // add the DEM source as a terrain layer with exaggerated height
        this.map.setTerrain({ source: "mapbox-dem", exaggeration: 1.5 });

      });
      this.map.on("click", (e) => {
        this.$emit("getLocation", e);
      });
    },
    
    loadMengban() {
      this.map.addLayer({
        //蒙版图层   //通过边界数据反选 达到挖洞效果
        id: "mb-tag",
        type: "fill",
        source: {
          type: "geojson",
          data: {
            type: "Feature",
            geometry: {
              type: "Polygon",
              coordinates: [
                [
                  // 多边形外围 需要进行遮罩的点 这里是给世界地图加遮罩 所以是世界的四个端点
                  [-180, 90],
                  [180, 90],
                  [180, -90],
                  [-180, -90],
                ],
                this.maskingData,
              ],
            },
          },
        },
        paint: {
          "fill-color": "#272d39",
          // 'fill-opacity': 1 /* 透明度 */,
        },
        layout: {
          visibility: "visible",
        },
      });
    },

    loadGaoQingLayer() {
      this.map.addLayer({
        id: "gaoqingyingxiang",
        type: "raster",
        source: {
          type: "raster",
          tiles: [
            "http://60.213.14.14:8060/geoserver/feixian/wms?service=WMS&version=1.1.0&request=GetMap&layers=feixian:yingxiang&styles=&bbox={bbox-epsg-3857}&width=256&height=256&srs=EPSG:3857&format=image/png&TRANSPARENT=TRUE",
          ],
          tileSize: 256,
        },
        layout: {
          visibility: "visible",
        },
        paint: {},
      });
    },

    loadXianJieLayer() {
      this.map.addLayer({
        id: "xianjie",
        type: "line",
        layout: {
          visibility: "visible",
        },
        source: {
          type: "geojson",
          data: "http://175.27.168.120:8080/geoserver/feixian/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=feixian%3Axianjie&maxFeatures=50&outputFormat=application%2Fjson",
        },
        paint: {
          "line-width": 2,
          "line-color": "orange",
        },
      });
    },

    loadZhenJieLayer() {
      this.map.addSource("shp_1691822212", {
        type: "vector",
        scheme: "tms", //new
        tiles: [
          "http://221.2.83.254:9007/geoserver/gwc/service/tms/1.0.0/ksp:shp_1691822212@EPSG:900913@pbf/{z}/{x}/{y}.pbf",
        ],
      });
      this.map.addLayer({
        id: "zhenjieline",
        type: "line",
        source: "shp_1691822212",
        "source-layer": "shp_1691822212",
        paint: {
          "line-color": "#0000ff",
          "line-width": 2,
        },
      });
      this.map.addLayer({
        id: "zhenjiepoint",
        type: "symbol",
        source: "shp_1691822212",
        "source-layer": "shp_1691822212",
        layout: {
          "text-field": "{xzqmc}",
          "text-size": 18,
        },
        paint: {
          "text-color": "#000000", // 文本的颜色（可选，默认值为 #000000）
          "text-halo-color": "#FFFFFF",
          "text-halo-width": 1,
        },
      });
    },
    loadZhenJieGeoJsonLayer(geojson){
       // 加载Source
       this.map.addSource("zhenjieSource",{
          type:"geojson",
          data:this.streetGeoJson
        })
        // 加载镇界图层
        this.map.addLayer({
          id: "zhenjieLayer",
          type: "line",
          source: "zhenjieSource",
          layout: {},
          paint: {
            "line-width": 2,
            "line-color": "orange",
          },
        });
    },
    loadClockInLayer(){
      // 判断是否已经添加过Source 如果有更新Source
      if(this.map.getSource("clockInSource")){
        this.map.getSource("clockInSource").setData(this.clockInLayerGeoJson);
      }else{
        // 加载Source
        this.map.addSource("clockInSource",{
          type:"geojson",
          data:this.clockInLayerGeoJson
        })

        // 加载Image
        let _this = this;

        this.map.loadImage("/img/dakadian.png",
          function (error, image) {
            if (error) throw error;
            _this.map.addImage("clockInImage", image);
          }
        );
        // 加载Layer
        this.map.addLayer({
          id: "clockInLayer",
          type: "symbol",
          source: "clockInSource",
          layout: {
            "icon-image": "clockInImage", // 图标名称
            "icon-size": 0.4, // 图标大小
            "text-field":"{pointname}",
            "text-offset":[0,-2.5],
            "text-size":12,
            "visibility":"visible"
          },
          paint:{
            "text-color":"#fff"
          }
        });
      }
    },

    getTrajectoryData(){
      let query = {
         userId:this.trajectory.createId,
         beginTime:this.trajectory.startTime,
         endTime:this.trajectory.endTime
      }
      getMethodCommon("/Patrol/LoadPatrolPointByTime",query).then(res=>{
        if(res.code == 200){
          let data = res.data;
          this.flyTo([parseFloat(res.data[0].lng),parseFloat(res.data[0].lat)]);
          this.trajectoryLayerGeoJson = this.handleRouterData(data)
          console.log("this.trajectoryLayerGeoJson",this.trajectoryLayerGeoJson);
          this.loadTrajectoryLayer(this.trajectoryLayerGeoJson);
        }
      })
    },
    handleRouterData(data){  // 处理路线数据
      let geojson = {
        "type": "FeatureCollection",
        "features": [],
        "crs": {
          "type": "name",
          "properties": {
        
          }
        }
      };
      let der = 0;

      let feature = {
        "type": "Feature",
        "geometry": {
          "type": "MultiLineString",
          "coordinates": [[]]
        },
        "properties": {
          
        }
      }

      data.forEach((item,index)=>{
        if(index == 0){
          der = item.intype;
          feature = {
            "type": "Feature",
            "geometry": {
              "type": "MultiLineString",
              "coordinates": [[]]
            },
            "properties": {
              "intype":item.intype
            }
          }
        }

        if(der == item.intype){
          feature.geometry.coordinates[0].push([parseFloat(item.lng),parseFloat(item.lat)]);
        }else{
          geojson.features.push(feature);
          feature = {
            "type": "Feature",
            "geometry": {
              "type": "MultiLineString",
              "coordinates": [[
                [parseFloat(data[index-1].lng),parseFloat(data[index-1].lat)]
              ]]
            },
            "properties": {
              "intype":item.intype
            }
          }
          der = item.intype;
        }

        if(geojson.features.length == 0 && feature.geometry.coordinates[0].length>0){
          geojson.features.push(feature);
        }
        
      })

      return geojson

    }, 
    getRangeData(e){
      getMethodCommon("/FireGrid/GetUserRange?phone="+this.rangePhone).then(res=>{
        if(res.code == 200){
          if(res.data.length>0){
            this.rangeGeoJson.features = [];
            res.data.forEach((item,index)=>{
              let rangeGeoJson = parse(item.geom);
              let feature = {
                "type": "Feature",
                "geometry": rangeGeoJson,
                "properties": {
                  id:item.id
                }
              }
              this.rangeGeoJson.features.push(feature);
            })
            this.loadRangeLayer();
          }
        }
      })
    },
    loadRangeLayer(){
      if(this.map.getSource("rangeSource")){
        this.map.getSource("rangeSource").setData(this.rangeGeoJson);
      }else{
        this.map.addSource("rangeSource",{
          type:"geojson",
          data:this.rangeGeoJson
        })

        this.map.addLayer({
          id: "rangeLayer",
          type: "line",
          source: "rangeSource",
          layout: {},
          paint: {
            "line-color": "#ff0000",
            "line-width": 2,
          },
        })
        console.log("rangeLayer",this.map.getLayer("rangeLayer"));
      }
    },
    loadStartAndEndPoint(){
        if(this.startMarker && this.endMarker){
          this.startMarker.remove();
          this.endMarker.remove();
          this.startMarker = null;
          this.endMarker = null;
        }

        let el = document.createElement("img"); //这里可以是任意标签
        el.className = "marker";
        el.src = "/img/route-start.png"; //图片路径赋值
        el.style.width = "40px";
        this.startMarker = new mapboxgl.Marker(el).setLngLat(this.startPoint).addTo(this.map);

        let el2 = document.createElement("img"); //这里可以是任意标签
        el2.className = "marker";
        el2.src = "/img/route-end.png"; //图片路径赋值
        el2.style.width = "40px";
        this.endMarker = new mapboxgl.Marker(el2).setLngLat(this.endPoint).addTo(this.map);
    },
    loadTrajectoryLayer(){
      // 判断是否已经存在
      if(this.map.getSource("trajectorySource")){
        // 如果存在更新数据
        this.map.getSource("trajectorySource").setData(this.trajectoryLayerGeoJson);
      }else{
        // 如果不存在添加Source
        this.map.addSource("trajectorySource",{
          type:"geojson",
          data:this.trajectoryLayerGeoJson
        })
        // 加载Layer
        this.map.addLayer({
          id: "trajectoryLayer",
          type: "line",
          layout: {
            visibility: "visible",
          },
          source:"trajectorySource",
          paint: {
            "line-width": 2,
            // "line-color": "orange",
            'line-color':[
                "case",
                ["==",["get","intype"],0],
                "#ff0000",
                ["==",["get","intype"],1],
                "#00ff00",
                // 默认
                "#67C23A",
              ],
          },
        })
      }
    },
    loadAllRangeLayer(){  // 获取所有管护范围
      let filter_options = this.currentStreet != '费县' ? "&cql_filter=xzq%20like%20%27%25"+this.currentStreet+"%25%27" : ''
      let url = "";
      if(this.currentStreet != '费县'){
        url = "http://221.2.83.254:9007/geoserver/ksp/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=ksp%3Ahulinyuanguanhufanwei"+filter_options+"&maxFeatures=5000&outputFormat=application%2Fjson";

      }else{
        url = "http://221.2.83.254:9007/geoserver/ksp/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=ksp%3Ahulinyuanguanhufanwei&maxFeatures=50000&outputFormat=application%2Fjson";
      }
      axios({
        method:"get",
        url:url
      }).then(res=>{
        let geojson = res.data;

        if(this.map.getSource("allRangeSource")){
          
        }else{
          this.map.addSource("allRangeSource",{
            type:"geojson",
            data:geojson
            // type: "vector",
            // scheme: "tms", //new
            // tiles: ["http://221.2.83.254:9007"+"/geoserver/gwc/service/tms/1.0.0/ksp%3A" +"hulinyuanguanhufanwei" +"@EPSG:900913@pbf/{z}/{x}/{y}.pbf"],
          })

          this.map.addLayer({
              id: "allRangeLayerFill",
              type: "fill",
              source: "allRangeSource",
              // "source-layer": "hulinyuanguanhufanwei",
              layout: {

              },
              paint: {
                "fill-color": "#7CD00F",
                "fill-opacity": 0.3,
              },
          })

          this.map.addLayer({
              id: "allRangeLayerLine",
              type: "line",
              source: "allRangeSource",
              // "source-layer": "hulinyuanguanhufanwei",
              layout: {

              },
              paint: {
                "line-color": "#F4CC39",
                "line-width": 1,
              },
          })

          this.map.addLayer({
              id: "allRangeLayerName",
              type: "symbol",
              source: "allRangeSource",
              // "source-layer": "hulinyuanguanhufanwei",
              layout: {
                "text-field": "{hulinyuan}",
                "text-size": 12,
              },
              paint: {
                "text-color": "#000000", // 文本的颜色（可选，默认值为 #000000）
                "text-halo-color": "#FFFFFF",
                "text-halo-width": 1,
              },
          })
        }
      })
    }
  },
};
</script>



<style scoped>
.data-map {
  width: 100%;
  height: 100%;
}
.data-map .map {
  width: 100%;
  height: 100%;
}
::v-deep.data-map .mapboxgl-ctrl-bottom-left {
  display: none !important;
}
::v-deep.data-map .mapboxgl-ctrl-bottom-right {
  display: none !important;
}
</style>
