<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: Function,
});

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

async function updateSvg(svg, option) {
  if (!chart.value && dom.value && svg) {
    init();
  }
  axios.get(svg.path).then(({ data }) => {
    echarts.registerMap(svg.full_name, { svg: data });
    chart.value.setOption(option);
    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);
      chart.value.setOption({
        series: {
          data: [dataPoint],
        },
      });
      console.log(chart.value.getOption());
    });
  });
  console.log("updateSvg", svg.path);
  // fetch(svg.path)
  //   .then((res) => console.log(res))
  //   .then(function (svg) {
  //     console.log(svg);
  //     // echarts.registerMap(svg.full_name, { svg });
  //     // chart.setOption(option);
  //     // chart.getZr().on("click", function (params) {
  //     //   var pixelPoint = [params.offsetX, params.offsetY];
  //     //   var dataPoint = curChart.convertFromPixel({ geoIndex: 0 }, pixelPoint);
  //     //   console.log(dataPoint);
  //     //   currentClickPosition.value = dataPoint;
  //     // });
  //   });
}

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-[500px] max-h-fit w-full" ref="dom"></div>
</template>

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