<template>
  <div ref="cloud" :style="{ width: '100%', height }"></div>
</template>

<script>
import 'echarts-wordcloud' // 引入 wordcloud 扩展 (必须在 echarts 之后)

export default {
  name: 'WordCloud',
  props: {
    /**
     * words 数组支持两种格式：
     * ["AI", "IoT", "Digital Humans"]
     * 或 [{ text:"AI", value:120 }, { text:"IoT", value:80 }]
     */
    words: { type: Array, required: true },
    height: { type: String, default: '300px' }
  },
  data() {
    return { chart: null }
  },
  watch: {
    words: {
      deep: true,
      handler() { this.renderCloud() }
    },
    height() {
      this.$nextTick(() => { this.chart && this.chart.resize() })
    }
  },
  mounted() { this.init() },
  beforeDestroy() { this.chart && this.chart.dispose() },
  methods: {
    init() {
      this.chart = this.$echarts.init(this.$refs.cloud)
      this.renderCloud()
      window.addEventListener('resize', this.chart.resize)
    },
    renderCloud() {
      if (!this.chart) return

      // ① 把字符串转成带权重对象
      const data = this.words.map(w =>
          typeof w === 'string'
              ? { name: w, value: w.length * 8 }     // 适当缩小基准权重
              : { name: w.text, value: w.value }
      )

      // ② 根据容器实时计算最大字号
      const { height: h } = this.$refs.cloud.getBoundingClientRect()
      const maxFont = Math.floor(h * 0.30)          // 占容器高度 30%
      const minFont = Math.max(10, Math.floor(maxFont / 3))

      this.chart.setOption({
        backgroundColor: 'transparent',
        tooltip: { show: false },
        series: [{
          type: 'wordCloud',
          /* --- 关键：贴满父容器，无留白 --- */
          left: 70, top: 0, right: 0, bottom: 0,
          shape: 'circle',

          sizeRange: [minFont, maxFont],   // 动态字号
          gridSize: 2,                     // 更细网格
          shrinkToFit: true,               // 末词再压缩
          rotationRange: [ -30, 30 ],      // 轻微倾斜即可
          rotationStep: 30,

          textStyle: {
            fontFamily: 'Impact',
            color(params) {
              const toppers = ['#FC8A66', '#FED95D', '#40DA93']
              if (params.dataIndex < 3) return toppers[params.dataIndex]
              const palette = ['#79D8FF', '#2C9AFF', '#C99CFF', '#6A44FF', '#8EC4FF']
              return palette[Math.floor(Math.random() * palette.length)]
            }
          },

          data
        }]
      })
    }

  }
}
</script>

<style scoped>
/* 可选：给 canvas 再加点淡淡的炫光背景 */
</style>
