<template>
  <div>
    <div class="echarts-wrap" ref="echartWord"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from "vue";
import * as echarts from "echarts";
import "echarts-wordcloud";

const props = defineProps({
  // 词云数据
  data: {
    type: Array,
    required: true,
    // 示例：
    // [
    //   { name: 'Vue', value: 1000 },
    //   { name: 'ECharts', value: 618 },
    //   // ...
    // ]
  },
  // 词云形状，可以是 'circle', 'cardioid', 'diamond', 'triangle-forward', 'triangle', 'pentagon' 等
  shape: {
    type: String,
    default: "circle",
  },
});

const echartWord = ref(null);
let myChart = null;

const initChart = () => {
  if (echartWord.value) {
    myChart = echarts.init(echartWord.value);
    const option = {
      grid: {
        left: 5,
        top: 5,
        right: 5,
        bottom: 5,
      },
      series: [
        {
          type: "wordCloud",
          shape: props.shape,
          width: '100%',
          height: '100%',
          // 其他形状你可以使用形状路径
          // shape: 'circle', // 示例
          // 或者自定义路径
          gridSize: 30, // 网格大小，影响词间距。
          sizeRange: [15, 40], // 定义词云中文字大小的范围
          rotationRange: [0, 0],
          rotationStep: 0,
          drawOutOfBound: false,  // 是否超出画布
          shrinkToFit: true,     // 是否自动缩小以适应容器
          // 字体
          textStyle: {
            // normal: {
            //   color: function () {
            //     return 'rgb(' + [
            //       Math.round(Math.random() * 160),
            //       Math.round(Math.random() * 160),
            //       Math.round(Math.random() * 160)
            //     ].join(',') + ')';
            //   }
            // },
            color: function () {
              let colors = [
                "rgba(189, 33, 33, 1)",
                "rgba(232, 151, 21, 1)",
                "rgba(220, 190, 68, 1)",
                "rgba(96, 58, 186, 1)",
                "rgba(32, 121, 69, 1)",
                "rgba(22, 119, 255, 1)",
              ];
              return colors[parseInt(Math.random() * colors.length)];
            },
            emphasis: {
              shadowBlur: 5,
              shadowColor: "#333",
            },
          },
          // 设置词云数据
          data: props.data,
        },
      ],
    };
    myChart.setOption(option);
    window.addEventListener("resize", myChart.resize);
  }
};

onMounted(() => {
  initChart();
});

onBeforeUnmount(() => {
  if (myChart) {
    window.removeEventListener("resize", myChart.resize);
    myChart.dispose();
  }
});
</script>

<style lang="scss" scoped>
.echarts-wrap {
  // width: 100%;
  width: 792px;
  height: 401px;
}
</style>
