import {Button, Input, Modal} from "antd";
import {saveAs} from "file-saver";
import {useEffect, useState} from "react";
import {useSetState} from "ahooks";
import {Player} from "@/components/video/player.tsx";

import ArticleGroup from "@/components/article/group";
import * as article from "@/service/api/article.ts";
import {push2room} from "@/service/api/video.ts";
import {showErrorToast, showToast} from "@/components/message.ts";

type Props = {
	video?: VideoInfo;
	onClose?: () => void
}
export default function VideoDetail({video, onClose}: Props) {
	const [groups, setGroups] = useState<BlockContent[][]>([]);

	const [state, setState] = useSetState({
		exporting: false,
		pushing: false,
	})
	// 将视频推送到数字人直播间
	const pushToRoom = () => {
		if (video) {
			if (state.pushing) return
			setState({pushing: true})
			push2room([video.id]).then(() => {
				showToast('一键推流成功，已推流至数字人直播间，请查看！', 'success')
			}).catch(showErrorToast).finally(() => {
				setState({pushing: false})
			})
		}
	}
	// 下载视频
	const downloadVideo = () => {
		if (video?.oss_video_url) {
			const filename = video.oss_video_url.split('/').pop() || `${video.id}.flv`
			saveAs(video.oss_video_url, filename)
		}
	}

	useEffect(() => {
		if (video) {
			if (video.id > 0) {
				article.getById(video.id).then(res => {
					setGroups(res.content_group)
				})
			}
		}
	}, [video])

	return (<>
		<Modal open={!!video} title="新闻视频详情" width={1000} footer={null} onCancel={onClose}>
			<div className="flex gap-2 my-5">
				<div className="news-video w-[350px]">
					<div className="video-container bg-gray-100 rounded overflow-hidden h-[640px]">
						<Player url={video?.oss_video_url} poster={video?.cover} showControls={true}
						        className="w-[360px] h-[640px] bg-white"/>
					</div>
					<div className="video-info text-right text-sm text-gray-600 mt-3">
						<span>创建时间: 5小时前</span>
					</div>
				</div>
				<div className="detail flex-1 ml-5">
					<div className="text-lg">新闻内容</div>
					<div className="article-title mt-5 items-center flex">
						<span className="text text-base">标题</span>
						<span className="ml-4 flex-1">
							<Input value={video?.title}/>
						</span>
					</div>
					<div className="aricle-body mt-3">
						<div className="title">
							<span className="text text-base">正文</span>
						</div>
						<div className="box mt-1">
							<ArticleGroup groups={groups}/>
						</div>
					</div>
				</div>
			</div>
			<div className="footer flex justify-between">
				<div className="action flex gap-2">
					<Button loading={state.pushing} type="primary" onClick={pushToRoom}>一键推流</Button>
					<Button onClick={downloadVideo}>下载视频</Button>
				</div>
				<div className="close">
					<Button onClick={onClose}>关闭</Button>
				</div>
			</div>
		</Modal>
	</>)
}