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

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

const props = defineProps({
	// 词云数据
	data: {
		type: Array,
		required: true
	},
	// 词云形状
	shape: {
		type: String,
		default: "circle"
	},
	// 选中的项的名字
	selectedName: {
		type: String,
		default: ""
	}
});

const emit = defineEmits(["wordClick"]);

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

const initChart = () => {
	if (echartWord.value) {
		if (myChart) {
			myChart.dispose();
		}
		myChart = echarts.init(echartWord.value);

		const chartData = props.data.map(item => {
			const isSelected = item.name === props.selectedName;
			if (isSelected) {
				return {
					...item,
					// 提升选中项的权重，确保其在布局中占主导地位
					value: 100, // 给予一个显著高于其他的固定大值，使其占据中心
					textStyle: {
						fontWeight: "bold",
						color: "#fff",
						backgroundColor: "rgba(189, 33, 33, 0.9)",
						borderRadius: 20,
						padding: [10, 16] // 适当增加 padding 以确保背景块足够大
					}
				};
			}
			return {
				...item,
				value: Math.floor(Math.random() * 20) + 10 // 为非选中项分配较小的随机权重，有助于均匀分布
			};
		});

		const option = {
			grid: {
				left: 0,
				top: 0,
				right: 0,
				bottom: 0
			},
			series: [
				{
					type: "wordCloud",
					shape: props.shape,
					gridSize: 30, // 增大网格间距，防止重叠
					sizeRange: [16, 26], // 保持字体大小
					rotationRange: [0, 0],
					rotationStep: 0,
					drawOutOfBound: true,
					layoutAnimation: true,
					keepAspect: true,
					textStyle: {
						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: chartData
				}
			]
		};
		myChart.setOption(option);

		myChart.on("click", params => {
			emit("wordClick", params.data);
		});

		window.addEventListener("resize", myChart.resize);
	}
};

watch(
	() => [props.data, props.selectedName],
	() => {
		initChart();
	},
	{ deep: true }
);

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

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

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