<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");
    setTimeout(() => {
      let lastIndex = 0; //最后一次选中的dataIndex
      //默认显示的内容dataIndex是第一个0
      ect.dispatchAction({
        type: "highlight",
        seriesIndex: 0,
        dataIndex: 0
      });

      ect.on("mouseover", v => {
        //清空第一次选中
        // console.log('鼠标移上去的index：')
        // console.log(v.dataIndex)
        if (v.componentType === 'series' &&lastIndex !== v.dataIndex) {
          ect.dispatchAction({
            type: "highlight",
            seriesIndex: 0,
            dataIndex: v.dataIndex
          });
          ect.dispatchAction({
            type: "downplay",
            seriesIndex: 0,
            dataIndex: lastIndex
          });
          lastIndex = v.dataIndex;
        }
      });
    }, 500);
  },
  { immediate: true, deep: true }
);
</script>
