<script lang="ts" setup>
import { ref, watch, computed } from 'vue';
import { type ECOption, useEcharts } from '@/composables';

type ChartData = {
  seriesData: string[];
  xaxis: string[];
};

type Props = {
  chartData: ChartData;
  xRotate?: number;
  itemStyleColor?: string;
};

const props = defineProps<Props>();

const isExceed = computed(() => {
  if (JSON.stringify(props.chartData) !== '{}') {
    return props?.chartData?.xaxis.length > 15;
  }
  return 0;
});

function barOptionsCreator() {
  const options = {
    grid: {
      x: 30,
      y: 30,
      x2: 30,
      y2: isExceed.value ? 90 : 30
    },
    tooltip: {
      showContent: true,
      trigger: 'axis',
      backgroundColor: 'rgba(8,36,68,.9)',
      borderColor: 'rgba(8,36,68,.9)',
      textStyle: {
        color: '#fff'
      },
      formatter(params: any) {
        let relVal = params[0].name;
        for (let i = 0, l = params.length; i < l; i++) {
          relVal += `<br/>${params[i].marker} ${parseFloat(params[i].value)}%`;
        }
        return relVal;
      }
    },

    xAxis: [
      {
        type: 'category',
        data: props.chartData?.xaxis || [],
        axisLine: {
          lineStyle: {
            color: '#ddd'
          }
        },
        axisTick: {
          show: false
        },
        axisLabel: {
          interval: 0,
          rotate: isExceed.value ? 40 : props.xRotate || 0,
          color: '#2b3d4f',
          margin: 15
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        axisLabel: {
          color: '#2b3d4f'
        },
        nameTextStyle: {
          color: '#2b3d4f',
          fontSize: 12,
          lineHeight: 40
        },
        // 分割线
        splitLine: {
          lineStyle: {
            type: 'dashed',
            color: '#E9E9E9'
          }
        },
        axisLine: {
          show: false
        },
        axisTick: {
          show: false
        }
      }
    ],
    series: [
      {
        type: 'bar',
        barMaxWidth: 50,
        itemStyle: {
          color: props.itemStyleColor || '#E6000A',
          opacity: 1
        },
        data: props.chartData?.seriesData || []
      }
    ]
  } as ECOption;
  return options;
}

const barOptions = ref<ECOption>(barOptionsCreator());

const { domRef: barRef } = useEcharts(barOptions);

watch(
  () => props.chartData,
  val => {
    if (val) {
      barOptions.value = barOptionsCreator();
    }
  },
  {
    deep: true,
    immediate: true
  }
);
</script>
<template>
  <div ref="barRef" class="w-full h-315px"></div>
</template>
