/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2024-07-04 15:27:08
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2024-12-17 16:47:29
 * @FilePath: /MediScreen/src/components/CircularProgressBar/index.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import React, { useEffect, useState } from 'react';
import './style.less';

interface CircularProgressBarProps {
  percentage: number;
  strokeWidth?: number;
  color?: string;
  trailColor?: string;
  animationDuration?: number;
}

const CircularProgressBar: React.FC<CircularProgressBarProps> = ({
  percentage,
  strokeWidth = 10,
  color = '#4DB6E1',
  trailColor = '#E0E0E0',
  animationDuration = 1000,
}) => {
  const [animatedPercentage, setAnimatedPercentage] = useState(0);

  useEffect(() => {
    setAnimatedPercentage(0);
    const timer = setTimeout(() => {
      setAnimatedPercentage(!Number.isNaN(percentage)?percentage:0);
    }, 100);

    return () => clearTimeout(timer);
  }, [percentage]);

  const size = 100;
  const radius = (size - strokeWidth) / 2;
  const circumference = 2 * Math.PI * radius;
  const offset = circumference - (animatedPercentage / 100) * circumference;


  return (
    <div className="circular-progress-bar">
      <svg
        width="100%"
        height="100%"
        viewBox={`0 0 ${size} ${size}`}
      >
        <circle
          stroke={trailColor}
          fill="transparent"
          strokeWidth={strokeWidth}
          r={radius}
          cx={size / 2}
          cy={size / 2}
        />
        <circle
          stroke={color}
          fill="transparent"
          strokeWidth={strokeWidth}
          strokeDasharray={circumference}
          strokeDashoffset={typeof offset == 'number'?offset:5}
          strokeLinecap="round"
          r={radius}
          cx={size / 2}
          cy={size / 2}
          style={{ transition: `stroke-dashoffset ${animationDuration}ms ease-in-out` }}
        />
      </svg>
      <div className="percentage">{parseFloat(animatedPercentage.toFixed(2))}%</div>
    </div>
  );
};

export default CircularProgressBar;
