<template>
  <div :id="mapContainerName" class="map-container" />
</template>
<script lang="ts" setup>
  import { ref, watch, 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 { getGeomData } from '@/api/demo/system';
  import { MAPBOX_TOKEN, TINADITU_TOKEN, defaultPaint, geoserverCodeValue } from './clound.data';
  import { getAppEnvConfig } from '@/utils/env';
  import axios from 'axios';

  const { VITE_GLOB_YINGXIANG_SERVER } = getAppEnvConfig();
  const { VITE_GLOB_API_URL } = getAppEnvConfig();
  const VITE_GLOB_API_URL_VAR = ref<String>(VITE_GLOB_API_URL);
  const mapContainerName = ref<String>();
  mapContainerName.value = 'mapContainer-' + generateUUID();

  const emits = defineEmits(['handleOpenImage', 'getDetailByFeature']);

  let map: Map;

  // init map
  const initMap = () => {
    return new mapboxgl.Map({
      container: mapContainerName.value,
      language: 'zh-cmn',
      projection: 'equirectangular', // 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,
          },
          '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,
          },
        ],
      },
      maxZoom: 22,
      minZoom: 5,
      zoom: 7.8,
      pitch: 0,
      center: [118.184425, 35.270654],
    });
  };

  // 地图定位
  function handlerLocation(lngLat, zoom) {
    map.flyTo({
      center: lngLat,
      zoom: zoom,
      bearing: 0,
      speed: 1,
      curve: 2,
      essential: true,
      easing(t) {
        return t;
      },
    });
  }

  // 获取县区边界数据
  const handlerDealCountry = (layerName): void => {
    let filterName = '';
    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, layerName);
    });
  };
  // 渲染县区边界数据
  const handlerLoadCountyLayer = (geojson, layerName) => {
    // 绘制线
    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, // 设置线的宽度
        },
      });
    }
    if (layerName && map.getLayer(layerName)) {
      map.moveLayer(layerName, '');
      if (layerName == 'AchievementManagerRaster') {
        if (map.getLayer('clusters')) {
          map.moveLayer('AchievementManagerRaster', 'clusters');
        }
        if (map.getLayer('cluster-count')) {
          map.moveLayer('AchievementManagerRaster', 'cluster-count');
        }
        // if (map.getLayer('unclustered-point')) {
        //   map.moveLayer('AchievementManagerRaster', 'unclustered-point');
        // }
      }
    }
  };

  // 获取乡镇数据
  const handlerDealStreet = (layerName): void => {
    axios({
      method: 'get',
      url: `http://175.27.168.120:8080/geoserver/linyishi/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=linyishi%3Azhenjie&maxFeatures=10000&outputFormat=application%2Fjson`,
    }).then((res) => {
      handlerLoadStreetLayer(res.data, layerName);
    });
  };
  // 渲染乡镇边界数据
  const handlerLoadStreetLayer = (geojson, layerName) => {
    // 绘制线
    if (map.getSource('streetSource')) {
      map.getSource('streetSource').setData(geojson);
    } else {
      map.addSource('streetSource', {
        type: 'geojson',
        data: geojson,
        minzoom: 10,
        maxzoom: 24,
      });
      map.addLayer({
        id: 'streetLayer',
        type: 'line',
        source: 'streetSource',
        paint: {
          'line-color': '#42befb', // 设置线的颜色
          'line-width': 2, // 设置线的宽度
        },
        minzoom: 10,
        maxzoom: 24,
      });
      map.addLayer({
        id: 'streetLabelLayer',
        type: 'symbol',
        source: 'streetSource',
        layout: {
          'text-field': ['get', 'xzqmc'],
          'text-font': ['Open Sans Bold', 'Arial Unicode MS Bold'],
          'text-size': ['interpolate', ['linear'], ['zoom'], 10, 0, 10.1, 12],
          'text-anchor': 'center',
        },
        paint: {
          'text-color': '#041B36',
          'text-halo-color': '#fff',
          'text-halo-width': 2,
        },
      });
      if (map.getLayer('countyLayer')) {
        map.moveLayer('streetLayer', 'countyLayer');
      }

      if (layerName && map.getLayer(layerName)) {
        if (layerName == 'AchievementManagerRaster') {
          if (map.getLayer('clusters')) {
            map.moveLayer('AchievementManagerRaster', 'clusters');
          }
          if (map.getLayer('cluster-count')) {
            map.moveLayer('AchievementManagerRaster', 'cluster-count');
          }
          // if (map.getLayer('unclustered-point')) {
          //   map.moveLayer('AchievementManagerRaster', 'unclustered-point');
          // }
        } else {
          map.moveLayer(layerName, '');
        }
      }
    }
  };

  // 图层管理-图层
  function GeoserverManagementRaster(chooseRows, lngLat, zoom, isMove, fillOpacity = 1) {
    // console.log(chooseRows);
    if (isMove) {
      handlerLocation(lngLat, zoom);
    }
    // 将映射数组转换为 match 表达式的输入
    const matchInput = geoserverCodeValue.flatMap(({ code, value }) => [code, value]);

    chooseRows?.forEach((chooseRow) => {
      map.addSource(chooseRow.dataTable, {
        type: 'vector',
        tiles: [
          VITE_GLOB_API_URL_VAR.value +
            '/api/ShpGeoLayer/QueryVectorTileByTable?z={z}&x={x}&y={y}&table=' +
            chooseRow.dataTable +
            '&field=id,dlbm,',
        ],
        minzoom: parseInt(1),
        maxzoom: parseInt(18),
      });

      // console.log(chooseRow.style);

      // 添加填充层
      map.addLayer({
        id: chooseRow.dataTable,
        type: 'fill',
        source: chooseRow.dataTable,
        'source-layer': chooseRow.dataTable,
        paint: chooseRow.style ? JSON.parse(chooseRow.style) : defaultPaint,
      });

      // 添加文本层
      map.addLayer({
        id: chooseRow.dataTable + '-text',
        type: 'symbol',
        source: chooseRow.dataTable,
        'source-layer': chooseRow.dataTable,
        layout: {
          'text-field': ['match', ['get', 'dlbm'], ...matchInput, ''],
          'text-font': ['Open Sans Bold', 'Arial Unicode MS Bold'],
          'text-size': ['interpolate', ['linear'], ['zoom'], 12, 0, 12.1, 12],
          // 'text-size': 12,
          'text-anchor': 'center',
          'symbol-placement': 'point',
          'text-allow-overlap': false,
          'text-padding': 20,
          'text-letter-spacing': 0.1,
          visibility: 'visible',
        },
        paint: {
          'text-color': '#ffffff', // 文本颜色
          'text-halo-color': '#000000', // 文本晕影颜色
          'text-halo-width': 1, // 文本晕影宽度
        },
      });
      map.on('click', chooseRow.dataTable, function (e) {
        // 显示弹窗
        if (e.features.length > 0) {
          // 获取第一个（也是唯一的）被点击的特征
          const feature = e.features[0];
          // console.log(400, feature);
          emits('getDetailByFeature', feature);
        }
      });
      if (map.getLayer('streetLayer')) {
        map.moveLayer(chooseRow.dataTable, 'streetLayer');
      }
    });
    // 透明度
    changeFillLayerOpacity('GeoserverManagementRaster', chooseRows, fillOpacity);
  }

  // 影像管理-图层
  function GeoTiffManagerRaster(chooseRows, lngLat, zoom, isMove, fillOpacity = 1) {
    // 清除图层
    if (isMove) {
      handlerLocation(lngLat, zoom);
    }
    chooseRows?.forEach((chooseRow, index) => {
      let tiles: any = [];
      let tile =
        'http://192.168.10.141:8080/geoserver/my_workspace/wms?service=WMS&version=1.1.0&request=GetMap&layers=my_workspace:' +
        chooseRow.layerName +
        '&styles=&bbox={bbox-epsg-3857}&width=256&height=256&srs=EPSG:3857' +
        '&format=image/png&TRANSPARENT=TRUE';
      tiles.push(tile);

      map.addSource(chooseRow.layerName, {
        type: 'raster',
        tiles: tiles,
        tileSize: 256,
      });
      map.addLayer({
        id: chooseRow.layerName,
        type: 'raster',
        source: chooseRow.layerName,
        layout: {
          visibility: 'visible',
        },
      });
      if (map.getLayer('streetLayer')) {
        map.moveLayer(chooseRow.layerName, 'streetLayer');
      }
    });
    // 透明度
    changeFillLayerOpacity('GeoTiffManagerRaster', chooseRows, fillOpacity);
  }

  // 航飞图片-图层
  function AchievementManagerRaster(taskLayerGeoJson, lngLat, zoom, isMove) {
    // resize();
    // 清除图层
    // clearTaskLayer('AchievementManagerRaster');
    // 县区边界
    if (!map.getLayer('streetLayer')) {
      handlerDealStreet('AchievementManagerRaster');
    }
    if (!map.getLayer('countyLayer')) {
      handlerDealCountry('AchievementManagerRaster');
    }
    if (isMove) {
      handlerLocation(lngLat, zoom);
    }

    if (map.getSource('AchievementManagerRaster')) {
      map.getSource('AchievementManagerRaster').setData(taskLayerGeoJson);
    } else {
      // 聚合效果
      map.addSource('AchievementManagerRaster', {
        type: 'geojson',
        data: taskLayerGeoJson,
        cluster: true,
        clusterMaxZoom: 14,
        clusterRadius: 50,
      });
      map.addLayer({
        id: 'clusters',
        type: 'circle',
        source: 'AchievementManagerRaster',
        filter: ['all', ['has', 'point_count'], ['!=', 'point_count', 1]], // 只显示聚合点数量大于1的情况
        paint: {
          'circle-color': [
            'step',
            ['get', 'point_count'],
            '#51bbd6',
            100,
            '#f1f075',
            750,
            '#f28cb1',
          ],
          'circle-radius': ['step', ['get', 'point_count'], 20, 100, 30, 750, 40],
        },
      });
      map.addLayer({
        id: 'cluster-count',
        type: 'symbol',
        source: 'AchievementManagerRaster',
        filter: ['all', ['has', 'point_count'], ['!=', 'point_count', 1]], // 只显示聚合点数量大于1的情况
        layout: {
          '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: 'AchievementManagerRaster' ,
      //   filter: ['any', ['!', ['has', 'point_count']], ['==', 'point_count', 1]],
      //   paint: {
      //     'circle-color': '#11b4da',
      //     'circle-radius': 4,
      //     'circle-stroke-width': 2,
      //     'circle-stroke-color': '#fff',
      //   },
      // });
      // 无人机图标
      map.loadImage('/videosupervision/uav-1.png', function (error, image) {
        if (error) throw error;
        if (!map.hasImage('taskIcon')) {
          map.addImage('taskIcon', image);
        }
      });
      map.addLayer({
        id: 'AchievementManagerRaster',
        type: 'symbol',
        source: 'AchievementManagerRaster',
        layout: {
          'icon-image': 'taskIcon',
          'icon-size': 0.8,
          // 'text-field': ['get', 'taskName'],
          'text-size': 10,
          'text-font': ['Open Sans Semibold', 'Arial Unicode MS Bold'],
          'text-offset': [0, 1.8],
          'text-anchor': 'top',
          'icon-allow-overlap': false,
          'text-allow-overlap': false,
          visibility: 'visible',
        },
        paint: {
          'text-color': '#fff',
          'text-halo-color': '#000',
          'text-halo-width': 1,
        },
      });
      map.on('click', 'AchievementManagerRaster', (e) => {
        console.log(e);
        // 显示弹窗
        if (e.features.length > 0) {
          // 获取第一个（也是唯一的）被点击的特征
          const feature = e.features[0];
          // 从特征的属性中获取 'path' 值
          // const path = feature.properties.path;
          // console.log(400, feature.properties);
          emits('handleOpenImage', feature.properties);
        }
      });

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

  // 清除图层
  function clearTaskLayer(layerName) {
    // 检查图层是否存在
    if (map.getLayer(layerName)) {
      // 删除图层
      map.removeLayer(layerName);
      if (layerName == 'AchievementManagerRaster') {
        if (map.getLayer('clusters')) {
          map.removeLayer('clusters');
        }
        if (map.getLayer('cluster-count')) {
          map.removeLayer('cluster-count');
        }
        // if (map.getLayer('unclustered-point')) {
        //   map.removeLayer('unclustered-point');
        // }
      }
      if (map.getLayer(layerName + '-text')) {
        map.removeLayer(layerName + '-text');
      }
    }
    // 检查数据源是否存在
    if (map.getSource(layerName)) {
      // 删除数据源
      map.removeSource(layerName);
    }
  }

  // 重新计算地图大小
  function resize() {
    map.resize();
  }

  // 动态调整透明度
  function changeFillLayerOpacity(layerType, filter, newOpacity) {
    if (layerType == 'GeoserverManagementRaster') {
      filter?.forEach((tuceng) => {
        map.setPaintProperty(tuceng.dataTable, 'fill-opacity', parseFloat(newOpacity));
      });
    }
    if (layerType == 'GeoTiffManagerRaster') {
      filter?.forEach((tuceng) => {
        map.setPaintProperty(tuceng.layerName, 'raster-opacity', parseFloat(newOpacity));
      });
    }
  }

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

    // handlerLocation([118.30207505530701, 35.30123435040745], 7.848587811931849);
    map.on('load', () => {
      // 地图跳转
      // map.flyTo({
      //   center: [118.30207505530701, 35.30123435040745],
      //   zoom: 7.848587811931849,
      // });

      // 县区边界
      handlerDealStreet(null);
      handlerDealCountry(null);
    });
  });

  // 抛出函数
  defineExpose({
    GeoserverManagementRaster,
    GeoTiffManagerRaster,
    AchievementManagerRaster,
    resize,
    clearTaskLayer,
    handlerLocation,
    changeFillLayerOpacity,
    handlerDealCountry,
    handlerDealStreet,
  });
</script>
<style type="less" scoped>
  .map-container {
    width: 100%;
    height: 100%;
    position: relative;
  }
  ::v-deep .mapboxgl-ctrl-logo {
    display: none !important;
  }
</style>
