<template>
  <div class="absolute inset-0" ref="elm"></div>
</template>

<script lang="ts" setup>
import * as echarts from "echarts";
import "echarts/map/js/china";
// import "echarts/map/json/province/chongqing.json";

import {
  defineProps,
  ref,
  watch,
  nextTick,
  onBeforeUnmount,
  onMounted,
} from "vue";

interface Ref<T> {
  value: T;
}

const props = defineProps({
  options: {
    type: Object,
    required: true,
  },
  default: {
    type: Number,
  },
});

const emits = defineEmits();

const elm = ref(null) as Ref<any>;

let ect: any = null;

const resize = () => ect && ect.resize();

onBeforeUnmount(() => {
  window.removeEventListener("resize", resize);
});

let selected: any = null;

watch(
  () => props.options,
  async () => {
    await nextTick();
    if (!ect && elm.value) {
      ect = echarts.init((elm as Ref<any>).value);
      window.addEventListener("resize", resize);
      ect.on("click", (e: any) => emits("ectCheck", e));
      ect.on("legendselectchanged", (e: any) => emits("ectLegendChange", e));
    }
    ect && ect.setOption(props.options, true);

    // ect && ect.off("mouseover");
    // ect && ect.off("mouseout");

    if (typeof props.default === "number") {
      let index = props.default;
      if (selected) {
        ect.dispatchAction({
          type: "downplay",
          seriesIndex: 0,
          dataIndex: selected,
        });
        selected = null;
      }
      ect.dispatchAction({
        type: "highlight",
        seriesIndex: 0,
        dataIndex: index,
      });

      ect.on("mouseover", function (e) {
        // console.log("mouserover", e.dataIndex, index, props.default);
        // console.log("selected", selected);
        // if (e.dataIndex != index) {
        //   ect.dispatchAction({
        //     type: "downplay",
        //     seriesIndex: 0,
        //     dataIndex: index,
        //   });
        // }
          if (e.componentType === 'series') {
            ect.dispatchAction({
              type: "downplay",
              seriesIndex: 0,
              dataIndex: index,
            });
            
            ect.dispatchAction({
              type: "highlight",
              seriesIndex: 0,
              dataIndex: e.dataIndex,
            });
            
            index = e.dataIndex;
            selected = e.dataIndex;
          }
      });
      ect.on("mouseout", function (e) {
        // index = e.dataIndex;
        // selected = e.dataIndex;
        // ect.dispatchAction({
        //   type: "highlight",
        //   seriesIndex: 0,
        //   dataIndex: e.dataIndex,
        // });
      });
    }
  },
  { immediate: true, deep: true }
);
</script>
