<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, watch } from "vue";
import { useMainStore } from "@/stores/store";
import axios from "axios";

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

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

  store.$subscribe((mutation, state) => {
    console.log("state >>>", state);
    console.log("state mapLocation >>>", state.mapLocation.lat);

    if (state.mapLocation.lat) {
      const newCenter = {
        lat: state.mapLocation.lat,
        lng: state.mapLocation.lng,
      };

      // 將地圖中心設為指定的經緯度
      map.setView([newCenter.lat, newCenter.lng], map.getZoom());
    }
  });

  // 監聽 Pinia 存儲中的值變化
  store.$subscribe((item) => {
    console.log("item", item);
    console.log("item.events", item.events);
    // if (item.events?.key === "lng") {
    //   console.log("經緯度", item.events.target);

    //   const newCenter = {
    //     lat: item.events.target.lat,
    //     lng: item.events.target.lng,
    //   };

    //   console.log("newCenter", newCenter);

    //   // 將地圖中心設為指定的經緯度
    //   map.setView([newCenter.lat, newCenter.lng], map.getZoom());
    // }
  });

  (async function getData() {
    try {
      const response = await axios.get(`${store.apiUrl}/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, 118),
  L.latLng(26.5, 124)
  );
  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>
