import useNewToken from "@/Hook/useNewToken"
import React, { useEffect, useState } from "react"
import style from './index.less'


interface Props {
    url?: string,
    times?: string
}
/**
 * 音频展示
 * @param param0 
 * @returns 
 */
const AudioNews: React.FC<Props> = ({ url, times }) => {

    /*****************************/
    const { token } = useNewToken()
    const [isPlay, setIsPlay] = useState<boolean>(false)  // 是否播放
    const [audio, setAudio] = useState<any>(null)
    /*****************************/

    const ended = () => {
        console.log("播放结束");
        setIsPlay(false)
    }

    const pause = () => {
        console.log("暂停触发");
        setIsPlay(false)
    }

    useEffect(() => {
        let audio = new Audio(url) // 创建音频对象
        setAudio(audio)
        audio.addEventListener('ended', ended, false);
        audio.addEventListener('pause', pause, false);

        return () => {
            if (audio) {
                audio?.removeEventListener('ended', ended)
                audio?.removeEventListener('pause', pause)
            }
        }
    }, [])

    const play = () => {
        setIsPlay(!isPlay)
        if (!isPlay) {
            audio.play()
        } else {
            audio.pause()
        }
    }

    return <div className={style.audioNews} >
        <div
            onClick={play}
            className={`${style.weap} ${isPlay ? style.play : ''}`}
            style={{
                backgroundColor: token.colorBgContainer,
                borderRadius: token.borderRadius,
                border: `1px solid ${token.colorBorder}`
            }}>
        </div>
        <div className={style.time}>
            {times}″
        </div>
    </div>
}


export default React.memo(AudioNews)