<!--
 * @Author: chris
 * @Date: 2025-08-18 09:36:11
 * @LastEditors: chris
 * @LastEditTime: 2025-09-29 15:19:28
-->
<script setup>
import { BarChart } from 'echarts/charts';
// 引入标题，提示框，直角坐标系，数据集，内置数据转换器组件，组件后缀都为 Component
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  DatasetComponent,
  TransformComponent
} from 'echarts/components';
// 标签自动布局、全局过渡动画等特性
import { LabelLayout, UniversalTransition } from 'echarts/features';
// 引入 Canvas 渲染器，注意引入 CanvasRenderer 或者 SVGRenderer 是必须的一步
import { CanvasRenderer } from 'echarts/renderers';

const props = defineProps({
  chartData: {
    type: Object,
    required: true,
    // default: () => ({
    //   names: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
    //   data: [120, 200, 150, 80, 70, 110, 130]
    // })
  }
});

const { proxy } = getCurrentInstance()
const barChartRef = ref(null)
let barChart = null

registerComponents()

onMounted(() => {
  initBarChart()
})

onUnmounted(() => {
  if (barChart) {
    barChart.dispose();
    barChart = null;
  }
});

watch(() => props.chartData, (newData) => {
  if (barChart) {
    barChart.setOption(createOption(newData));
  }
}, { deep: true });

function initBarChart() {
  if (barChartRef.value) {
    barChart = proxy.$echarts.init(barChartRef.value);
    barChart.setOption(createOption(props.chartData));
  }
}

function createOption (data) {
  const option = {
    tooltip: {
      show: true
    },
    xAxis: {
      type: 'category',
      data: data.names
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        data: data.data,
        type: 'bar',
        colorBy: 'series',
        itemStyle: {
          color: ({ dataIndex }) => {
            const colorList = getItemsColorList(data.data?.length || 0)
            return colorList[dataIndex]
          }
        },
      }
    ]
  };
  return option;
}

function registerComponents() {
  // 注册必须的组件
  proxy.$echarts.use([TitleComponent, TooltipComponent, GridComponent, DatasetComponent, TransformComponent, BarChart, LabelLayout, UniversalTransition, CanvasRenderer]);
}

/**
 * 随机生成暗色
 * 确保生成的颜色不是亮色，通过控制RGB值在较低范围内
 * @returns {string} 十六进制颜色代码
 */
function generateDarkColorList() {
  // 生成0-180之间的随机RGB值，确保颜色较暗
  const r = Math.floor(Math.random() * 180);
  const g = Math.floor(Math.random() * 180);
  const b = Math.floor(Math.random() * 180);
  
  // 转换为十六进制并格式化
  const toHex = (value) => {
    const hex = value.toString(16);
    return hex.length === 1 ? '0' + hex : hex;
  };
  
  return '#' + toHex(r) + toHex(g) + toHex(b);
}

function getItemsColorList (length) {
  const colorList = []
  for (let i = 0; i < length; i++) {
    colorList.push(generateDarkColorList())
  }
  return colorList
}

function calcBoxSize () {}
</script>

<template>
  <div class="statistics-chart">
    <div class="bar-chart" ref="barChartRef"></div>
  </div>
</template>

<style lang="scss" scoped>
.statistics-chart, .bar-chart {
  @apply h-100% w-100%;
}
</style>