<!--  评分占比柱状图 -->
<template>
  <div :id="id" :class="className" :style="{ height, width }" />
</template>

<script setup lang="ts">
import * as echarts from "echarts";

const props = defineProps({
  id: {
    type: String,
    default: "percentBarChart",
    required: true,
  },
  className: {
    type: String,
    default: "chart",
  },
  width: {
    type: String,
    default: "400px",
  },
  height: {
    type: String,
    default: "400px",
  },
  title: {
    type: String,
    default: "",
  },
  // percent:[5,5,65,10,10]
  percent: {
    type: Array,
    default: [] as Array<number>,
  },
  // data:[1,2,13,2,2]
  data: {
    type: Array,
    default: [] as Array<number>,
  },
});

const labelFormatter = (params) => {
  // 显示人数 加 百分比
  console.log(params);
  if (params.value > 0) {
    return props.data?.[params.dataIndex] + "人 (" + params.value + "%)";
  } else {
    return "";
  }
};
const colorFormatter = function (params) {
  // 每个柱子的颜色即为colorList数组里的每一项，如果柱子数目多于colorList的长度，则柱子颜色循环使用该数组
  const colorList = ["#68cfff", "#688fff", "#b890ef", "#ee7a66", "#f6c04c"];
  return colorList[params.dataIndex];
};
/**
 * 配置项
 */
const options = {
  title: {
    text: props.title,
    left: "20%",
    textStyle: {
      color: "#2e3346",
      fontWeight: "normal",
      fontSize: 15,
    },
  },
  grid: {
    left: "5%",
    right: "5%",
    top: "8%",
    containLabel: true,
  },
  xAxis: [
    //x轴数据设置
    {
      type: "value",
      show: false,
      min: 0,
      max: 100,
    },
  ],
  yAxis: [
    {
      type: "category",
      offset: 0,
      axisLine: {
        show: false,
      },
      data: ["0-20分", "21-40分", "41-60分", "51-60分", "60分以上"],
      interval: 100,
      axisPointer: {
        type: "shadow",
      },
      axisTick: {
        show: false,
      },
    },
  ],
  series: [
    {
      data: props.percent,
      type: "bar",
      label: {
        show: true,
        position: "right",
        formatter: labelFormatter,
      },
      showBackground: true,
      backgroundStyle: {
        color: "#f2f2fb",
      },
      itemStyle: {
        color: colorFormatter,
      },
      barCategoryGap: "50%",
    },
  ],
};

onMounted(() => {
  // 图表初始化
  const chart = echarts.init(
    document.getElementById(<string>props.id) as HTMLDivElement
  );
  chart.setOption(options);
  // 大小自适应
  window.addEventListener("resize", () => {
    chart.resize();
  });
});
</script>
