/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2024-07-02 17:50:08
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2024-12-17 17:00:48
 * @FilePath: /MediScreen/src/components/BarChartComponent/index.tsx
 * @Description: BarChartComponent示例代码
 */
import React, { useEffect, useState } from 'react';
import './style.less';

interface BarChartItem {
  label: string;
  value: number | null; // 如果可能为null，请声明为 number | null
  unit: string;
}

interface BarChartComponentProps {
  data: BarChartItem[];
}

const maxBarWidth = 200; // 最大条形图宽度

const BarChartComponent: React.FC<BarChartComponentProps> = ({ data }) => {
  const [animatedWidths, setAnimatedWidths] = useState<number[]>([]);

  useEffect(() => {
    if (data.length === 0) {
      setAnimatedWidths([]);
      return;
    }

    const values = data.map(d => d.value || 0); // 如果为 null 则赋值为0
    const maxValue = Math.max(...values);

    // 设置初始宽度为0
    setAnimatedWidths(new Array(data.length).fill(0));
    // 模拟数据加载并设置实际宽度
    setTimeout(() => {
      setAnimatedWidths(values.map(v => (v / maxValue) * maxBarWidth));
    }, 100);
  }, [data]);

  if (data.length === 0) {
    return <div className="bar-chart">暂无数据</div>;
  }

  return (
    <div className="bar-chart">
      {data.map((item, index) => {
        // 处理可能的null值，若为null则显示"N/A"
        const displayValue = (typeof item.value === 'number' && !isNaN(item.value))
          ? item.value.toLocaleString()
          : 'N/A';

        return (
          <div className="bar-chart-item" key={index}>
            <div className="bar-chart-label">{item.label}</div>
            <div className="bar-chart-bar-wrapper">
              <div
                className="bar-chart-bar"
                style={{ width: `${animatedWidths[index]}px` }}
              ></div>
              <div className="bar-chart-value">
                {displayValue}{item.value !== null ? ` ${item.unit}` : ''}
              </div>
            </div>
          </div>
        );
      })}
    </div>
  );
};

export default BarChartComponent;
