<template>
  <div :id="mapContainerName" class="map-container">

    <div class="map-type-switch-container">
      <div class="switch-button" v-if="mapAngle == '3D'"  @click="handlerChangeMapAngle()">
          <TableOutlined  style="font-size:20px;position:relative;top:1px;left:-6px;" />
          <span>&nbsp;二维地图</span>
      </div>
      
      <div class="switch-button" v-else  @click="handlerChangeMapAngle()">
          <GlobalOutlined   style="font-size:20px;position:relative;top:1px;left:-6px;"/>
          <span>&nbsp;三维地图</span>
      </div> 

      <div class="home-button" @click="handlerInitialize">
         
      </div>
  </div>
  </div>
</template>
<script lang="ts" setup>
import MonitoringData from './MonitoringData.json';

import { TableOutlined, GlobalOutlined,HomeOutlined} from '@ant-design/icons-vue';
  import { ref, onMounted, defineExpose, defineEmits } from 'vue';
  import { generateUUID } from '@/components/MapboxMaps/src/tool';
  import { WktToGeojson } from '@/components/MapboxMaps/src/WktGeojsonTransform';
  import mapboxgl, { Map, Popup } from 'mapbox-gl';
  import { MAPBOX_TOKEN, TINADITU_TOKEN, MAP_VIEWER } from './config.ts';
  import heatGeoJson from './data.json';
  import { getPolygonCenter,getIntersectTif } from '@/api/tiankongdi';
  import { message, Modal } from 'ant-design-vue';
  import axios from 'axios';
  import { getAppEnvConfig } from '@/utils/env';
  const { VITE_GLOB_API_URL } = getAppEnvConfig();
  const VITE_GLOB_API_URL_VAR = ref<String>(VITE_GLOB_API_URL);
  import YingXiangAddress from './index.json'
  import {serverAddress} from '/public/yingxiangConfig/index.json'
  const {VITE_GLOB_YINGXIANG_SERVER,VITE_GLOB_YAOGANYINGXIANG_SERVER} = getAppEnvConfig();
  const mapContainerName = ref<String>();
  mapContainerName.value = 'mapContainer-' + generateUUID();
  //
  import U from 'mapbox-gl-utils';
  import {MP} from "./src/MP";
  import {  GeojsonToWkt } from './src/WktGeojsonTransform';

  const emits = defineEmits(['onload', 'handlerGetDetails', 'showMonitor',"handlerQueryIntersectTif"]);

  let map: Map;
  let mp: any = null;

  // init map
  const initMap = () => {
    return new mapboxgl.Map({
      container: mapContainerName.value,
      language: 'zh-cmn',
      projection: 'globe', // wgs84参考系
      style: {
        glyphs: 'mapbox://fonts/mapbox/{fontstack}/{range}.pbf',
        version: 8,
        sources: {
          dianzi: {
            type: 'raster',
            tiles: [
              `https://t0.tianditu.gov.cn/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=${TINADITU_TOKEN}`,
            ],
            tileSize: 256,
          },
          'dianzi-biaozhu': {
            type: 'raster',
            tiles: [
              `https://t0.tianditu.gov.cn/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=${TINADITU_TOKEN}`,
            ],
            tileSize: 256,
          },
          weixing: {
            type: 'raster',
            tiles: [
              `http://t0.tianditu.gov.cn/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=${TINADITU_TOKEN}`,
            ],
            tileSize: 256,
            minzoom:0,
            maxzoom:15,
          },
          yaogan: {
            type: 'raster',
            tiles: [
              VITE_GLOB_YAOGANYINGXIANG_SERVER,
            ],
            tileSize: 256,
            minzoom:9,
            maxzoom:15,
          },
          yingxiang: {
            type: 'raster',
            tiles: [
              VITE_GLOB_YINGXIANG_SERVER,
            ],
            tileSize: 256,
            minzoom:13,
            maxzoom:24,
          }
        },
        layers: [
          {
            id: 'dianzi-biaozhu',
            type: 'raster',
            source: 'dianzi-biaozhu',
            layout: {
              visibility: 'visible',
            },
          },
          {
            id: 'weixing',
            type: 'raster',
            source: 'weixing',
            layout: {
              visibility: 'visible',
            },
            maxzoom:15,
            minzoom:0
          },
          {
            id: 'yaogan',
            type: 'raster',
            source: 'yaogan',
            layout: {
              visibility: 'visible',
            },
            minzoom:9,
            maxzoom:15
          },
          {
            id: 'yingxiang',
            type: 'raster',
            source: 'yingxiang',
            layout: {
              visibility: 'visible',
            },
            minzoom:13,
            maxzoom:24
          },
          {
            id: 'dianzi',
            type: 'raster',
            source: 'dianzi',
            layout: {
              visibility: 'visible',
            },
          },
        ],
      },
      minZoom: 8,
      zoom: 8,
      maxZoom: 22,
      pitch: 0,
      center: [118.35731795360051,35.31214553447394],
    });
  };

  // 获取图斑面数据
  const polygonVisibility = ref<String>('none');

  function handlerLoadPolygon(code = '', filter = '', type = '') {
    let sql_filter;
    if (code) {
      sql_filter = '&filter="countyid"=\'' + code + "'";
    } else {
      sql_filter = '';
    }
    let map_filter;

    switch (filter) {
      case '合法':
        map_filter = [
          'all',
          ['==', ['get', 'is_illegal'], 0],
          ['==', ['get', 'handle_status_id'], 5],
        ];
        break;
      case '违法':
        map_filter = [
          'any',
          ['==', ['get', 'is_illegal'], 1],
          ['!=', ['get', 'handle_status_id'], 5],
        ];
        break;
      case '其他':
        map_filter = [
          'all',
          ['==', ['get', 'is_illegal'], 2],
          ['==', ['get', 'handle_status_id'], 5],
        ];
        break;
      case '补办手续':
        map_filter = [
          'all',
          ['==', ['get', 'measure_name'], 0],
          ['==', ['get', 'handle_status_id'], 5],
        ];
        break;
      case '拆除复耕':
        map_filter = [
          'all',
          ['==', ['get', 'measure_name'], 1],
          ['==', ['get', 'handle_status_id'], 5],
        ];
        break;
      default:
        map_filter = ['!=', ['get', 'gid'], 0];
    }
    let type_filter;
    switch (type) {
      case '农用地':
        type_filter = ['==', ['get', 'typename'], '农用地'];
        break;
      case '建设用地':
        type_filter = ['==', ['get', 'typename'], '建设用地'];
        break;
      case '推堆土':
        type_filter = ['==', ['get', 'typename'], '推堆土'];
        break;
    }
    if (filter && type) {
      map_filter.push(type_filter);
    } else if (!filter && type) {
      map_filter = ['all', ['!=', ['get', 'gid'], 0], type_filter];
    }

    // alert(map_filter);
    // console.log("map_filter123",map_filter);

    if (map.getSource('historyLayerLine')) {
      polygonVisibility.value = map.getLayoutProperty('historyLayerLine', 'visibility');
      map.removeLayer('historyLayerLine');
      map.removeLayer('historyLayerFill');
      map.removeSource('historyLayerLine');
      map.removeSource('historyLayerFill');
    }
    map.addLayer({
      id: 'historyLayerLine',
      type: 'line',
      source: {
        type: 'vector',
        tiles: [
          VITE_GLOB_API_URL_VAR.value +
            '/api/DroneCaseInfoSingle/QueryVectorTileByTable?z={z}&x={x}&y={y}&table=view_drone_shp_data&' +
            sql_filter +
            '&field="gid","handle_status_id","is_illegal","measure_name","typename","Id",',
        ],
        minzoom: 1,
        maxzoom: 20,
      },
      'source-layer': 'view_drone_shp_data',
      layout: {
        'line-join': 'round',
        'line-cap': 'round',
        visibility: polygonVisibility.value,
      },
      filter: map_filter,
      paint: {
        'line-color': [
          'case',
          ['all', ['==', ['get', 'is_illegal'], 0], ['==', ['get', 'handle_status_id'], 5]], //合法
          '#0AF703',
          ['any', ['==', ['get', 'is_illegal'], 1], ['!=', ['get', 'handle_status_id'], 5]], //违法
          '#F70303',
          ['all', ['==', ['get', 'is_illegal'], 2], ['==', ['get', 'handle_status_id'], 5]], //其他
          '#0382F7',
          ['all', ['==', ['get', 'measure_name'], 0], ['==', ['get', 'handle_status_id'], 5]], //补办手续
          '#AD04F4',
          ['all', ['==', ['get', 'measure_name'], 1], ['==', ['get', 'handle_status_id'], 5]], //拆除复耕
          '#F4E004',
          // 默认
          '#F70303',
        ],
        'line-width': 5,
      },
    });

    map.addLayer({
      id: 'historyLayerFill',
      type: 'fill',
      source: {
        type: 'vector',
        tiles: [
          VITE_GLOB_API_URL_VAR.value +
            '/api/DroneCaseInfoSingle/QueryVectorTileByTable?z={z}&x={x}&y={y}&table=view_drone_shp_data' +
            sql_filter +
            '&field="gid","handle_status_id","is_illegal","measure_name","typename","Id",',
        ],
        //
        minzoom: 1,
        maxzoom: 20,
      },
      'source-layer': 'view_drone_shp_data',
      filter: map_filter,
      layout: {
        visibility: polygonVisibility.value,
      },
      paint: {
        'fill-color': [
          'case',
          ['all', ['==', ['get', 'is_illegal'], 0], ['==', ['get', 'handle_status_id'], 5]], //合法
          '#0AF703',
          ['any', ['==', ['get', 'is_illegal'], 1], ['!=', ['get', 'handle_status_id'], 5]], //违法
          '#F70303',
          ['all', ['==', ['get', 'is_illegal'], 2], ['==', ['get', 'handle_status_id'], 5]], //其他
          '#0382F7',
          ['all', ['==', ['get', 'measure_name'], 0], ['==', ['get', 'handle_status_id'], 5]], //补办手续
          '#AD04F4',
          ['all', ['==', ['get', 'measure_name'], 1], ['==', ['get', 'handle_status_id'], 5]], //拆除复耕
          '#F4E004',
          // 默认
          '#F70303',
        ],
        'fill-opacity': 0.4,
      },
    });

    map.on('click', 'historyLayerFill', (e) => {
      emits('handlerGetDetails', e.features[0].properties);
    });
  }

  // 获取和处理图斑点数据
  const currentCode = ref('');
  async function handlerDealPoint(code = '') {
    let sql_filter;
    if (code) {
      sql_filter = '"countyid"=\'' + code + "'";
    } else {
      sql_filter = '';
    }
    let points = await getPolygonCenter({ tablename: 'view_drone_shp_data', filter: sql_filter });

    let heatdata = {
      type: 'FeatureCollection',
      features: [],
    };
    points?.forEach((item, index) => {
      let geometry = WktToGeojson(item['centroid_point']);
      let feature = {
        geometry: geometry,
        properties: {
          mag: parseFloat((5 * Math.random()).toFixed(1)),
        },
      };
      heatdata.features.push(feature);
    });

    handlerLoadHeatLayer(heatdata);

    if (map.getLayer('clusters')) {
      map.moveLayer('clusters', 'heatLayer');
      map.moveLayer('cluster-count', 'heatLayer');
      map.moveLayer('unclustered-point', 'heatLayer');
    }
  }

  // 获取遮罩数据
  function getMaskData(){
      axios({
          method:"get",
          url:`http://120.222.154.7:8090/geoserver/linyishi/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=linyishi%3Ashijie&maxFeatures=50&outputFormat=application%2Fjson`,
      }).then(res=>{
          let geojson = {DATA:res.data.features[0].geometry.coordinates[0][0]}
          handlerLoadMaskLayer(geojson);
      });

  }

  // 加载地图遮罩
  function handlerLoadMaskLayer(geojson) {
    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],
              ],
              geojson.DATA,
            ],
          },
        },
      },
      paint: {
        'fill-color': '#ffffff',
        'fill-opacity': 1 /* 透明度 */,
      },
      layout: {
        visibility: 'visible',
      },
    });
  }

  // 加载热力图图斑数据
  function handlerLoadHeatLayer(heatdata) {
    console.log('heatdata123', heatdata);
    if (map.getSource('heatSource')) {
      map.getSource('heatSource').setData(heatdata);
    } else {
      map.addSource('heatSource', {
        type: 'geojson',
        data: heatdata,
      });
      map.addLayer({
        id: 'heatLayer',
        type: 'heatmap',
        source: 'heatSource',
        maxzoom: 13,
        minzoom: 7,
        layout: {
          visibility: 'visible',
        },
        // 'paint': {
        //     'heatmap-weight': [
        //         'interpolate',
        //         ['linear'],
        //         ['get', 'mag'],
        //         1,
        //         2,
        //         3,
        //         4
        //     ],
        //     'heatmap-intensity': [
        //         'interpolate',
        //         ['linear'],
        //         ['zoom'],
        //         0,
        //         1,
        //         9,
        //         3
        //     ],
        //     'heatmap-color': [
        //         'interpolate',
        //         ['linear'],
        //         ['heatmap-density'],
        //         0,
        //         'rgba(33,102,172,0)',
        //         0.2,
        //         'rgba(103,169,207,0.8)',
        //         0.4,
        //         'rgba(209,229,240,0.8)',
        //         0.6,
        //         'rgba(253,219,199,0.8)',
        //         0.8,
        //         'rgba(239,138,98,0.8)',
        //         1,
        //         'rgba(178,24,43,0.8)'
        //     ],
        //     'heatmap-radius': [
        //         'interpolate',['linear'],['zoom'],
        //         2,
        //         7,
        //         11,
        //         20
        //     ],
        //     'heatmap-opacity': [
        //         'interpolate',
        //         ['linear'],
        //         ['zoom'],
        //         7,
        //         0,
        //         8,
        //         1
        //     ]
        // }
        paint: {
          'heatmap-weight': 1,
          'heatmap-intensity': 1,
          'heatmap-color': [
            'interpolate',
            ['linear'],
            ['heatmap-density'],
            0,
            'rgba(33,102,172,0)',
            0.2,
            'rgba(51, 71, 255 ,0.7)',
            0.4,
            'rgba(51, 255, 81 ,0.7)',
            0.6,
            'rgba(253,219,199,0.8)',
            0.8,
            'rgba(255, 90, 51,0.8)',
            0.9,
            'rgba(214,34,8,0.9)',
            1,
            'rgba(178,24,43,1)',
          ],
          'heatmap-radius': 10,
          'heatmap-opacity': 0.9,
        },
      });
    }

    handlerLoadConvergeLayer(heatdata);

    if (map.getLayer('heatLayer')) {
      map.moveLayer('heatLayer', 'historyLayerLine');
      map.moveLayer('heatLayer', 'historyLayerFill');
      if (map.getLayer('clusters')) {
        map.moveLayer('clusters', 'heatLayer');
        map.moveLayer('cluster-count', 'heatLayer');
        map.moveLayer('unclustered-point', 'heatLayer');
      }
    }
  }

  // 地图定位
  function handlerLocation(lngLat, zoom) {
    map.flyTo({
      center: lngLat,
      zoom: zoom,
      bearing: 0,
      speed: 1, // 飞行速度
      curve: 2, // 飞行曲线
      essential: true,
      easing(t) {
        // 飞行动画函数
        return t;
      },
    });
  }

  // 获取县区边界数据
  const handlerDealCountry = (countyName: String = '临沂市'): void => {
    let center = {};
    let zoom;
    let filterName = '';
    if (countyName == '临沂市') {
      center = { lng: 118.72504868812163, lat: 35.180072027132915 };
      zoom = 7.848587811931849;
      handlerLocation([center['lng'], center['lat']], zoom);
    } else if (countyName) {
      center = MAP_VIEWER[countyName].center;
      zoom = MAP_VIEWER[countyName].zoom;
      handlerLocation([center['lng'], center['lat']], zoom);
      filterName = countyName;
    }

    axios({
      method: 'get',
      url: `http://175.27.168.120:8080/geoserver/linyishi/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=linyishi%3Axianjie&maxFeatures=50&outputFormat=application%2Fjson&cql_filter=xzqmc%20like%20%27%25${filterName}%25%27`,
    }).then((res) => {
      handlerLoadCountyLayer(res.data);
    });
  };

  // 渲染边界数据
  const handlerLoadCountyLayer = (geojson) => {
    // 绘制线
    if (map.getSource('countySource')) {
      map.getSource('countySource').setData(geojson);
    } else {
      map.addSource('countySource', {
        type: 'geojson',
        data: geojson,
      });
      map.addLayer({
        id: 'countyLayer',
        type: 'line',
        source: 'countySource',
        paint: {
          'line-color': '#6F7FF4', // 设置线的颜色
          'line-width': 3, // 设置线的宽度
        },
      });
      map.moveLayer('heatLayer', 'countLayer');
      // map.moveLayer("historyLayerLine","countLayer");
      // map.moveLayer("historyLayerFill","countLayer");
    }
  };

  // 控制图层显示隐层
  /**
   * 热力图：heatLayer
   *
   * 图斑线：historyLayerLine
   *
   * 图斑面：historyLayerFill
   *
   * 行政区划：countyLayer
   *
   * */
  function handlerChangeLayerVisible(layers, checked) {
    layers?.forEach((item,index)=>{
      if (map.getLayer(item)) {
        if (checked) {
          map.setLayoutProperty(item, 'visibility', 'visible');
        } else {
          map.setLayoutProperty(item, 'visibility', 'none');
        }
      }
    })
  }

  // 切换县区
  function handlerChangeCounty(county, type = '') {
    handlerDealCountry(county.name);
    handlerLoadPolygon(county.code, type);
    handlerDealPoint(county.code);
  }

  // 加载汇聚图
  function handlerLoadConvergeLayer(geojson) {
    if (map.getSource('earthquakes')) {
      map.getSource('earthquakes').setData(geojson);
    } else {
      map.addSource('earthquakes', {
        type: 'geojson',
        // Point to GeoJSON data. This example visualizes all M1.0+ earthquakes
        // from 12/22/15 to 1/21/16 as logged by USGS' Earthquake hazards program.
        data: geojson,
        cluster: true,
        clusterMaxZoom: 14, // Max zoom to cluster points on
        clusterRadius: 50, // Radius of each cluster when clustering points (defaults to 50)
      });

      map.addLayer({
        id: 'clusters',
        type: 'circle',
        source: 'earthquakes',
        filter: ['has', 'point_count'],
        layout: {
          visibility: 'none',
        },
        paint: {
          // Use step expressions (https://docs.mapbox.com/style-spec/reference/expressions/#step)
          // with three steps to implement three types of circles:
          //   * Blue, 20px circles when point count is less than 100
          //   * Yellow, 30px circles when point count is between 100 and 750
          //   * Pink, 40px circles when point count is greater than or equal to 750
          'circle-color': [
            'step',
            ['get', 'point_count'],
            // '#51bbd6',
            // 100,
            // '#f1f075',
            // 750,
            // '#f28cb1'

            'rgba(51, 71, 255 ,0.6)',
            50,
            'rgba(51, 255, 81 ,0.6)',
            200,
            'rgba(253,219,199,0.9)',
            300,
            'rgba(255, 90, 51,1)',
            400,
            'rgba(214,34,8,0.9)',
            700,
            'rgba(178,24,43,1)',
          ],
          'circle-radius': ['step', ['get', 'point_count'], 20, 100, 30, 750, 40],
        },
      });

      map.addLayer({
        id: 'cluster-count',
        type: 'symbol',
        source: 'earthquakes',
        filter: ['has', 'point_count'],
        layout: {
          visibility: 'none',
          'text-field': ['get', 'point_count_abbreviated'],
          'text-font': ['DIN Offc Pro Medium', 'Arial Unicode MS Bold'],
          'text-size': 12,
        },
      });

      map.addLayer({
        id: 'unclustered-point',
        type: 'circle',
        source: 'earthquakes',
        filter: ['!', ['has', 'point_count']],
        layout: {
          visibility: 'none',
        },
        paint: {
          'circle-color': '#11b4da',
          'circle-radius': 4,
          'circle-stroke-width': 1,
          'circle-stroke-color': '#fff',
        },
      });

      if (map.getLayer('clusters')) {
        map.moveLayer('clusters', 'heatLayer');
        map.moveLayer('cluster-count', 'heatLayer');
        map.moveLayer('unclustered-point', 'heatLayer');
      }
    }
  }

  //
  onMounted(() => {
    mapboxgl.accessToken = MAPBOX_TOKEN;
    map = initMap();
    map.on('load', () => {
      
      //挂载mapbox-gl-utils
      U.init(map);
      mp = new MP(map);


      // handlerDealCountry();
      // handlerDealPoint();
      // handlerLoadPolygon();
      // handlerLoadMaskLayer();
      getMaskData();
      loadMonitorLayer();
      loadFuFeiLayer();
      getHangFeiPlanData();
      getHangFeiAreaData();
      emits('onload');
      map.on('click', (e) => {
        var center = map.getCenter(); // 获取当前视图中心点
        var zoom = map.getZoom(); // 获取当前视图缩放级别
        console.log(zoom);
        console.log(center);
      });

      // 添加地形数据
      map.addSource('mapbox-dem', {
        'type': 'raster-dem',
        'tiles':[VITE_GLOB_API_URL_VAR.value+'/mapbox_terrain/{z}/{x}/{y}.png'],
        'tileSize': 256,
        'maxzoom': 13,
        'minzoom':10,
      });
      map.setTerrain({ source: "mapbox-dem", exaggeration: 1 });

      // 设置2D地图
      map.easeTo({ pitch: 0, bearing: 0, duration: 1000 });
        map.dragRotate.disable(); // 禁用拖动旋转
        map.pitchWithRotate = false; // 禁用旋转时俯仰变化
        mapAngle.value = "2D";

    });
  });
  // 视频监控
  function loadMonitorLayer() {
    axios({
      method: 'get',
      // url: 'http://123.132.248.154:9302/api/DeviceInfo/GetDeviceInfo',
      url:"http://221.2.83.254:9007/geoserver/ksp/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=ksp%3Amonitornest2&maxFeatures=1000000&outputFormat=application%2Fjson&cql_filter=is_del%20=0",
      params: {
        rtuid: '382569943420997,374488578232389',
        pageSize: 200,
        pageIndex: 1,
        type: 0,
      },
    }).then((res) => {
      // console.log("res333",res.data.features);

      let data = [{
        "type": "Feature",
        "id": "monitornest2.1",
        "geometry": {
            "type": "Point",
            "coordinates": [
              118.429056,
              35.387537
            ]
        },
        "geometry_name": "geom",
        "properties": {
            "id": 1,
            "cameraindexcode": "41a59135f4284841aa4addf3dd83a05e",
            "cameraname": "沂南县砖埠镇东岳庄村北可见光",
            "cameratype": "0",
            "camerat_01": "xres.query.camera.type.qj",
            "channelno": "1",
            "updatetime": "45255.7759867824",
            "transtype": "1",
            "transtypen": "TCP",
            "creater_id": "1",
            "is_del": 0
        }
    }]
      // addMonitorLayer(res.data.features);
      addMonitorLayer(data);
      // if (res.data.code == 200) {
        // addMonitorLayer(res.data.result);
      //   console.log("jiankong",res.data.result)
      // }
    });
  }
  // 视频监控
  function addMonitorLayer(data) {
    let geojson = {
      type: 'FeatureCollection',
      features: [],
    };
    data.forEach((item, index) => {
      // console.log("data123",item);
      let obj = {
        type: 'Feature',
        geometry: {
          type: 'Point',
          // coordinates: item.lnglat.split(','),
          coordinates:item.geometry.coordinates
        },
        properties: {
          name: item.properties.cameraname,
          deviceId: item.properties.cameraindexcode,
          rtuId: item.properties.cameraname,
        },
      };
      geojson.features.push(obj);
    });

    // 加载监控图标
    map.loadImage('/monitor/monitor.png', function (error, image) {
      if (error) throw error;
      if (!map.hasImage('monitorIcon')) {
        map.addImage('monitorIcon', image);
      }
    });


    // 加载监控数据源
    map.addSource('JianKongSource', {
      type: 'geojson',
      data: MonitoringData,
    });

    // 加载监控图层
    map.addLayer({
      id: 'JianKong',
      type: 'symbol',
      source: 'JianKongSource',
      layout: {
        'icon-image': 'monitorIcon',
        'icon-size': 0.8,
        'text-field': ['get', 'name'],
        'text-size': 12,
        'text-font': ['Open Sans Semibold', 'Arial Unicode MS Bold'],
        'text-offset': [0, 1.6],
        'text-anchor': 'top',
        'text-allow-overlap': false,
        visibility: 'none',
      },
      paint: {
        'text-color': '#041B36',
        'text-halo-color': '#fff',
        'text-halo-width': 2,
      },
    });

    map.on('click', 'JianKong', (e) => {
      // 显示弹窗
      emits('showMonitor', e.features[0].properties);
    });
  }

  // 无人机图层
  function handlerUpdateUavLayer(uavLayerGeoJson) {
    if (map.getSource('uavSource')) {
      map.getSource('uavSource').setData(uavLayerGeoJson);
    } else {
      map.loadImage('/videosupervision/uav.png', function (error, image) {
        if (error) throw error;
        if (!map.hasImage('uavIcon')) {
          map.addImage('uavIcon', image);
        }
      });

      map.addSource('uavSource', {
        type: 'geojson',
        data: uavLayerGeoJson,
      });

      map.addLayer({
        id: 'uavlayer',
        type: 'symbol',
        source: 'uavSource',
        layout: {
          'icon-image': 'uavIcon',
          'icon-size': 0.8,
          'text-field': ['get', 'account'],
          'text-size': 14,
          'text-font': ['Open Sans Semibold', 'Arial Unicode MS Bold'],
          'text-offset': [0, 1.8],
          'text-anchor': 'top',
          'text-allow-overlap': false,
          visibility: 'visible',
        },
        paint: {
          'text-color': '#fff',
          'text-halo-color': '#000',
          'text-halo-width': 1,
        },
      });
    }
  }

  // 复飞核实图斑
  function loadFuFeiLayer(){
    let sql_filter = '&filter="measure_name"=\'0\'';

    if (map.getSource('fufeiSource')) {
      map.removeLayer('fufeiLayerLine');
      map.removeSource('fufeiLayerFill');
    }
    map.addLayer({
      id: 'fufeiLayerLine',
      type: 'line',
      source: {
        type: 'vector',
        tiles: [
          VITE_GLOB_API_URL_VAR.value +
            '/api/DroneCaseInfoSingle/QueryVectorTileByTable?z={z}&x={x}&y={y}&table=view_drone_shp_data&' +
            sql_filter +
            '&field="gid","handle_status_id","is_illegal","measure_name","typename","Id",',
        ],
        minzoom: 1,
        maxzoom: 20,
      },
      'source-layer': 'view_drone_shp_data',
      layout: {
        'line-join': 'round',
        'line-cap': 'round',
        "visibility": "visible",
      },
      paint: {
        'line-color': [
          'case',
          ['all', ['==', ['get', 'is_illegal'], 0], ['==', ['get', 'handle_status_id'], 5]], //合法
          '#0AF703',
          ['any', ['==', ['get', 'is_illegal'], 1], ['!=', ['get', 'handle_status_id'], 5]], //违法
          '#F70303',
          ['all', ['==', ['get', 'is_illegal'], 2], ['==', ['get', 'handle_status_id'], 5]], //其他
          '#0382F7',
          ['all', ['==', ['get', 'measure_name'], 0], ['==', ['get', 'handle_status_id'], 5]], //补办手续
          '#AD04F4',
          ['all', ['==', ['get', 'measure_name'], 1], ['==', ['get', 'handle_status_id'], 5]], //拆除复耕
          '#F4E004',
          // 默认
          '#F70303',
        ],
        'line-width': 5,
      },
    });

    map.addLayer({
      id: 'fufeiLayerFill',
      type: 'fill',
      source: {
        type: 'vector',
        tiles: [
          VITE_GLOB_API_URL_VAR.value +
            '/api/DroneCaseInfoSingle/QueryVectorTileByTable?z={z}&x={x}&y={y}&table=view_drone_shp_data' +
            sql_filter +
            '&field="gid","handle_status_id","is_illegal","measure_name","typename","Id",',
        ],
        //
        minzoom: 1,
        maxzoom: 20,
      },
      'source-layer': 'view_drone_shp_data',
      layout: {
        visibility:"visible",
      },
      paint: {
        'fill-color': [
          'case',
          ['all', ['==', ['get', 'is_illegal'], 0], ['==', ['get', 'handle_status_id'], 5]], //合法
          '#0AF703',
          ['any', ['==', ['get', 'is_illegal'], 1], ['!=', ['get', 'handle_status_id'], 5]], //违法
          '#F70303',
          ['all', ['==', ['get', 'is_illegal'], 2], ['==', ['get', 'handle_status_id'], 5]], //其他
          '#0382F7',
          ['all', ['==', ['get', 'measure_name'], 0], ['==', ['get', 'handle_status_id'], 5]], //补办手续
          '#AD04F4',
          ['all', ['==', ['get', 'measure_name'], 1], ['==', ['get', 'handle_status_id'], 5]], //拆除复耕
          '#F4E004',
          // 默认
          '#F70303',
        ],
        'fill-opacity': 0.4,
      },
    });


    map.on('click', 'fufeiLayerFill', (e) => {
      emits('handlerGetDetails', e.features[0].properties);
    });

  }

  // 航飞区域
  function getHangFeiAreaData(){
    axios({
      method: 'get',
      url: `http://120.222.154.7:8090/geoserver/linyishi/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=linyishi%3Azhongdianquyu&maxFeatures=99999&outputFormat=application%2Fjson`,
    }).then((res) => {
      loadHangFeiAreaLayer(res.data);
    });
  }

  function loadHangFeiAreaLayer(geojson){
      map.addSource('hangfeiAreaSource', {
        type: 'geojson',
        data: geojson,
      });
      map.addLayer({
        id: 'hangfeiareaLine',
        type: 'line',
        source: 'hangfeiAreaSource',
        paint: {
          'line-color': '#e37575', // 设置线的颜色
          'line-width': 3, // 设置线的宽度
        },
        layout:{
          "visibility":"none"
        }
      });

      map.addLayer({
        id: 'hangfeiareaFill',
        type: 'fill',
        source: 'hangfeiAreaSource',
        paint: {
          'fill-color': '#e37575',
          'fill-opacity': 0.3
        },
        layout:{
          "visibility":"none"
        }
      });
      map.addLayer({
          'id': 'hangfeiareaLable',
          'type': 'symbol',
          'source': 'hangfeiAreaSource',
          'layout': {
              'text-field': ['get', 'xz'],
              'text-font': ['Open Sans Bold', 'Arial Unicode MS Bold'],
              'text-size': 12,
              'text-anchor': 'center',
              "visibility":"none"
          },
          'paint': {
              // 'text-color': '#000000'
              'text-color': '#041B36',
              'text-halo-color': '#fff',
              'text-halo-width': 2,
          }
      });
  }

  // 航飞规划
  function getHangFeiPlanData(){
    axios({
      method: 'get',
      url: `http://120.222.154.7:8090/geoserver/linyishi/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=linyishi%3Ahangfeiquyu&maxFeatures=9990&outputFormat=application%2Fjson`,
    }).then((res) => {
      loadHangFeiPlanLayer(res.data);
    });
  }

  function loadHangFeiPlanLayer(geojson){
      map.addSource('hangfeiPlanSource', {
        type: 'geojson',
        data: geojson,
      });
      map.addLayer({
        id: 'hangfeiplanLine',
        type: 'line',
        source: 'hangfeiPlanSource',
        paint: {
          'line-color': '#6F7FF4', // 设置线的颜色
          'line-width': 3, // 设置线的宽度
        },
        layout:{
          "visibility":"none"
        }
      });
      map.addLayer({
        id: 'hangfeiplanFill',
        type: 'fill',
        source: 'hangfeiPlanSource',
        paint: {
          'fill-color': '#6F7FF4',
          'fill-opacity': 0.5
        },
        layout:{
          "visibility":"none"
        }
      });
      map.addLayer({
          'id': 'hangfeiplanLable',
          'type': 'symbol',
          'source': 'hangfeiPlanSource',
          'layout': {
              'text-field': ['get', 'Name'],
              'text-font': ['Open Sans Bold', 'Arial Unicode MS Bold'],
              'text-size': 12,
              'text-anchor': 'center',
              "visibility":"none"
          },
          'paint': {
              // 'text-color': '#000000'
              'text-color': '#041B36',
              'text-halo-color': '#fff',
              'text-halo-width': 2,
          }
      });
  }

  // 绘制范围

