<script setup>
import * as echarts from "echarts";
import { onMounted, ref, markRaw } from "vue";
import axios from "axios";

const props = defineProps({
  option: Object,
  className: String,
  id: String,
  svg: Object,
  getCoordinate: {
    type: Function,
    default: null,
  },
});

let chart = ref(null);
let dom = ref(null);
let currentClickPosition = ref([]);
let currentMapName = ref(null);

async function updateSvg(svg, option) {
  if (!chart.value && dom.value && svg) {
    init();
  }
  
  // 檢查是否需要載入新的 SVG 地圖
  const needNewSvg = currentMapName.value !== svg.full_name;
  
  if (needNewSvg) {
    // 載入新的 SVG 地圖
    console.log("Loading new SVG map:", svg.full_name);
    currentMapName.value = svg.full_name;
    
    try {
      const { data } = await axios.get(svg.path);
      echarts.registerMap(svg.full_name, { svg: data });
      chart.value.setOption(option);
      setupClickHandler(option);
    } catch (error) {
      console.error("Failed to load SVG:", error);
    }
  } else if (chart.value) {
    // 只更新數據，不重新載入 SVG
    console.log("Updating chart data only");
    chart.value.setOption({
      series: option.series
    }, false, true);
  }
}

function setupClickHandler(option) {
  if (props.getCoordinate && chart.value) {
    chart.value.getZr().on("click", function (params) {
      var pixelPoint = [params.offsetX, params.offsetY];
      var dataPoint = chart.value.convertFromPixel(
        { geoIndex: 0 },
        pixelPoint
      );
      currentClickPosition.value = dataPoint;
      props.getCoordinate(dataPoint);
      const updatedData = option.series[1].data
        .filter(
          (point) => !(point.itemStyle && point.itemStyle.color === "#0000FF")
        )
        .concat({
          value: dataPoint, // 當前座標值
          itemStyle: { color: "#0000FF" }, // 設為藍色
        });
      chart.value.setOption({
        series: [{}, {
          data: updatedData,
        }]
      });
    });
  }
}

function clear() {
  chart.value.clear();
}

function init() {
  const curChart = echarts.init(dom.value);
  chart.value = markRaw(curChart);
}

onMounted(() => {
  if (!chart.value && dom.value && props.svg) {
    init();
  }
});

defineExpose({
  chart,
  currentClickPosition,
  updateSvg,
});
</script>
<template>
  <div :id="id" class="min-h-full max-h-fit w-full" ref="dom"></div>
</template>

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