import { useServerTime } from '@/hooks/useServerTime';
import { elapsedTime } from '@/utils/date';
import React, { useEffect, useState } from 'react';

type RunDurationProps = {
  createTime?: string;
  finishTime?: string;
  className?: string;
  style?: React.CSSProperties;
};
function RunDuration({ createTime, finishTime, className, style }: RunDurationProps) {
  const [now] = useServerTime();
  const [currentTime, setCurrentTime] = useState<Date>(finishTime ? new Date(finishTime) : now());

  // console.log(
  //   'currentTime',
  //   new Date(createTime ?? 0),
  //   currentTime,
  //   (currentTime.getTime() - new Date(createTime ?? 0).getTime()) / 1000,
  // );

  // 定时刷新耗时
  useEffect(() => {
    if (finishTime) {
      setCurrentTime(new Date(finishTime));
    } else {
      setCurrentTime(now());
      const timer = setInterval(() => {
        setCurrentTime(now());
      }, 1000);
      return () => {
        clearInterval(timer);
      };
    }
  }, [finishTime, now]);

  return (
    <span className={className} style={style}>
      {elapsedTime(createTime, currentTime)}
    </span>
  );
}

export default RunDuration;