const handlerDrawPolygon = () => {
  mp.draw('Polygon');
  mp.on('Polygon', function (e) {
    Modal.confirm({
      title: '是否查询历史影像?',
      onCancel() {

      },
      async onOk() {
          let geojson = {
              "type": "Feature",
              "geometry": {
                  "type": "Polygon",
                  "coordinates":[]
              }
          }
          let coordinates = [];
          e?.forEach((item, index) => {
            coordinates?.push([item.lng, item.lat]);
          });
          coordinates.push(coordinates[0]);
          geojson.geometry.coordinates[0] = coordinates
          let wktStr =  GeojsonToWkt(geojson.geometry)
          emits("handlerQueryIntersectTif",wktStr)
      },
    });
    // emit('mapDraw', 'Polygon', e);
  });
};
const handlerQueryIntersectTif = (wkt:string)=>{
  let query = {
    TargetShape:wkt,
    page:1,
    limit:10,
    key:null
  }
  getIntersectTif(query).then(res=>{
    if(res.code == 200){
      
    }
  })
}

const tifLayers = ref<Array<String>>([]);

function handlerChangeTifLayer(item){
  if (item.checked) {  // 加载
    if(map.getLayer(item.tifId)){
      map.setLayoutProperty(item.tifId, 'visibility', 'visible');
    }else{
      map.addSource("source"+item.tifId,{
          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",
            item.accessUrl.replace("http://192.168.10.141","http://localhost")
          ],
          tileSize: 256,
      })
      map.addLayer({
        id: item.tifId,
        type: "raster",
        source: "source"+item.tifId,
        layout: {
          visibility: "visible",
        },
        paint: {},
      })
      tifLayers.value.push(item.tifId);
    }
  } else {
    map.setLayoutProperty(item.tifId, 'visibility', 'none');
  }
}


