<template>
  <div :id="mapContainerName" class="map-container">
    <div class="search-container-box">
      <SearchComponent
        @toPosition="toPosition"
        @handlerFilter="handlerFilter"
        :layerSettings="layerSettings"
      ></SearchComponent>
      <div class="to-location-button" @click="LocationShow = !LocationShow">
        <EnvironmentOutlined style="color: #fff; font-size: 20px" />
      </div>
      <div class="to-location-input" v-if="LocationShow">
        <div class="location-operation">
          <span style="font-size: 16px">坐标定位</span>
          <span style="float: right; margin-right: 10px; cursor: pointer">
            <CloseOutlined @click="handlerLocationClose" />
          </span>
        </div>
        <div class="location-item-list-coantienr">
          <a-table :dataSource="locationArrays" size="small" :pagination="false">
            <a-table-column-group>
              <a-table-column key="lng" title="经度(Y)" data-index="lng">
                <template #default="{ record }">
                  <a-input
                    v-model:value="record.lng"
                    @chagne="handlerLocationChange"
                    size="small"
                  />
                </template>
              </a-table-column>

              <a-table-column key="lat" title="纬度(X)" data-index="lat">
                <template #default="{ record }">
                  <a-input
                    v-model:value="record.lat"
                    @chagne="handlerLocationChange"
                    size="small"
                  />
                </template>
              </a-table-column>

              <a-table-column key="operation" title="操作" data-index="operation" width="100px">
                <template #default="{ record, index }">
                  <a-button type="default" size="small" @click="handlerLocationFlyTo(index)"
                    ><EnvironmentOutlined
                  /></a-button>
                  &nbsp;
                  <a-button type="default" size="small" @click="handlerClearDate(index)"
                    ><DeleteOutlined
                  /></a-button>
                </template>
              </a-table-column>
            </a-table-column-group>
          </a-table>
        </div>
      </div>
    </div>
    <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
        :class="`switch-button ${showTodayType === 1 ? 'switch-button-active' : ''}`"
        style="margin-top: 20px"
        @click="showToday(1)"
      >
        <span>&nbsp;最新线索</span>
      </div>
      <div
        :class="`switch-button ${showTodayType === 0 ? 'switch-button-active' : ''}`"
        style="margin-top: 10px"
        @click="showToday(0)"
      >
        <span>&nbsp;历史线索</span>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
  import { ref, onMounted, defineExpose, defineEmits, defineProps, watch, reactive } 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, getUserOrgs, getNetworkType } from '@/api/tiankongdi';
  import axios from 'axios';
  import SearchComponent from './SearchComponent.vue';
  import { getAppEnvConfig } from '@/utils/env';
  const { VITE_GLOB_API_URL, VITE_GLOB_LAN_API_URL, VITE_GLOB_GEOSERVER_PREFECTURE_CITY_NAME } =
    getAppEnvConfig();
  const VITE_GLOB_API_URL_VAR = ref<String>(VITE_GLOB_API_URL);
  import { waiData } from '../LargeScreenMap/linyishi';
  const mapContainerName = ref<String>();
  mapContainerName.value = 'mapContainer-' + generateUUID();
  const { VITE_GLOB_YINGXIANG_SERVER, VITE_GLOB_YAOGANYINGXIANG_SERVER } = getAppEnvConfig();
  import {
    CloseOutlined,
    MinusOutlined,
    ExpandAltOutlined,
    EnvironmentOutlined,
    DeleteOutlined,
  } from '@ant-design/icons-vue';
  import proj4 from 'proj4';

  interface LocationItem {
    lng: string;
    lat: string;
  }
  const LocationShow = ref<Boolean>(false);
  const locationArrays = ref<LocationItem[]>([{ lng: '', lat: '' }]);
  const locationDrawArrays = ref<LocationItem[]>();
  const locationGeoJson = reactive({
    point: {
      type: 'FeatureCollection',
      features: [],
    },
    polyline: {
      type: 'FeatureCollection',
      features: [],
    },
    polygon: {
      type: 'FeatureCollection',
      features: [],
    },
  });
  const networkType = ref('WAN');
  const showTodayType = ref<null | number>(null);
  const handlerLoadPolygonAttr = ref({
    code: '',
    filter: '',
    type: '',
    level: '',
  });

  //
  import { TableOutlined, GlobalOutlined, HomeOutlined } from '@ant-design/icons-vue';

  // 图层控制 历史影像
  import { message, Modal } from 'ant-design-vue';
  import U from 'mapbox-gl-utils';
  import { MP } from './src/MP';
  import { GeojsonToWkt } from './src/WktGeojsonTransform';

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

  let isZoomVisible: any = false;
  let map: Map;
  let mp: any = null;
  const props = defineProps({
    layer: Object,
    defaultColor: String,
  });
  const layerSettings = ref<any>({});
  const layerDefaultColor = ref<String>();
  watch(
    () => props.layer,
    (val) => {
      layerSettings.value = val;
      layerDefaultColor.value = props.defaultColor;
    },
  );
  // 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: {
          'raster-tiles': {
            type: 'raster',
            tiles: [
              `http://t0.tianditu.gov.cn/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=${TINADITU_TOKEN}`,
            ],
            tileSize: 256,
            minzoom: 1,
            maxzoom: 17,
          },
          'raster-tiles-font': {
            type: 'raster',
            tiles: [
              `https://t0.tianditu.gov.cn/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=${TINADITU_TOKEN}`,
            ],
            tileSize: 256,
          },
        },
        layers: [
          {
            id: 'tdt-vec-tiles',
            type: 'raster',
            source: 'raster-tiles-font',
            maxZoom: 32,
          },
          {
            id: 'tdt-img-tiles',
            type: 'raster',
            source: 'raster-tiles',
            maxZoom: 32,
          },
          // {
          //     id: 'tdt-wms-tiles',
          //     type: 'raster',
          //     source: 'raster-tiles-geo',
          // },
        ],
      },
      maxZoom: 22,
      minZoom: 8,
      zoom: 8,
      pitch: 0,
      // center: [117.847293,37.542609],
      center: [117.978146, 37.420085],
    });
  };
  // load map info

  function loadMapInfo() {
    map = initMap();

    map.on('load', () => {
      //挂载mapbox-gl-utils
      U.init(map);
      mp = new MP(map);
      // 添加地形数据
      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';
      handlerCheckUserOrgs();
      // handlerLoadMaskLayer();
      getMaskData();
      handlerDealStreet();
      handlerDealCountry();
      // 视频监控
      addMonitorLayer();
      // 叠加遥感影像和高清影像
      try {
        axios.get(VITE_GLOB_LAN_API_URL + '/api/DroneCloudQuery/IsPublic').then((res) => {
          if (res.data.result) {
            networkType.value = 'WAN';
          } else {
            networkType.value = 'LAN';
            // 加载内网影像
            loadYingXiangLayer();
          }
        });
      } catch (e) {
        networkType.value = 'WAN';
      } finally {
      }
      const sources = map.getStyle().sources;
      let loadedSources = 0;
      Object.keys(sources).forEach((sourceId) => {
        map.on('sourcedata', (e) => {
          if (e.sourceId === sourceId && e.isSourceLoaded) {
            loadedSources++;
            if (loadedSources === Object.keys(sources).length) {
              console.log('所有图层关联的数据源已加载完成');
              emits('changeLoading', false);
            }
          }
        });
      });
    });
  }

  function loadYingXiangLayer() {
    map.addSource('yaogan', {
      type: 'raster',
      tiles: [VITE_GLOB_YAOGANYINGXIANG_SERVER],
      tileSize: 256,
      minzoom: 16,
      maxzoom: 24,
    });
    map.addSource('yingxiang', {
      type: 'raster',
      tiles: [VITE_GLOB_YINGXIANG_SERVER],
      tileSize: 256,
      minzoom: 16,
      maxzoom: 24,
    });

    map.addLayer({
      id: 'yaogan',
      type: 'raster',
      source: 'yaogan',
      layout: {
        visibility: networkType.value == 'LAN' ? 'visible' : 'none',
      },
      minzoom: 9,
      maxzoom: 15,
    });

    map.addLayer({
      id: 'yingxiang',
      type: 'raster',
      source: 'yingxiang',
      layout: {
        visibility: networkType.value == 'LAN' ? 'visible' : 'none',
      },
      minzoom: 13,
      maxzoom: 24,
    });
  }
  // 获取线索面数据
  const polygonVisibility = ref<String>('none');

  const isRootLevel = ref<Boolean>(false);
  async function handlerCheckUserOrgs() {
    let orgs = await getUserOrgs({});
    let isLevel = orgs.find((item, index) => {
      return (
        item.name == VITE_GLOB_GEOSERVER_PREFECTURE_CITY_NAME ||
        item.parentId == 0 ||
        item.parentName == '根节点'
      );
    });
    if (isLevel) {
      isRootLevel.value = true;
      handlerLoadPolygon('', '', '', '1');
    } else {
      isRootLevel.value = false;
      handlerLoadPolygon();
    }
  }

  function handlerLoadPolygon(code = '', filter = '', type = '', level = '') {
    handlerLoadPolygonAttr.value = {
      code,
      filter,
      type,
      level,
    };
    let sql_filter;
    let map_filter;
    let type_filter;
    let table_filter = layerSettings.value.tablename;
    let field_filter = '&field="gid","tubantype","Id","is_today",';
    let color_filter: any = [];
    if (code) {
      sql_filter = '&filter="countyid"=\'' + code + "'";
    } else {
      sql_filter = '';
    }
    if (filter && filter != '全部') {
      map_filter = ['all', ['==', ['get', 'tubantype'], filter]];
    } else {
      map_filter = ['!=', ['get', 'gid'], 0];
    }
    let legend = layerSettings.value.legend[0];
    color_filter.push('case');
    for (const key in legend) {
      color_filter.push(['all', ['==', ['get', 'tubantype'], key]]);
      color_filter.push(legend[key].colour);
    }
    color_filter.push(layerDefaultColor.value);
    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];
    }
    if (showTodayType.value !== null) {
      if (map_filter[0] == 'all') {
        map_filter.push(['==', ['get', 'is_today'], showTodayType.value]);
      } else {
        map_filter = ['all', map_filter, ['==', ['get', 'is_today'], showTodayType.value]];
      }
    }
    if (map.getSource('historyLayerLine')) {
      polygonVisibility.value = map.getLayoutProperty('historyLayerLine', 'visibility');
      map.removeLayer('historyLayerLine');
      map.removeLayer('historyLayerFill');
      map.removeSource('historyLayerLine');
      map.removeSource('historyLayerFill');
    }

    if (level) {
    } else {
      sql_filter =
        '&filter=streetid in ( select CAST("OrgId" AS VARCHAR) from sys_userorg where "UserId" = ' +
        localStorage.getItem('userid') +
        ') or countyid in ( select CAST("OrgId" AS VARCHAR) from sys_userorg where "UserId" = ' +
        localStorage.getItem('userid') +
        ')';
    }
    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=' +
            table_filter +
            sql_filter +
            field_filter,
        ],
        minzoom: 1,
        maxzoom: 20,
        cluster: true, // 启用聚合
        clusterMaxZoom: 0, // 最大聚合缩放级别
        clusterRadius: 0, // 聚合半径
      },
      'source-layer': table_filter,
      layout: {
        'line-join': 'round',
        'line-cap': 'round',
        visibility: polygonVisibility.value,
      },
      filter: map_filter,
      paint: {
        'line-color': color_filter,
        '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=' +
            table_filter +
            sql_filter +
            field_filter,
        ],
        minzoom: 1,
        maxzoom: 20,
        cluster: false,
      },
      'source-layer': table_filter,
      filter: map_filter,
      layout: {
        visibility: polygonVisibility.value,
      },
      paint: {
        'fill-color': color_filter,
        'fill-opacity': 0.5,
      },
    });
    emits('onload');

    map.on('click', 'historyLayerFill', (e) => {
      console.log('handlerGetDetails', e.features[0].properties);
      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: 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 toPosition(item) {
    handlerLocation(item, 17.2);
    handlerLoadSearchResult(item);
  }

  function handlerFilter(item) {
    // handlerLoadPolygon("",item);
    if (isRootLevel.value) {
      handlerLoadPolygon('', item, '', '1');
    } else {
      handlerLoadPolygon('', item, '', '');
    }
  }
  function handlerLoadSearchResult(item) {
    let geojson = {
      type: 'FeatureCollection',
      features: [
        {
          type: 'Feature',
          geometry: {
            type: 'Point',
            coordinates: item.location,
          },
          properties: {
            name: item.id,
          },
        },
      ],
    };

    // if (map.getSource("searchSource")) {
    //     map.getSource("searchSource").setData(geojson);
    // } else {
    //     map.addSource("searchSource", {
    //     type: "geojson",
    //     data: geojson,
    //     });
    // }

    // if (map.hasImage("searchIcon")) {
    // } else {
    //     map.loadImage(
    //     "/public/statistical/search-icon.png",
    //     function (error, image) {
    //         if (error) throw error;
    //         map.addImage("searchIcon", image);
    //     }
    //     );
    // }

    // if (map.getLayer("searchLayer")) {
    // } else {
    //     map.addLayer({
    //     id: "searchLayer",
    //     type: "symbol",
    //     source: "searchSource",
    //     layout: {
    //         "icon-image": "searchIcon",
    //         "icon-size": 1.2,
    //         "text-field": "{name}",
    //         "text-offset": [0, 2],
    //         "text-anchor": "top",
    //         "text-size": 12,
    //     },
    //     paint: {
    //         "text-color": "#fff",
    //     },
    //     });
    // }
  }
  // 加载热力图线索数据
  function handlerLoadHeatLayer(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: 'none',
        },
        paint: {
          'heatmap-weight': ['interpolate', ['linear'], ['get', 'mag'], 0, 1, 7, 0],
          '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'], 4, 7, 11, 20],
          'heatmap-opacity': ['interpolate', ['linear'], ['zoom'], 7, 0, 8, 1],
        },
      });
    }

    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 = 17) {
    map.flyTo({
      center: lngLat,
      zoom: zoom,
      bearing: 0,
      speed: 1, // 飞行速度
      curve: 2, // 飞行曲线
      essential: true,
      easing(t) {
        // 飞行动画函数
        return t;
      },
    });
  }

  // 获取县区边界数据
  const handlerDealCountry = (): void => {
    map.addSource('wmsSource', {
      type: 'vector',
      scheme: 'tms',
      tiles: [
        'http://175.27.168.120:8080/geoserver/gwc/service/tms/1.0.0/binzhou%3Axianmian@EPSG%3A900913@pbf/{z}/{x}/{y}.pbf',
      ],
      tileSize: 512,
    });
    map.addLayer({
      id: 'xianjie',
      type: 'line',
      source: 'wmsSource',
      'source-layer': 'xianmian',
      layout: {
        visibility: 'visible',
      },
      paint: {
        'line-color': '#6f7ff4',
        'line-width': 4,
      },
    });
    map.addSource('xianjiepoint', {
      type: 'vector',
      scheme: 'tms',
      tiles: [
        'http://175.27.168.120:8080/geoserver/gwc/service/tms/1.0.0/binzhou%3Axiandian@EPSG%3A900913@pbf/{z}/{x}/{y}.pbf',
        // "http://175.27.168.120:8080/geoserver/binzhou/wms?service=WMS&version=1.1.0&request=GetMap&layers=binzhou%3Ashimian&bbox=117.25779007900007%2C36.68862257500007%2C118.61855647400007%2C38.33089195900007&width=636&height=768&srs=EPSG%3A4490&format=application/openlayers"
      ],
      tileSize: 512,
    });
    map.addLayer({
      id: 'xianjiepoint',
      type: 'symbol',
      source: 'xianjiepoint',
      'source-layer': 'xiandian',
      layout: {
        visibility: 'visible',
        'text-field': '{XQMC}',
        'text-size': 18,
      },
      paint: {
        'text-color': '#041B36',
        'text-halo-color': '#fff',
        'text-halo-width': 2,
      },
      minzoom: 8,
      maxzoom: 10,
    });
  };

  // 渲染县界白板图层
  const handlerLoadPanelLayer = (geojson) => {
    if (map.getSource('countyPanelLayer')) {
      map.getSource('countyPanelSource').setData(geojson);
    } else {
      map.addSource('countyPanelSource', {
        type: 'geojson',
        data: geojson,
      });
      map.addLayer({
        id: 'countyPanelLayer',
        type: 'fill',
        source: 'countyPanelSource',
        layout: {
          visibility: 'none',
        },
        paint: {
          'fill-color': [
            'case',
            ['==', ['get', 'xzqdm_1'], '371302'],
            '#49B0F9',
            ['==', ['get', 'xzqdm_1'], '371311'],
            '#3EABFA',
            ['==', ['get', 'xzqdm_1'], '371312'],
            '#27A2FB',
            ['==', ['get', 'xzqdm_1'], '3713122'],
            '#34E6B1',
            ['==', ['get', 'xzqdm_1'], '3713001'],
            '#1099FB',
            ['==', ['get', 'xzqdm_1'], '3713271'],
            '#0695FB',
            ['==', ['get', 'xzqdm_1'], '371321'],
            '#058DEE',
            ['==', ['get', 'xzqdm_1'], '371322'],
            '#09C78E',
            ['==', ['get', 'xzqdm_1'], '371323'],
            '#047DD4',
            ['==', ['get', 'xzqdm_1'], '371324'],
            '#94D515',
            ['==', ['get', 'xzqdm_1'], '371325'],
            '#0568B0',
            ['==', ['get', 'xzqdm_1'], '371326'],
            '#3EABFA',
            ['==', ['get', 'xzqdm_1'], '371327'],
            '#49B0F9',
            ['==', ['get', 'xzqdm_1'], '371328'],
            '#27A2FB',
            ['==', ['get', 'xzqdm_1'], '371329'],
            '#94D515',
            '#1099FB',
          ],
          'fill-opacity': 0.9,
        },
      });

      // if(map.getLayer("countyPanelLayer")){
      //     map.moveLayer("countyPanelLayer","countyLayer");
      //     map.moveLayer("countyPanelLayer","historyLayerLine");
      //     map.moveLayer("countyPanelLayer","historyLayerFill");
      // }
    }
  };

  function getMaskData() {
    map.addLayer({
      id: 'linyishizhezhao',
      type: 'raster',
      source: {
        type: 'raster',
        tiles: [
          'http://175.27.168.120:8080/geoserver/gwc/service/wms?service=WMS&version=1.1.0&request=GetMap&layers=binzhou%3Azhezhao&styles=&bbox={bbox-epsg-3857}&width=256&height=256&srs=EPSG:3857&format=image/png&TRANSPARENT=TRUE',
        ],
        tileSize: 256,
      },
      layout: {
        visibility: 'visible',
      },
    });
  }

  // 加载地图遮罩
  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',
      },
    });
  }

  // 获取乡镇数据
  const handlerDealStreet = (): void => {
    map.addSource('zhenjie', {
      type: 'vector',
      scheme: 'tms',
      tiles: [
        'http://175.27.168.120:8080/geoserver/gwc/service/tms/1.0.0/binzhou%3Azhenmian@EPSG%3A900913@pbf/{z}/{x}/{y}.pbf',
      ],
      tileSize: 512,
    });
    map.addLayer({
      id: 'zhenjie',
      type: 'line',
      source: 'zhenjie',
      'source-layer': 'zhenmian',
      layout: {
        visibility: 'visible',
      },
      paint: {
        'line-color': '#42befb', // 设置线的颜色
        'line-width': 1, // 设置线的宽度
      },
      minzoom: 10,
      maxzoom: 24,
    });
    map.addSource('zhenjiepoint', {
      type: 'vector',
      scheme: 'tms',
      tiles: [
        'http://175.27.168.120:8080/geoserver/gwc/service/tms/1.0.0/binzhou%3Azhendian@EPSG%3A900913@pbf/{z}/{x}/{y}.pbf',
      ],
      tileSize: 512,
    });
    map.addLayer({
      id: 'zhenjiepoint',
      type: 'symbol',
      source: 'zhenjiepoint',
      'source-layer': 'zhendian',
      layout: {
        visibility: 'visible',
        'text-field': '{XZQMC}',
      },
      paint: {
        'text-color': '#041B36',
        'text-halo-color': '#fff',
        'text-halo-width': 2,
      },
      minzoom: 10,
      maxzoom: 24,
    });
  };

  let VillageGeojson = {};
  const handlerLoadVillageLayer = () => {
    // 绘制线
    if (map.getSource('villageSource')) {
      map.getSource('villageSource').setData(VillageGeojson);
    } else {
      map.addSource('villageSource', {
        type: 'geojson',
        data: VillageGeojson,
        minzoom: 12,
        maxzoom: 24,
      });
      map.addLayer({
        id: 'villageLayer',
        type: 'line',
        source: 'villageSource',
        paint: {
          'line-color': '#42befb', // 设置线的颜色
          'line-width': 2, // 设置线的宽度
        },
        minzoom: 12,
        maxzoom: 24,
      });

      map.addLayer({
        id: 'villageLabelLayer',
        type: 'symbol',
        source: 'villageSource',
        layout: {
          'text-field': ['get', 'zldwmc'],
          'text-font': ['Open Sans Bold', 'Arial Unicode MS Bold'],
          'text-size': 12,
          'text-anchor': 'center',
        },
        paint: {
          'text-color': '#041B36',
          'text-halo-color': '#fff',
          'text-halo-width': 2,
        },
      });
    }
  };

  // 控制图层显示隐层
  /**
   * 热力图：heatLayer
   *
   * 线索线：historyLayerLine
   *
   * 线索面：historyLayerFill
   *
   * 行政区划：countyLayer
   *
   *
   *
   * */
  function handlerChangeLayerVisible(layerName, checked) {
    if (checked) {
      map.setLayoutProperty(layerName, 'visibility', 'visible');
    } else {
      map.setLayoutProperty(layerName, 'visibility', 'none');
    }

    if (layerName == 'countyPanelLayer') {
      if (map.getLayer('countyPanelLayer')) {
        map.moveLayer('countyPanelLayer', 'streetLayer');
        map.moveLayer('countyPanelLayer', 'streetLabelLayer');
        map.moveLayer('countyPanelLayer', 'countyLayer');
        map.moveLayer('countyPanelLayer', 'historyLayerFill');
        map.moveLayer('countyPanelLayer', 'historyLayerLine');
      }
    }
  }

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

  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: [117.978146, 37.420085], // 设置中心点坐标
      zoom: 8, // 设置缩放等级
      pitch: 0,
      bearing: 0,
      duration: 1000,
    });
  };

  onMounted(() => {
    mapboxgl.accessToken = MAPBOX_TOKEN;

    // 获取网络环境后加载地图

    loadMapInfo();
  });

  // 抛出函数
  defineExpose({
    handlerChangeCounty, // 切换县区
    handlerChangeLayerVisible, // 控制图层显示隐藏
    handlerLoadPolygon,
    handlerDrawPolygon, // 绘制范围
    handlerDeletePolygon, // 取消绘制
    handlerChangeTifLayer, // 图层切换
  });

  /* 图层控制 视频监控*/

  import MonitoringData from './MonitoringData.json';

  function addMonitorLayer() {
    // 加载监控图标
    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': true,
        visibility: 'none',
        'icon-allow-overlap': true,
      },
      paint: {
        'text-color': '#041B36',
        'text-halo-color': '#fff',
        'text-halo-width': 2,
      },
      minzoom: 0, // 最小缩放级别
      maxzoom: 22, // 最大缩放级别
    });

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

  function handlerDeletePolygon() {
    mp.deleteDraw();
  }
  function handlerDrawPolygon() {
    // 先移除查询的影像图层
    handlerDeleteHistoryLayer();

    mp.draw('Polygon');
    mp.on('Polygon', function (e) {
      Modal.confirm({
        title: '是否查询历史影像?',
        onCancel() {
          // mp.deleteDraw();
        },
        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 tifLayers = ref([]);

  function handlerChangeTifLayer(item) {
    if (item.type == 'historyLayer' || item.type == 'speciaLayer') {
      if (item.checked) {
        // 加载
        if (map.getLayer(item.id)) {
          map.setLayoutProperty(item.id, 'visibility', 'visible');
        } else {
          map.addSource('source' + item.id, {
            type: 'raster',
            tiles: [item.url],
            tileSize: 256,
          });
          map.addLayer({
            id: item.id,
            type: 'raster',
            source: 'source' + item.id,
            layout: {
              visibility: 'visible',
            },
            paint: {},
          });

          if (item.type == 'historyLayer') {
            tifLayers.value.push(item.id);
            console.log('tifLayers', tifLayers.value);
          }

          map.moveLayer(item.id, 'historyLayerFill');
          map.moveLayer(item.id, 'historyLayerLine');
        }
      } else {
        map.setLayoutProperty(item.id, 'visibility', 'none');
      }
    } else if (item.type == 'dataLayer') {
      if (item.id == 'Monitor') {
        if (map.getLayer('JianKong')) {
          if (item.checked) {
            map.setLayoutProperty('JianKong', 'visibility', 'visible');
          } else {
            map.setLayoutProperty('JianKong', 'visibility', 'none');
          }
        }
      } else if (item.id == 'Data') {
        if (map.getLayer('historyLayerLine')) {
          if (item.checked) {
            map.setLayoutProperty('historyLayerLine', 'visibility', 'visible');
            map.setLayoutProperty('historyLayerFill', 'visibility', 'visible');
          } else {
            map.setLayoutProperty('historyLayerLine', 'visibility', 'none');
            map.setLayoutProperty('historyLayerFill', 'visibility', 'none');
          }
        }
      }
    } else if (item.type == 'baseLayer') {
      switch (item.id) {
        case 1:
          handlerChangeLayerVisible('tdt-img-tiles', false);
          handlerChangeLayerVisible('tdt-vec-tiles', true);
          handlerChangeLayerVisible('yaogan', false);
          handlerChangeLayerVisible('yingxiang', false);
          handlerChangeLayerVisible('countyPanelLayer', false);
          break;
        case 2:
          handlerChangeLayerVisible('tdt-img-tiles', true);
          handlerChangeLayerVisible('yaogan', true);
          handlerChangeLayerVisible('yingxiang', true);
          handlerChangeLayerVisible('tdt-vec-tiles', false);
          handlerChangeLayerVisible('countyPanelLayer', false);
          break;
        case 3:
          handlerChangeLayerVisible('tdt-img-tiles', false);
          handlerChangeLayerVisible('tdt-vec-tiles', false);
          handlerChangeLayerVisible('yaogan', false);
          handlerChangeLayerVisible('yingxiang', false);
          handlerChangeLayerVisible('countyPanelLayer', true);
          break;
      }
    }

    function handlerChangeTifLayer(item) {
      if (item.type == 'historyLayer' || item.type == 'speciaLayer') {
        if (item.checked) {
          // 加载
          if (map.getLayer(item.id)) {
            map.setLayoutProperty(item.id, 'visibility', 'visible');
          } else {
            map.addSource('source' + item.id, {
              type: 'raster',
              tiles: [item.url],
              tileSize: 256,
            });
            map.addLayer({
              id: item.id,
              type: 'raster',
              source: 'source' + item.id,
              layout: {
                visibility: 'visible',
              },
              paint: {},
            });
            tifLayers.value.push(item.id);

            map.moveLayer(item.id, 'historyLayerFill');
            map.moveLayer(item.id, 'historyLayerLine');
          }
        } else {
          map.setLayoutProperty(item.id, 'visibility', 'none');
        }
      } else if (item.type == 'dataLayer') {
        if (item.id == 'Monitor') {
          if (map.getLayer('JianKong')) {
            if (item.checked) {
              map.setLayoutProperty('JianKong', 'visibility', 'visible');
            } else {
              map.setLayoutProperty('JianKong', 'visibility', 'none');
            }
          }
        } else if (item.id == 'Data') {
          if (map.getLayer('historyLayerLine')) {
            if (item.checked) {
              map.setLayoutProperty('historyLayerLine', 'visibility', 'visible');
              map.setLayoutProperty('historyLayerFill', 'visibility', 'visible');
            } else {
              map.setLayoutProperty('historyLayerLine', 'visibility', 'none');
              map.setLayoutProperty('historyLayerFill', 'visibility', 'none');
            }
          }
        }
      } else if (item.type == 'baseLayer') {
        switch (item.id) {
          case 1:
            handlerChangeLayerVisible('tdt-img-tiles', false);
            handlerChangeLayerVisible('tdt-vec-tiles', true);
            handlerChangeLayerVisible('countyPanelLayer', false);
            break;
          case 2:
            handlerChangeLayerVisible('tdt-img-tiles', true);
            handlerChangeLayerVisible('tdt-vec-tiles', false);
            handlerChangeLayerVisible('countyPanelLayer', false);
            break;
          case 3:
            handlerChangeLayerVisible('tdt-img-tiles', false);
            handlerChangeLayerVisible('tdt-vec-tiles', false);
            handlerChangeLayerVisible('countyPanelLayer', true);
            break;
        }
      }
    }
  }

  function handlerDeleteHistoryLayer() {
    tifLayers.value?.forEach((item, index) => {
      if (map.getLayer(item)) {
        map.removeLayer(item);
        map.removeSource('source' + item);
      }
    });
    tifLayers.value = [];
  }
  const showToday = (value) => {
    if (showTodayType.value === value) {
      showTodayType.value = null;
    } else {
      showTodayType.value = value;
    }
    const { code, filter, type, level } = handlerLoadPolygonAttr.value;
    handlerLoadPolygon(code, filter, type, level);
  };
  const handlerLocationClose = () => {
    LocationShow.value = false;
  };
  const handlerLocationChange = (e) => {};
  // 定位跳转
  const handlerLocationFlyTo = (clickIndex: number) => {
    locationDrawArrays.value = [];
    locationArrays.value?.forEach((location) => {
      let obj = { ...location };
      //console.log(obj);
      locationDrawArrays.value?.push(obj);
    });

    locationDrawArrays.value?.forEach((item, index) => {
      // 坐标系转换
      if (item.lng > 180) {
        let coor = GkToCGCS2000([parseFloat(item.lng), parseFloat(item.lat)]);
        item.lng = coor[0];
        item.lat = coor[1];
      }
      if (item.lng && item.lat) {
        handlerLocationGeoJson();
      }
    });

    // 跳转坐标
    handlerLocation([
      locationDrawArrays.value[clickIndex].lng,
      locationDrawArrays.value[clickIndex].lat,
    ]);
  };
  // 投影转地理坐标系
  function GkToCGCS2000(lngLat) {
    try {
      // 需要根据投影度带确定转换参数
      let from_system = '';
      if (lngLat[0] >= 37000000 && lngLat[0] < 38000000) {
        from_system =
          '+proj=tmerc +lat_0=0 +lon_0=111 +k=1 +x_0=37500000 +y_0=0 +ellps=GRS80 +units=m +no_defs +type=crs';
      }
      if (lngLat[0] >= 38000000 && lngLat[0] < 39000000) {
        from_system =
          '+proj=tmerc +lat_0=0 +lon_0=114 +k=1 +x_0=38500000 +y_0=0 +ellps=GRS80 +units=m +no_defs +type=crs';
      }
      if (lngLat[0] >= 39000000 && lngLat[0] < 40000000) {
        // CGCS2000 / 3-degree Gauss-Kruger zone 39
        from_system =
          '+proj=tmerc +lat_0=0 +lon_0=117 +k=1 +x_0=39500000 +y_0=0 +ellps=GRS80 +units=m +no_defs +type=crs';
      } else if (lngLat[0] >= 40000000) {
        // CGCS2000 / 3-degree Gauss-Kruger zone 40
        from_system =
          '+proj=tmerc +lat_0=0 +lon_0=120 +k=1 +x_0=40500000 +y_0=0 +ellps=GRS80 +units=m +no_defs +type=crs';
      }
      // China Geodetic Coordinate System 2000
      // let to_system = "+proj=longlat +ellps=GRS80 +no_defs +type=crs";

      // WGS 84 -- WGS84 - World Geodetic System 1984,
      let to_system = '+proj=longlat +datum=WGS84 +no_defs +type=crs';
      // transform
      let trasnformLnglat = proj4(from_system, to_system, lngLat);
      return trasnformLnglat;
    } catch (e) {
      return null;
    }
  }
  const handlerLocationGeoJson = () => {
    locationGeoJson.point.features = [];
    locationGeoJson.polyline.features = [];
    locationGeoJson.polygon.features = [];

    locationDrawArrays.value?.forEach((item, index) => {
      if (item.lng && item.lat) {
        let feature = {
          type: 'Feature',
          geometry: {
            type: 'Point',
            coordinates: [parseFloat(item.lng), parseFloat(item.lat)],
          },
        };
        locationGeoJson.point.features.push(feature);
      }
    });
    handlerLocationLoadLayer();
    //console.log('locationGeoJson', locationGeoJson);
  };
  // 加载点、线、面图层
  const handlerLocationLoadLayer = () => {
    //console.log("locationGeoJson123",locationGeoJson);
    // 绘制点
    if (map.getSource('LocationPointSource')) {
      map.getSource('LocationPointSource').setData(locationGeoJson.point);
    } else {
      map.addSource('LocationPointSource', {
        type: 'geojson',
        data: locationGeoJson.point,
      });
      map.addLayer({
        id: 'LocationPointLayer',
        type: 'circle',
        source: 'LocationPointSource',
        paint: {
          'circle-radius': 5,
          'circle-color': '#408eff', // 设置点的颜色
        },
      });
    }

    // 绘制线
    if (map.getSource('LocationPolylineSource')) {
      map.getSource('LocationPolylineSource').setData(locationGeoJson.polyline);
    } else {
      map.addSource('LocationPolylineSource', {
        type: 'geojson',
        data: locationGeoJson.polyline,
      });
      map.addLayer({
        id: 'LocationLineLayer',
        type: 'line',
        source: 'LocationPolylineSource',
        paint: {
          'line-color': '#408eff', // 设置线的颜色
          'line-width': 2, // 设置线的宽度
        },
      });
    }

    // 绘制面
    if (map.getSource('LocationPolygonSource')) {
      map.getSource('LocationPolygonSource').setData(locationGeoJson.polygon);
    } else {
      map.addSource('LocationPolygonSource', {
        type: 'geojson',
        data: locationGeoJson.polygon,
      });
      map.addLayer({
        id: 'LocationPolygonLayer',
        type: 'fill',
        source: 'LocationPolygonSource',
        paint: {
          'fill-color': '#408eff', // 设置填充颜色
          'fill-opacity': 0.5, // 设置填充透明度
        },
      });
    }
  };
  const handlerClearDate = (index) => {
    locationArrays.value[index].lat = '';
    locationArrays.value[index].lng = '';
  };
</script>
<style type="scss" scoped>
  .map-container {
    width: 100%;
    height: 100%;
    position: relative;
  }
  .search-container-box {
    position: absolute;
    width: 330px;
    height: 40px;
    top: 72px;
    left: 73px;
    z-index: 9999;
  }

  .map-type-switch-container {
    width: 208px;
    height: 40px;
    position: absolute;
    top: 72px;
    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-active {
    color: yellow;
  }

  .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;
    text-align: center;
  }
  ::v-deep .mapboxgl-ctrl-logo {
    display: none !important;
  }
  .to-location-button {
    position: absolute;
    right: -165px;
    top: 0px;
    width: 36px;
    height: 36px;
    background-color: #0a62c6;
    border-radius: 6px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
  }
  .to-location-input {
    padding: 16px;
    padding-right: 4px;
    width: 418px;
    min-height: 60px;
    background: #fff;
    position: absolute;
    top: 48px;
    right: -547px;
    z-index: 999999;
    border-radius: 5px;
    box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.1);
    .location-operation {
      width: 100%;
      height: 40px;
      border-bottom: 1px solid #f1f1f1;
      margin-bottom: 12px;
    }
    .location-item-list-coantienr {
      width: 100%;
      max-height: 400px;
      overflow-y: auto;
      .location-item {
        line-height: 20px;
        margin-bottom: 6px;
      }
    }
  }
</style>
