<template>
  <div ref="chartRef" :style="{ height, width }"></div>
</template>
<script>
import { ref, reactive, watch, watchEffect } from 'vue';
import { cloneDeep } from 'lodash';
import { useEcharts } from '@/hooks/useEcharts';

export default {
  name: 'customEchartBubble',
  props: {
    chartData: {
      type: Array,
      default: () => [],
    },
    size: {
      type: Object,
      default: () => {},
    },
    option: {
      type: Object,
      default: () => ({}),
    },
    width: {
      type: String,
      default: '100%',
    },
    height: {
      type: String,
      default: 'calc(100vh - 78px)',
    },
  },
  emits: ['click'],
  setup(props, { emit }) {
    const chartRef = ref(null);
    const { setOptions, getInstance, resize } = useEcharts(chartRef);
    const option = reactive({
      tooltip: {
        formatter: function (params) {
          console.log(params);
          var str = params.marker + '' + params.data.name + '</br>' + '交易额：' + params.data.value + '万元</br>';
          return str;
        },
      },
      animationDurationUpdate: function (idx) {
        // 越往后的数据延迟越大
        return idx * 100;
      },
      animationEasingUpdate: 'bounceIn',
      color: ['#fff', '#fff', '#fff'],
      series: [
        {
          type: 'graph',
          layout: 'force',
          force: {
            repulsion: 80,
            edgeLength: 20,
          },
          roam: true,
          label: {
            normal: {
              show: true,
            },
          },
          data: props.chartData,
        },
      ],
    });

    watchEffect(() => {
      props.chartData && initCharts();
    });

    watch(
      () => props.size,
      () => {
        console.info(' option.series[0]', props.chartData);
        resize();
      },
      {
        immediate: true,
      }
    );

    function initCharts() {
      if (props.option) {
        Object.assign(option, cloneDeep(props.option));
      }
      option.series[0].data = props.chartData;
      setOptions(option);
      resize();
      getInstance()?.off('click', onClick);
      getInstance()?.on('click', onClick);
    }

    function onClick(params) {
      emit('click', params);
    }

    return { chartRef };
  },
};
</script>
