<!-- 地图组件 -->
<template>
  <div style="position: relative">
    <div class="bars_w" ref="chartMap" id="chartMap"></div>
  </div>
</template>

<script setup lang="ts">
import { onBeforeUnmount, ref, watch, onMounted, defineEmits } from "vue";
import * as echarts from "echarts";
import "echarts-gl";
import "echarts-liquidfill";
import "echarts/lib/component/dataZoom";

const props = defineProps(["options"]);
const myCharts = ref();
const showCircle = ref(false);

const fetchConfig = async (name: string) => {
  const res = await import(`./mapJson/${name}.json`);
  return res.default;
  // GetEchar(res.default)
};
// fetchConfig()

const emit = defineEmits(["getRegionByRegion", "eliminate", "clickMap"]);
onMounted(() => {});

const GetEchar = async (name: string) => {
  let chartDom = document.getElementById("chartMap");
  myCharts.value?.dispose();
  myCharts.value = echarts.init(chartDom);

  echarts.registerMap(name, await fetchConfig(name)); //注册可用的地图
  let option = {
    title: {
      left: "center",
      top: "3%",
      ...props.options.title,
    },
    tooltip: {
      trigger: "item",
      axisPointer: {
        type: "shadow",
        label: {
          color: "#fff",
          fontSize: 16,
        },
      },
      textStyle: {
        color: "#fff",
        fontStyle: "normal",
        opacity: 0.35,
        fontSize: 14,
      },
      backgroundColor: "rgba(0,0,0,0.55)",
      ...(props.options.tooltip || null),
    },

    legend: {
      orient: "vertical",
      left: 25,
      bottom: 40,
      itemWidth: 16,
      itemHeight: 16,

      ...(props.options.legend || null),
    },

    color: [
      ...(props.options.color || ""),
      "#07CCCA ",
      "#00BFF5",
      "#FFBF00",
      "#77DA63",
      "#D5FF6B",
      "#Ff6600",
      "#FF9100",
      "#5B6E96",
      "#66FFCC",
      "#B3B3B3",
    ],

    geo: {
      map: name,
      zoom: 1.3,
      // top: 10,
      //    bottom: 0,
      roam: true,
      rotation: 90,

      label: {
        normal: {
          show: true,
          fontSize: "12",
          color: "#fff",
        },
      },

      itemStyle: {
        normal: {
          color: "#0a73ff80", //地图背景色
          borderColor: "#fff",
          borderWidth: 1,
          areaColor: {
            type: "radial",
            x: 0.5,
            y: 0.5,
            r: 0.8,
            colorStops: [
              {
                offset: 0,
                color: "#0a73ff80", // 0% 处的颜色
              },
              {
                offset: 1,
                color: "#0a73ff80", // 100% 处的颜色
              },
            ],
            globalCoord: false, // 缺省为 false
          },
          shadowColor: "#0a73ff80",

          shadowOffsetX: -2,
          shadowOffsetY: 2,
          shadowBlur: 10,
        },
        emphasis: {
          areaColor: "#0a73ff70",
          shadowOffsetX: 0,
          shadowOffsetY: 0,
          borderWidth: 0,
          color: "#fff",
        },
      },
    },

    ...props.options.options,
  };
  if (props.options.visualMap) {
    option.visualMap = props.options.visualMap;
  }
  if (props.options.geo3D) {
    option.geo = null;
    option.geo3D = {
      map: name,
      ...(props.options.geo3D || null),
    };
  }
  myCharts.value.setOption(option);
  window.addEventListener("resize", resizeHandler);
  const flag1 = ref(true);
  // 点击事件
  myCharts.value.off("click");
  myCharts.value.on("click", (e: any) => {
    setIcon('')
    if (props.options.geo3D) {
      // emit('clickMap', e)
      if (flag1.value) {
        flag1.value = false;
        setTimeout(() => {
          emit("clickMap", e);
          flag1.value = true;
        }, 100);
      }
    } else {
      // if (name == dictData.state.area?.[0].name  && e.componentIndex == 0) {
      if (name == "中国" && e.componentIndex == 0) {
        // console.log('🚀 ~ file: MyEchartMap.vue:156 ~ myCharts.value.on ~  MapReturn(e.name):', MapReturn(e.name))
      }
    }
  });
  myCharts.value.on("datarangeselected", function (params: any) {
    // 手动调用restore方法恢复地图的默认颜色映射
    myCharts.value.dispatchAction({
      type: "restore",
    });
  });
};
// 记录上次操作的点信息
let lastModifiedPoint = null; // 格式: {name, oldColor, oldSize}

