import React from 'react';
import styles from './index.less';
import { Progress } from 'antd';
import { PlayCircleOutlined, PauseCircleOutlined } from '@ant-design/icons';
import moment from 'moment';
import { SingleAudioContext } from '../single-audio';

interface AudioPlayerProps {
  url?: string;
}

const AudioPlayer: React.FC<AudioPlayerProps> = props => {
  const { url } = props;

  const [playing, setPlaying] = React.useState(false);
  const [duration, setDuration] = React.useState(0);
  const [current, setCurrent] = React.useState(0);
  const audioRef = React.useRef<HTMLAudioElement>();
  const idRef = React.useRef<string>(`${Date.now()}-${Math.random()}`);
  //不晓得为毛current会超过duration
  const percent =
    duration !== 0 ? (Math.min(current, duration) * 100) / duration : 0;
  const { playingId, setPlayingId } = React.useContext(SingleAudioContext);

  React.useEffect(() => {
    function handleTimeUpdate() {
      if (audioRef?.current) {
        setCurrent(audioRef?.current.currentTime);
        setDuration(audioRef?.current.duration);
        if (audioRef?.current?.duration <= audioRef?.current.currentTime) {
          handleStop();
          setCurrent(0);
        }
      }
    }

    // function getAudioTime(): Promise<number> {
    //   return new Promise((resolve, reject) => {
    //     const audio = audioRef?.current;
    //     if (audio) {
    //       audio.addEventListener("loadedmetadata", function() {
    //         const duration = audio.duration;
    //         resolve(duration);
    //       });
    //     } else {
    //       reject();
    //     }
    //   });
    // }

    async function init() {
      audioRef.current = new Audio(url);
      // const duration = await getAudioTime();
      // setDuration(duration);
      audioRef.current.addEventListener('timeupdate', handleTimeUpdate);
    }

    if (url) {
      init();
    }
    return () => {
      if (audioRef.current) {
        audioRef.current.removeEventListener('timeupdate', handleTimeUpdate);
        audioRef.current = undefined;
      }
    };
  }, [url]);

  React.useEffect(() => {
    if (playingId !== idRef?.current) {
      handleStop();
    }
  }, [playingId]);

  const handlePlay = () => {
    if (audioRef.current) {
      audioRef.current.play();
      setPlaying(true);
      setPlayingId?.(idRef.current);
    }
  };

  const handleStop = () => {
    if (audioRef.current) {
      audioRef.current.pause();
      setPlaying(false);
    }
  };

  return (
    <div className={styles.player}>
      {playing ? (
        <PauseCircleOutlined
          style={{ marginRight: 8, cursor: 'pointer' }}
          onClick={handleStop}
        />
      ) : (
        <PlayCircleOutlined
          style={{ marginRight: 8, cursor: 'pointer' }}
          onClick={handlePlay}
        />
      )}
      <Progress
        percent={percent}
        size="small"
        status={'normal'}
        style={{ width: '108px' }}
        format={() =>
          moment(
            moment()
              .startOf('day')
              .valueOf() +
              Math.min(current, duration) * 1000,
          ).format('HH:mm:ss')
        }
        strokeWidth={2}
      />
    </div>
  );
};

export default AudioPlayer;
