<template>
  <view
    :id="htmlId"
    ref="echartsRef"
    :style="{ width: '100%', height: `${yData.length * 100}rpx` }"
  ></view>
</template>

<script setup lang="ts">
import * as echarts from 'echarts';
import { computed, onMounted, ref } from 'vue';

const props = defineProps({
  htmlId: String,
  yData: {
    type: Array,
    default: () => [],
  },
  xData: {
    type: Array,
    default: () => [],
  },
});
const echartsRef = ref(null);

const colors = [
  '#FBCA85',
  '#F5EB82',
  '#FB8F85',
  '#82F58B',
  '#85FBDE',
  '#85DEFB',
  '#9FA7FB',
  '#D59FFB',
  '#FB9FD5',
];

const seriesData = computed(() => {
  return props.xData.map((item, index) => {
    return {
      value: item,
      itemStyle: {
        color: colors[index],
      },
    };
  });
});

const initEcharts = async () => {
  const myChart = echarts.init(document.getElementById(props.htmlId));
  const option = {
    grid: {
      left: '40px',
      right: '20px',
      top: '0%',
      bottom: '20',
    },
    xAxis: {
      type: 'value',
    },
    yAxis: {
      type: 'category',
      data: props.yData,
    },
    series: [
      {
        // 460, 280, 200, 260, 560, 280, 880, 590, 500
        data: seriesData.value,
        type: 'bar',
        label: {
          show: true,
          position: 'right',
          valueAnimation: true,
        },
      },
    ],
  };
  myChart && myChart.setOption(option);
};
onMounted(() => {
  initEcharts();
});
</script>

<style scoped lang="scss"></style>
