// import ReactPlayer from 'react-player'
// import {PauseOutlined, PlayCircleOutlined, FullscreenOutlined, FullscreenExitOutlined} from "@ant-design/icons"
// import {Progress} from "antd";
import React, {useEffect, useState} from "react";
import {PlayerInstance} from "@/hooks/useCache.ts";
import TCPlayer from 'tcplayer.js';
import 'tcplayer.js/dist/tcplayer.min.css';

type State = {
	playing: boolean
	muted: boolean
	end?: boolean
	error?: boolean
	fullscreen: boolean
	progress: number
	playedSeconds: number
	duration: number
}
type StateUpdate = Partial<State> | ((prev: State) => Partial<State>)

type Props = {
	url?: string; cover?: string; showControls?: boolean; className?: string;
	poster?: string;
	onChange?: (state: State) => void;
	onProgress?: (current:number,duration:number) => void;
	muted?: boolean;
	autoPlay?: boolean;
}
export type PlayerInstance = {
	play: (url: string, currentTime: number) => void;
	pause: () => void;
	getState: () => State;
}
export const Player = React.forwardRef<PlayerInstance, Props>((props, ref) => {
	const [tcPlayer, setTcPlayer] = useState<TCPlayer | null>(null)
	const [prevUrl, setPrevUrl] = useState<string | undefined>();
	const [state, _setState] = useState<State>({
		playing: false,
		muted: false,
		// 是否全屏
		fullscreen: false,
		progress: 0,
		playedSeconds: 0,
		duration: 0
	})

	const setState = (data: StateUpdate) => {
		console.log('playstate change', data)
		_setState(prev => {
			const _state = typeof (data) === 'function' ? {...prev, ...data(prev)} : {...prev, ...data}
			props.onChange?.(_state)
			return _state
		})
	}

	useEffect(()=>{
		if(props.url && tcPlayer){
			tcPlayer.src(props.url)
		}
	},[props.url, tcPlayer])

	useEffect(() => {
		if(PlayerInstance.length != 0){
			PlayerInstance.forEach(player => player.pause())
			PlayerInstance.length = 0
		}
		const playerVideo = document.createElement('video');
		const playerId = `player-container-${Date.now().toString(16)}`;
		playerVideo.setAttribute('id', playerId)
		playerVideo.setAttribute('preload', 'auto')
		playerVideo.setAttribute('playsInline', 'true')
		playerVideo.setAttribute('webkit-playsinline', 'true')
		if(props.className) playerVideo.setAttribute('className', props.className)
		playerVideo.classList.add('digital-video-player')
		PlayerInstance.push(playerVideo)
		document.querySelector('.video-player-container-inner')!.appendChild(playerVideo)

		const player = TCPlayer(playerId, {
				//sources: [{src: props.url}],
				controls: props.showControls,
				// muted:props.muted,
				poster: props.poster,
				autoplay: typeof(props.autoPlay) != 'undefined' ? props.autoPlay : true,
				licenseUrl: 'https://license.vod2.myqcloud.com/license/v2/1328581896_1/v_cube.license'
			}
		)
		player.on('pause', () => {
			setState({playing: false, end: false, error: false})
		})
		player.on('playing', () => {
			setState({playing: true, end: false, error: false})
		})
		player.on('ended', () => {
			setState({end: true, playing: false, error: false})
		})
		player.on('timeupdate', () => {
			props.onProgress?.(player.currentTime(), player.duration())
		})
		player.on('error', () => {
			setState({end: false, playing: false, error: true})
		})
		setTcPlayer(() => player)
		return () => {
			// if (tcPlayer) {
			// 	tcPlayer.pause()
			// 	tcPlayer.unload()
			// }else{
			// 	playerVideo.pause()
			// }
			console.log('destroy video')
			try{
				Array.from(document.querySelectorAll('video')).forEach(v => v.pause())
			}catch (e){
				console.log(e)
			}
			playerVideo.parentElement?.removeChild(playerVideo)
		}
	}, [])
	React.useImperativeHandle(ref, () => {
		return {
			pause(){
				if (!tcPlayer) return;
				tcPlayer.pause()
			},
			play: (url, currentTime = 0) => {
				console.log('play', url, currentTime)
				if (!tcPlayer) return;
				const player = tcPlayer
				if (prevUrl == url) {
					player.currentTime(0)
				} else {
					player.src(url)
				}
				player.play()
				setPrevUrl(url)
				if (currentTime > 0) {
					player.currentTime(currentTime)
				}
			},
			getState: () => state
		}
	})

	return <div className={`video-player relative ${props.className} video-player-container-inner`}>
	</div>
})