<script setup>
import { useRoute } from "vue-router";
import EffectScatter from "@/components/chart/EffectScatter.vue";
import DashboardEffectScatterModal from "./DashboardEffectScatterModal.vue";
import useSearchParam from "@/hooks/useSearchParam";
import { computed, inject, ref, watch } from "vue";
import { useI18n } from "vue-i18n";

const { t } = useI18n();
const route = useRoute();
const { searchParams, changeParams } = useSearchParam();
const FILE_BASEURL = import.meta.env.VITE_FILE_API_BASEURL;

const props = defineProps({
  data: {
    type: Object,
  },
});

const asset_floor_chart = ref(null);
const currentFloorId = ref(null);
const selectedDevice = ref(null);

const defaultOption = (map, data = []) => {
  return {
    animation: false,
    geo: {
      map,
      roam: true, // 允許縮放和平移
      layoutSize: window.innerWidth <= 768 ? "80%" : "55%",
      layoutCenter: ["50%", "40%"],
      scaleLimit: { min: 1, max: 2 },
    },
    series: [
      // 背景圓形
      {
        type: "scatter",
        coordinateSystem: "geo",
        geoIndex: 0,
        symbolSize: (value) => value[2]?.bgSize || 50,
        symbol: "range",
        itemStyle: {
          color: (params) => params.data[2]?.bgColor || "rgba(0,0,0,0.8)",
        },
        data,
        z: 1,
      },
      {
        type: "scatter",
        coordinateSystem: "geo",
        geoIndex: 0,
        symbolSize: 30,
        itemStyle: {
          color: "rgba(225,225,225,0.8)",
        },
        symbol: (value, params) => {
          // 若有 icon 屬性就用 image，否則用圓點
          return params.data[2]?.icon
            ? `image://${params.data[2].icon}`
            : "roundRect";
        },
        data,
        label: {
          show: true,
          position: "bottom",
          formatter: (params) => params.data[2]?.full_name || "",
          color: "#333",
          fontSize: 14,
          backgroundColor: "rgba(255,255,255)",
          padding: [4, 4],
          borderRadius: 3,
        },
        z: 2,
      },
    ],
  };
};

const currentIconData = computed(() => {
  const data = props.data?.[searchParams.value.floor_id] || [];
  return data;
});

// 處理圖表項目點擊事件
const handleItemClick = (params) => {
  if (params.data && params.data[2]) {
    selectedDevice.value = params.data[2];
  }
};

watch(
  [searchParams, () => asset_floor_chart.value, () => props.data],
  ([newValue, newChart, newData], [oldValue]) => {
    console.groupCollapsed("[FloorMap] watch fired");
    console.log("floor_id =", newValue.floor_id);
    console.log("chart ready =", !!newChart);
    console.log("data keys =", Object.keys(newData || {}).length);
    console.groupEnd();
    const floorId = newValue.floor_id;
    const chartReady = !!newChart;
    // (1) 首次/樓層切換：不等 data，先載 SVG
    if (floorId && chartReady && currentFloorId.value !== floorId) {
      console.log("[FloorMap] load SVG for floor:", floorId);
      currentFloorId.value = floorId;
      newChart.updateSvg(
        {
          full_name: floorId,
          path: `${FILE_BASEURL}/upload/floor_map/${floorId}.svg`,
        },
        defaultOption(floorId, []) // 先不帶點位
      );
      setTimeout(() => {
        if (newChart.chart) {
          newChart.chart.off("click");
          newChart.chart.on("click", handleItemClick);
        }
      }, 100);
    }

    // (2) 資料到齊後，再補點位（不重載 SVG）
    if (
      floorId &&
      chartReady &&
      Object.keys(newData || {}).length > 0 &&
      newChart.chart
    ) {
      console.log("[FloorMap] update series only for floor:", floorId);
      newChart.chart.setOption(
        { series: defaultOption(floorId, currentIconData.value).series },
        false,
        true
      );
    }
  },
  {
    immediate: true,
    deep: true,
  }
);
</script>

<template>
  <DashboardEffectScatterModal :data="selectedDevice" />
  <EffectScatter
    id="system_floor_chart"
    ref="asset_floor_chart"
    class="bg-slate-300 absolute top-0 left-0 min-h-full z-0"
  />
</template>

<style lang="scss" scoped></style>
