<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 { useMainStore } from "@/stores/store";

const store = useMainStore();
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: store.getImageUrl("map-icon/icon_house06.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);

  // 取得使用者的當前位置座標
  map.locate({ setView: true, maxZoom: 16 });
  console.log(
    "使用者的當前位置座標",
    map.locate({ setView: true, maxZoom: 16 })
  );

  let customIcon = L.icon({
    iconUrl: store.getImageUrl("map-icon/icon_house05.png"),
    iconSize: [30, 50],
  });

  // 當取得位置成功時，將地圖中心設定為使用者位置
  function onLocationFound(e) {
    L.marker(e.latlng, { icon: customIcon })
      .addTo(map)
      .bindPopup("您的位置")
      .openPopup();
  }

  // 當取得位置失敗時，顯示錯誤提示
  function onLocationError(e) {
    alert("無法取得位置或拒絕提供位置訪問權限。");
  }

  map.on("locationfound", onLocationFound);
  map.on("locationerror", onLocationError);

  // 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);
  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>
