<template>
  <div>
    <div :ref="refName" class="wordChart" ></div>
  </div>
</template>
<script>
let echarts = require("echarts");
require("echarts-wordcloud");
require("echarts/lib/component/legend");
import customed from '../../assets/js/customed.json';
echarts.registerTheme('customed',customed)
import { mediaWord } from "../../assets/js/chart-color";
const refName= Math.random().toString(36).substr(2)
export default {
  name: "wordChart",
  data() {
    return {
      refName: refName,
      img: new Image(),
      option: {
        series: [
          {
            type: "wordCloud",
            sizeRange: [14, 48],
            width:this.width,
            rotationRange: [0, 0],
            left: "center",
            gridSize: 20,
            shape: "smooth",
            maskImage: "",
            drawOutOfBound: false,
            data: this.getdata()
          }
        ]
      },
      words: {}
    };
  },
  props: {
    className: String,
    datas: Array,
    imgUrl:String,
    width:String
  },
  methods: {
    getdata(obj) {
      var data = [];
      for (var key in obj) {
        var i = Math.floor(Math.random() * mediaWord.length);
        if(!obj[key]){
          continue;
        }
        data.push({
          name: key,
          value: Math.sqrt(obj[key]),
          textStyle: {
            normal: {
              // color: mediaWord[i]
            }
          }
        });
      }
      return data.sort(function(a, b) {
        return b.value - a.value;
      });
    },
    loadData() {
      var that = this;
      this.img.onload = function() {
        that.option.series[0].maskImage = this;
        that.option.series[0].data = that.datas;
        that.mychart.setOption(that.option);
      };
      this.img.src = this.imgUrl;
    }
  },
  updated() {
    this.loadData();
  },
  mounted() {
    this.mychart = echarts.init(this.$refs[refName],'customed');
    this.loadData();
  },
  created() {},
  watch: {
    datas: {
      handler(val, oldVal) {
        this.loadData();
      },
      deep: true
    }
  }
};
</script>
<style lang="scss" scoped>
.wordChart {
  width: 100%;
  height: 100%;
}
</style>
