<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 } 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(['handleOpen']);

  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: 8,
      zoom: 14,
      pitch: 0,
      center: [117.984425, 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 = '';
    let center = { lng: 118.30207505530701, lat: 35.30123435040745 };
    let zoom = 7.848587811931849;
    handlerLocation([center['lng'], center['lat']], zoom);
    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, // 设置线的宽度
        },
      });
    }
    map.moveLayer(layerName, '');
  };

  // 获取乡镇数据
  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': 12,
          'text-anchor': 'center',
        },
        paint: {
          'text-color': '#041B36',
          'text-halo-color': '#fff',
          'text-halo-width': 2,
        },
      });
      map.moveLayer('countyLayer');
      map.moveLayer(layerName, '');
    }
  };

  // 图层管理-图层
  function GeoserverManagementRaster(chooseRow, lngLat, zoom) {
    // 县区边界
    handlerDealStreet('GeoserverManagementRaster');
    handlerDealCountry('GeoserverManagementRaster');
    handlerLocation(lngLat, zoom);

    let format =
      chooseRow.dataType == '点'
        ? '&format=application/openlayers'
        : '&format=image/png&TRANSPARENT=TRUE';

    map.addSource('wmsSource', {
      type: 'raster',
      tiles: [
        'http://192.168.10.131:8080/geoserver/my_workspace/wms?service=WMS&version=1.1.0&request=GetMap&layers=my_workspace:' +
          chooseRow.dataTable +
          '&styles=&bbox={bbox-epsg-3857}&width=256&height=256&srs=' +
          chooseRow.spatialRef +
          format,
        // 'http://192.168.10.131:8080/geoserver/my_workspace/wms?service=WMS&version=1.1.0&request=GetMap&layers=my_workspace:parse_shpinfo_text3&styles=&bbox=118.32113719388846%2C35.64528587987562%2C118.89333296872105%2C36.17725393199594&width=256&height=256&srs=EPSG:4326&format=image/png&TRANSPARENT=TRUE&exceptions=application%2Fvnd.ogc.se_inimage',
        // 'http://175.27.168.120:8080/geoserver/yinanxian/wms?SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&FORMAT=image%2Fjpeg&TRANSPARENT=true&LAYERS=yinanxian%3Ayingxiang_01&exceptions=application%2Fvnd.ogc.se_inimage&SRS=EPSG%3A4548&STYLES=&WIDTH=529&HEIGHT=769&BBOX=607366.3276808303%2C3919435.438766631%2C612405.5241015075%2C3926765.179014889',
      ],
      tileSize: 256,
    });
    map.addLayer({
      id: 'GeoserverManagementRaster',
      type: 'raster',
      source: 'wmsSource',
      layout: {
        visibility: 'visible',
      },
    });
  }

  // 影像管理-图层
  function GeoTiffManagerRaster(chooseRow, lngLat, zoom) {
    // 县区边界
    handlerDealStreet('GeoTiffManagerRaster');
    handlerDealCountry('GeoTiffManagerRaster');
    handlerLocation(lngLat, zoom);
    map.addSource('wmsSource', {
      type: 'raster',
      tiles: [chooseRow.accessUrl],
      tileSize: 256,
    });
    map.addLayer({
      id: 'GeoTiffManagerRaster',
      type: 'raster',
      source: 'wmsSource',
      layout: {
        visibility: 'visible',
      },
    });
  }

  // 航飞图片-图层
  function AchievementManageRaster(taskLayerGeoJson, lngLat, zoom) {
    // 清除图层
    clearTaskLayer('AchievementManageRaster');
    // 县区边界
    handlerDealStreet('AchievementManageRaster');
    handlerDealCountry('AchievementManageRaster');
    handlerLocation(lngLat, zoom);
    map.loadImage('/map/AchievementManage.png', function (error, image) {
      if (error) throw error;
      if (!map.hasImage('taskIcon')) {
        map.addImage('taskIcon', image);
      }
    });
    map.addSource('wmsSource', {
      type: 'geojson',
      data: taskLayerGeoJson,
    });
    map.addLayer({
      id: 'AchievementManageRaster',
      type: 'symbol',
      source: 'wmsSource',
      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': true,
        'text-allow-overlap': true,
        visibility: 'visible',
      },
      paint: {
        'text-color': '#fff',
        'text-halo-color': '#000',
        'text-halo-width': 1,
      },
    });
    map.on('click', 'AchievementManageRaster', (e) => {
      // 显示弹窗
      if (e.features.length > 0) {
        // 获取第一个（也是唯一的）被点击的特征
        const feature = e.features[0];
        // 从特征的属性中获取 'path' 值
        const path = feature.properties.path;
        emits('handleOpen', path);
      } else {
        console.log('No feature was clicked.');
      }
    });
  }

  // 清除图层
  function clearTaskLayer(layerName) {
    // 检查图层是否存在
    if (map.getLayer(layerName)) {
      // 删除图层
      map.removeLayer(layerName);
    }
    // 检查数据源是否存在
    if (map.getSource('wmsSource')) {
      // 删除数据源
      map.removeSource('wmsSource');
    }
  }

  onMounted(() => {
    mapboxgl.accessToken = MAPBOX_TOKEN;
    map = initMap();
    // map.on('load', () => {
    //   map.flyTo({
    //     center: [118.30207505530701, 35.30123435040745],
    //     zoom: 7.848587811931849,
    //   });
    // });
  });

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