<script setup>
import L from "leaflet";
import "leaflet.markercluster";
import "leaflet/dist/leaflet.css";
import "leaflet.markercluster/dist/MarkerCluster.css";
import "leaflet.markercluster/dist/MarkerCluster.Default.css";
import { ref, reactive, onMounted, getCurrentInstance } from "vue";
import axios from "axios";
// import mapData from "@/assets/mapData.json";

const mapContainer = ref(null);
const location_id = ref("");
const { proxy } = getCurrentInstance();

onMounted(() => {
  let mapData = reactive({
    data: [],
  });

  (async function getData() {
    try {
      const response = await axios.get("https://cmm.ai:8088/api/get_school");
      mapData.data = response.data.schools;
      console.log("data", mapData.data);
      console.log("response.data", response.data);

      mapData.data.forEach((item) => {
        let customIcon = L.icon({
          iconUrl: getImageUrl('icon_house07.png'),
          iconSize: [30, 50],
        });

        let marker = L.marker(new L.LatLng(item.Lat, item.Lng), {
          icon: customIcon,
        }).bindPopup(`<p>${item.location_name}</p>`);

        // let marker = L.marker(new L.LatLng(item.Lat, item.Lng)).bindPopup(
        //   `<p>${item.location_name}</p>`
        // );

        marker.on("mouseover", function () {
          this.openPopup();
        });

        marker.on("mouseout", function () {
          this.closePopup();
        });

        marker.on("click", function () {
          location_id.value = item.location_id;
          proxy.$emit("locationId", location_id.value);
        });

        markers.addLayer(marker);
      });
    } catch (error) {
      console.error(error);
    }
  })();

  // 創建地圖
  const map = L.map(mapContainer.value, {
    center: [23.611, 120.768],
    zoom: 8,
  });

  // 加入圖層
  L.tileLayer(
    "https://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Base/MapServer/tile/{z}/{y}/{x}"
  ).addTo(map);

  // const popup = L.popup();
  const markers = L.markerClusterGroup();

  // 限制在台灣範圍
  const taiwanBounds = L.latLngBounds(
    L.latLng(20.68, 119.16),
    L.latLng(25.56, 122.48)
  );
  map.setMaxBounds(taiwanBounds);

  const getImageUrl = (name) => {
    return new URL(`/src/assets/img/map-icon/${name}`, import.meta.url).href;
  };

  map.setMaxZoom(16); // 最大縮放級別
  map.setMinZoom(8); // 最小縮放級別

  map.addLayer(markers);
});
</script>

<template>
  <div id="map" class="mapContainer" ref="mapContainer"></div>
</template>

<style>
#map {
  width: 100%;
  height: 100%;
}
</style>