/**
 * 修改地图上指定名称点的样式并显示提示框
 * @param {string} targetName - 要修改的点的name属性值
 * @param {string} newColor - 新的颜色值（如"#ff0000"）
 * @param {number} newSize - 新的图标大小（如20）
 */
function setIcon(targetName) {
  // 获取当前图表实例（替换为你的地图容器ID）
  const chartInstance = echarts.getInstanceByDom(
    document.getElementById("chartMap")
  );
  if (!chartInstance) return;

  // 获取当前配置项
  const option = chartInstance.getOption();
  if (!option || !option.series ) return;

  // 找到对应的series（你的场景中是第一个series）
  const targetSeries = option.series[0];
  let pointIndex = -1;
  let currentPoint = null;

  // 1. 先恢复上次修改的点的样式
  if (lastModifiedPoint) {
    targetSeries.data.forEach((item) => {
      if (item.name === lastModifiedPoint.name) {
        // 恢复原始颜色和大小
        item.itemStyle.color = lastModifiedPoint.oldColor;
        item.symbolSize = lastModifiedPoint.oldSize;
      }
    });
  }

  // 2. 查找当前目标点并记录原始样式
  targetSeries.data.forEach((item, index) => {
    if (item.name === targetName) {
      pointIndex = index;
      currentPoint = item;
      // 记录当前点的原始样式（用于下次恢复）
      lastModifiedPoint = {
        name: item.name,
        oldColor: "#00FF00", // 默认为原始绿色
        oldSize: 15, // 默认为原始大小15
      };
      // 修改为新样式
      item.itemStyle = { ...item.itemStyle, color: "#ff0000" };
      item.symbolSize = 25;
    }
  });

  // 3. 更新图表并显示提示框
  if (pointIndex !== -1 && currentPoint) {
    chartInstance.setOption(option);

    // 关闭之前的提示框（避免重叠）
    chartInstance.dispatchAction({ type: "hideTip" });

    // 显示当前点的提示框
    setTimeout(() => {
      chartInstance.dispatchAction({
        type: "showTip",
        seriesIndex: 0,
        dataIndex: pointIndex,
      });
    }, 50);
  } else {
    // 如果未找到目标点，清空上次记录
    // lastModifiedPoint = null;
    // console.warn(`未找到名称为${targetName}的点`);
    // 如果未找到目标点，恢复所有点的样式并清空记录
    targetSeries.data.forEach((item) => {
      // 恢复默认样式
      item.itemStyle = { ...item.itemStyle, color: "#00FF00" };
      item.symbolSize = 15;
    });
    // 清空上次修改记录
    lastModifiedPoint = null;
    // 隐藏提示框
    chartInstance.dispatchAction({ type: "hideTip" });
    // 更新图表
    chartInstance.setOption(option);
    console.warn(`未找到名称为${targetName}的点，已恢复所有点原始样式`);
  }
}

const resizeHandler = () => {
  myCharts.value?.resize();
  myCharts.value?.setOption(myCharts.value.getOption()); // 强制更新配置
};
onBeforeUnmount(() => {
  window.removeEventListener("resize", resizeHandler);
  myCharts.value?.dispose();
});
defineExpose({ GetEchar, setIcon });
watch(
  () => props.options,
  (newVal, oldVal) => {
    // GetEchar('中国')
  }
);
</script>

<style lang="scss" scoped>
.bars_w {
  width: 100%;
  height: 100%;
}

.iconfont {
  cursor: pointer;
  position: absolute;
  top: 10px;
  left: 10px;
  z-index: 2;
  font-size: 20px;
  color: var(--el-color-primary) !important;
}
</style>
