<template>
  <div class="w-full h-full" ref="containerRef"></div>
</template>

<script setup lang="ts">
import { ref, withDefaults, defineProps, computed, watch } from 'vue';
import maskImg from '@/assets/images/cloud-word-bg.png';
import VChart from '@visactor/vchart';

type Word = {
  name: string;
  value: number;
  textStyle?: { [key: string]: string };
};

const props = withDefaults(defineProps<{ words: Word[] }>(), {
  words: () => [],
});

const containerRef = ref<HTMLDivElement | null>(null);
const chart = ref<VChart | null>(null);

const spec = computed(() => {
  return {
    type: 'wordCloud',
    nameField: 'name',
    valueField: 'value',
    seriesField: 'name',
    background: 'transparent',
    fontSizeRange: [26, 42],
    maskShape: process.env.NODE_ENV === 'production' ? maskImg : window.location.origin + maskImg,
    wordCloudShapeConfig: {
      fillingColorList: ['#466688', '#6789a6', '#c5edf9', '#2881bc', '#309cdd'],
      fillingTimes: 1,
      importantWordCount: 2,
      fillingRatio: 0,
    },
    colorMode: 'ordinal',
    colorList: ['#466688', '#6789a6', '#c5edf9', '#2881bc', '#309cdd'],
    data: {
      id: 'cloud',
      name: 'baseData',
      values: props.words,
    },
    word: {
      interactive: false,
      padding: 30,
      style: {
        fontFamily: 'PingFangSC-Medium, sans-serif',
      },
    },
  };
});

watch(
  () => [props.words, containerRef.value],
  () => {
    // chart.value?.updateData('cloud', props.words);
    if (containerRef.value && props.words?.length) {
      chart.value = new VChart(spec.value, {
        dom: containerRef.value!,
      });
      chart.value?.renderSync();
    }
  },
);
</script>