// 取消绘制
const handlerDeletePolygon = ()=>{
  mp.deleteDraw();
  tifLayers.value?.forEach((item,index)=>{
    if(map.getLayer(item)){
      map.removeLayer(item);
      map.removeSource("source"+item);
    }
  })

  tifLayers.value = [];
}



const mapAngle = ref<String>( "2D")

const handlerChangeMapAngle = ()=>{
    if(map){
        const currentPitch = map.getPitch();
        if (currentPitch === 0) {
            map.easeTo({ pitch: 60, bearing: 0, duration: 1000 });
            map.dragRotate.enable(); // 启用拖动旋转
            map.pitchWithRotate = true; // 启用旋转时俯仰变化
            mapAngle.value = "3D";
        } else {
            map.easeTo({ pitch: 0, bearing: 0, duration: 1000 });
            map.dragRotate.disable(); // 禁用拖动旋转
            map.pitchWithRotate = false; // 禁用旋转时俯仰变化
            mapAngle.value = "2D";
        }
        
    }
}
// 回到初始视角
const handlerInitialize = ()=>{
    map.flyTo({
        center: [118.30207505530701, 35.30123435040745],        // 设置中心点坐标
        zoom: 8,             // 设置缩放等级
    });


}

  // 抛出函数
  defineExpose({
    handlerChangeCounty, // 切换县区
    handlerChangeLayerVisible, // 控制图层显示隐藏
    handlerLoadPolygon,
    handlerLocation, // 定位
    handlerUpdateUavLayer, // 无人机图层
    handlerDrawPolygon,  //绘制多边形
    handlerDeletePolygon, // 取消绘制
    handlerChangeTifLayer,
  });


</script>
<style type="less" scoped>
  .map-container {
    width: 100%;
    height: 100%;
  }
  ::v-deep .mapboxgl-ctrl-logo {
    display: none !important;
  }
  .map-type-switch-container{
    width:280px;
    height:40px;
    position:absolute;
    top:102px;
    right:23px;
    z-index:9999;
    font-size:22px;
    color:#fff;
    text-align:center;
    line-height:40px;
    cursor:pointer;
}
.map-type-switch-container .switch-button{
    line-height:40px;
    width:150px;
    height:40px;
    float:left;
    background: url(/map/change-view-btn.png);
    background-size:100% 100%;
}

.map-type-switch-container .switch-button span{
    font-size:14px;
}

.home-button{
    width:40px;
    height:40px;
    background:url(/map/home-btn.png);
    background-size: 100% 100%;
    float:right;
    position:relative;
    line-height:100px;
    text-align:center;
}


</style>
