<template>
  <div ref="mapContainer" class="map-container"></div>
</template>

<script setup>
  import { ref, onMounted, onUnmounted } from 'vue';
  // 引入 Leaflet
  import L from 'leaflet';
  import 'leaflet/dist/leaflet.css';
  // Ant Design Vue 图标

  // --- 1. 组件引用和状态定义 ---
  const mapContainer = ref(null);
  let map = null; // Leaflet 地图实例

  // --- 2. 瓦片图层配置 ---
  const tileLayers = {
    custom: {
      name: '基准瓦片',
      layer: null,
      url: 'https://shaanxizhxx.chinamine-safety.gov.cn/zh1/8/33/17.png',
      options: {
        maxZoom: 18,
        attribution: '',
        // crossOrigin: true,
      },
    },
    satellite: {
      name: '卫星图',
      layer: null,
      url: 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
      options: {
        maxZoom: 18,
        attribution: '© Esri',
      },
    },
  };

  // --- 3. 地图初始化 ---
  onMounted(() => {
    initMap();
  });

  onUnmounted(() => {
    if (map) {
      map.remove();
    }
  });

  // 初始化地图
  function initMap() {
    if (!mapContainer.value) return;

    // 创建地图实例，设置太原市中心和初始缩放级别
    map = L.map(mapContainer.value, {
      center: [35.841, 108.94], // 西安市中心坐标 [纬度, 经度]
      zoom: 7, // 初始缩放级别，适合城市级别查看
      zoomControl: false, // 显示缩放控件
      attributionControl: false, // 显示属性控件
    });

    // 初始化所有瓦片图层
    initTileLayers();

    // 默认显示自定义底图
    tileLayers.custom.layer.addTo(map);
    // tileLayers.satellite.layer.addTo(map);

    initGeoJSON();
  }

  // 初始化瓦片图层
  function initTileLayers() {
    Object.keys(tileLayers).forEach((key) => {
      const config = tileLayers[key];
      config.layer = L.tileLayer(config.url, config.options);
    });
  }

  async function initGeoJSON() {
    const response = await fetch('/js/shanxi.geo.json');
    const ShanXiGeoJSON = await response.json();
    L.geoJSON(ShanXiGeoJSON, {
      style: function () {
        return { color: '#ff9100' };
      },
    }).addTo(map);
  }
</script>

<style lang="less" scoped>
  .map-container {
    flex: 1;
    height: 100%;
    width: 100%;
    position: fixed;
    top: 0;
    left: 0;
    z-index: @simple-map-z-index;
  }
</style>
