<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: 'customEchartPictorialBar',
  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({
      grid: {
        left: '3%',
        right: '4%',
        bottom: '6%',
        top: '11%',
        containLabel: true,
      },
      tooltip: {
        formatter: '{b}',
      },
      series: [
        {
          type: 'pictorialBar',
          barCategoryGap: '40%',
          barWidth: '100%',
          symbol: 'path://M0,10 L10,10 C5.5,10 5.5,5 5,0 C4.5,5 4.5,10 0,10 z',
          data: [],
          labelLine: { show: true },
          z: 10,
          itemStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                {
                  offset: 0,
                  color: '#000001', // 起始颜色
                },
                {
                  offset: 1,
                  color: '#0175b6', // 结束颜色
                },
              ],
              global: false, // 默认为 false
            },
          },
          label: {
            show: false,
            position: 'top',
            formatter: '{c}',
            color: 'white',
            fontSize: 14,
          },
        },
      ],
    });

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

    watch(
      () => props.size,
      () => {
        resize();
      },
      {
        immediate: true,
      }
    );

    function initCharts() {
      if (props.option) {
        Object.assign(option, cloneDeep(props.option));
      }
      setOptions(option);
      resize();
      getInstance()?.off('click', onClick);
      getInstance()?.on('click', onClick);
    }

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

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