<template>
  <div :id="mapId" class="map">
    <div class="mapInfo">
      <span> {{ props.nowPreviewRecord.lat }}°N</span>
      <span> {{ props.nowPreviewRecord.lng }}°E</span>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { defineProps, ref, onMounted, onUnmounted, defineEmits, watch } from 'vue';
  import { v4 as uuidv4 } from 'uuid';
  import mapboxgl, { Map } from 'mapbox-gl';
  import { MapboxConfig, MapboxDefaultStyle } from '@/components/MapboxMaps/src/config';
  import axios from 'axios';
  import {
    ExpandOutlined,
    CompressOutlined,
    PlusOutlined,
    MinusOutlined,
    HeatMapOutlined,
  } from '@ant-design/icons-vue';
  import { cloneDeep } from 'lodash-es';

  const props = defineProps(['nowPreviewRecord', 'previewRecordList', 'hideOrShowTextboxFlag']);
  const emit = defineEmits(['chooseNowPreviewRecord', 'reloadTable']);

  const mapId = `modal-map-${uuidv4()}`;
  const networkType = ref('WAN');
  let map: Map;

  const initMap = () => {
    let mapDataSources: any = {
      'raster-tiles': {
        type: 'raster',
        tiles: [
          `http://t0.tianditu.gov.cn/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=${MapboxConfig.TDT_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=${MapboxConfig.TDT_TOKEN}`,
        ],
        tileSize: 256,
      },
    };
    let mapDataLayers: any = [
      {
        id: 'tdt-vec-tiles',
        type: 'raster',
        source: 'raster-tiles-font',
      },
      {
        id: 'tdt-img-tiles',
        type: 'raster',
        source: 'raster-tiles',
      },
    ];
    map = new mapboxgl.Map({
      container: mapId,
      language: 'zh-cmn',
      projection: 'equirectangular', // wgs84参考系
      style: {
        glyphs: 'mapbox://fonts/mapbox/{fontstack}/{range}.pbf',
        version: 8,
        sources: mapDataSources,
        layers: mapDataLayers,
      },
      maxZoom: 22,
      minZoom: 8,
      pitch: 0,
      zoom: 14,
      center: [parseFloat(props.nowPreviewRecord.lng), parseFloat(props.nowPreviewRecord.lat)],
    });
    setImage();
  };

  watch(
    () => props.hideOrShowTextboxFlag,
    (newValue) => {
      if (newValue) {
        props.previewRecordList.forEach((item) => {
          if (!map.getLayer(item.id)) {
            const coordinates = [parseFloat(item.lng), parseFloat(item.lat)];
            // 图片
            map.addLayer({
              id: item.id,
              type: 'symbol',
              source: {
                type: 'geojson',
                data: {
                  type: 'FeatureCollection',
                  features: [
                    {
                      type: 'Feature',
                      geometry: {
                        type: 'Point',
                        coordinates: coordinates,
                      },
                    },
                  ],
                },
              },
              layout: {
                'icon-image': item.id,
                'icon-size': 40 / item.width,
                // 关键配置：始终显示
                'icon-allow-overlap': true, // 允许图标重叠时也显示
                'icon-ignore-placement': true, // 忽略自动布局规则，强制显示
                visibility: 'visible', // 显式设置为可见
              },
            });
          }
        });
      } else {
        let filters = cloneDeep(props.previewRecordList).filter(
          (item) => item.id != props.nowPreviewRecord.id,
        );
        filters.forEach((fl) => {
          if (map.getLayer(fl.id)) {
            map.removeLayer(fl.id);
          }
          if (map.getSource(fl.id)) {
            map.removeSource(fl.id);
          }
        });
      }
    },
  );

  function setImage() {
    props.previewRecordList.forEach((item) => {
      map.on('style.load', () => {
        map.loadImage(item.url, (error, image) => {
          if (error) {
            console.error('加载图片失败:', error.message);
            return;
          }
          if (!map.hasImage(item.id)) {
            map.addImage(item.id, image);
          }
          const coordinates = [parseFloat(item.lng), parseFloat(item.lat)];
          if (!map.getLayer(item.id)) {
            // 图片
            map.addLayer({
              id: item.id,
              type: 'symbol',
              source: {
                type: 'geojson',
                data: {
                  type: 'FeatureCollection',
                  features: [
                    {
                      type: 'Feature',
                      geometry: {
                        type: 'Point',
                        coordinates: coordinates,
                      },
                    },
                  ],
                },
              },
              layout: {
                'icon-image': item.id,
                'icon-size': 40 / item.width,
                // 关键配置：始终显示
                'icon-allow-overlap': true, // 允许图标重叠时也显示
                'icon-ignore-placement': true, // 忽略自动布局规则，强制显示
                visibility: 'visible', // 显式设置为可见
              },
            });
            map.on('click', item.id, function (e) {
              clickHandler(item);
            });
          }
        });
      });
    });
  }

  onMounted(() => {
    mapboxgl.accessToken = MapboxConfig.ACCESS_TOKEN;
    // 获取网络环境后加载地图
    initMap();
  });

  onUnmounted(() => {
    map && map.remove();
    props.previewRecordList.forEach((item) => {
      map.off('click', item.id, function (e) {
        clickHandler(item);
      });
    });
  });

  // 点击事件
  function clickHandler(item) {
    emit('chooseNowPreviewRecord', item);
  }
</script>

<style lang="less" scoped>
  .map {
    position: relative;
    width: 100%;
    height: 100%;
  }

  .mapInfo {
    position: absolute;
    width: 100%;
    height: 30px;
    bottom: 0px;
    left: 0px;
    background: #3d3f3aaa;
    z-index: 1000;
    display: flex;
    justify-content: flex-start;

    span {
      height: 100%;
      width: 30%;
      color: #ffffff;
      display: flex;
      align-items: center;
      justify-content: flex-start;

      font-size: 15px;
      margin-left: 10px;
    }
  }

  ::v-deep .mapboxgl-ctrl {
    display: none !important;
  }
</style>
