import * as React from 'react';
import InfiniteScroll from 'react-infinite-scroller';
import { Slider, Select, message } from 'antd';
import {
	PlusOutlined,
	MinusOutlined,
	PauseOutlined,
	CaretUpOutlined,
} from '@ant-design/icons';
import VideoPlayer from '../../compontens/videoPlayer';
import BoxWrapper from '../../compontens/box';
import {
	useChanleList,
	chanleStatus,
	ChanleProps,
	useChanleLiveUrl,
	IliveUrlProps,
	useVideoControllerPtz,
	PTzParmas,
} from '../../hooks/video';
import './index.scss';
import view1 from './static/view1.png';
import view2 from './static/view2.png';
import view3 from './static/view3.png';
import view6 from './static/view6.png';
import view4 from './static/view4.png';
import view8 from './static/view8.png';
import view9 from './static/view9.png';
const { Option } = Select;
const controllerViews = [
	{
		view: 1,
		icon: view1,
	},
	{
		view: 2,
		icon: view2,
	},
	{
		view: 3,
		icon: view3,
	},
	{
		view: 4,
		icon: view4,
	},
	{
		view: 6,
		icon: view6,
	},
	{
		view: 8,
		icon: view8,
	},
	{
		view: 9,
		icon: view9,
	},
];

type PlayWindowProps = {
	liveUrls?: IliveUrlProps;
	chanalChecked?: boolean; //通道选中
	windowChecked: boolean; // 播放界面选中
} & Partial<ChanleProps>;

const videos: React.FC = (props) => {
	// 保存的搜素依赖条件
	const [state, setState] = React.useState({
		filter: '',
		page: 1,
	});
	const [ptzState, handleChangePtzState] = React.useState<{
		silderNum: number;
		position: number | undefined;
	}>({
		silderNum: 30,
		position: undefined,
	});
	// 保存的正在播放的列表
	const [playState, setPlayState] = React.useState<{
		playWindows: PlayWindowProps[]; // 当前播放的地址列表
	}>({
		playWindows: [
			{
				id: Date.now(),
				windowChecked: true,
			},
		],
	});
	// 请求通道列表
	const [
		chanleListState,
		requestChanleList,
		handleChangeChanleList,
	] = useChanleList();
	// 请求直播Url地址
	const [liveUrlState, requestChanleLiveUrl] = useChanleLiveUrl();
	//请求控制摄像头
	const { request: requestControllerVideo } = useVideoControllerPtz();
	//监听过滤条件(如果发生变化则，进行请求)
	React.useEffect(() => {
		requestChanleList({
			page: state.page,
			channel_no: state.filter,
		});
	}, [state.filter, state.page]);

	// 改变播放界面个数
	const changeVidowWindow = (num: number) => {
		const isAdd = num > playState.playWindows.length;
		if (isAdd) {
			setPlayState((preState) => ({
				...preState,
				playWindows: Array(num)
					.fill({})
					.map((element, index) => {
						return preState.playWindows[index] || { id: Math.random() };
					}),
			}));
		} else {
			setPlayState((preState) => {
				// 将正在播放得放前面去
				const playWindows = preState.playWindows.sort((element) => {
					if (!!element.liveUrls) {
						return -1;
					}
					return 0;
				});
				// 取前面得n个
				return {
					...preState,
					playWindows: playWindows.slice(0, num),
				};
			});
		}
	};
	/**
	 * @description 切换选中的播放视频
	 * @param record
	 */
	const handleCheckPlayWindow = (sn: number) => {
		setPlayState((preState) => ({
			...preState,
			playWindows: preState.playWindows.map((element, index) => {
				return {
					...element,
					windowChecked: index === sn,
				};
			}),
		}));
	};
	//选择 通道
	const handlePlayVideo = (record: ChanleProps) => {
		//判断 这个通道是否已经在播放列表中
		const isExit = playState.playWindows.some((element) => {
			return element && element.id === record.id;
		});
		//如果在，则将这个窗口选中
		if (isExit) {
			setPlayState((preState) => ({
				...preState,
				playWindows: preState.playWindows.map((element) => {
					if (element && element.id === record.id) {
						return { ...element, windowChecked: true };
					}
					return { ...element, windowChecked: false };
				}),
			}));
			return;
		}
		// 如果不在(则判断当前哪个播放窗口被选中，的如果没有则找一个空的插入)
		let checkedWindowIndex = playState.playWindows.findIndex(
			(element) => element.windowChecked
		);
		//如果有选中的就替换这个选中
		if (checkedWindowIndex !== -1) {
			setPlayState((preState) => ({
				...preState,
				playWindows: preState.playWindows.map((element, index) => {
					if (checkedWindowIndex === index) {
						return { ...record, windowChecked: true };
					}
					return element;
				}),
			}));
			// 如果没有选中的话则，找一个空的插入,并将这个元素选中
		} else {
			let emptyIndex = playState.playWindows.findIndex(
				(element) => !element.id
			);
			setPlayState((preState) => ({
				...preState,
				playWindows: preState.playWindows.map((element, index) => {
					if (index === emptyIndex) {
						return { ...record, windowChecked: true };
					}
					return { ...element, windowChecked: false };
				}),
			}));
		}

		requestChanleLiveUrl({ channel_no: record.channel_no })
			.then((data) => {
				setPlayState((preState) => {
					const willChangeList = preState.playWindows.map((element) => {
						if (element && element.id === record.id) {
							return {
								...element,
								liveUrls: data,
							};
						}
						return element;
					});
					return {
						...preState,
						playWindows: willChangeList,
					};
				});
			})
			.catch((error) => {
				message.error(error.message);
			});
	};

	/**
	 * @description 请求更多通道列表
	 * @param page 页码
	 */
	const handleLoadMoreVideoList = (page: number) => {
		requestChanleList({
			page: page,
			channel_no: state.filter,
		});
	};
	const requestContollerChekcedVideo = (params: {
		ptz_type?: PTzParmas['ptz_type'];
		ptz_param?: PTzParmas['ptz_param'];
	}) => {
		const isPlayWindow = playState.playWindows.find((element) => {
			return element && element.liveUrls && element.windowChecked;
		});
		if (!isPlayWindow) {
			return;
		}
		requestControllerVideo({
			ptz_param: ptzState.silderNum,
			channel_no: isPlayWindow.channel_no as string,
			...params,
		}).catch((error) => {
			message.error(error.message);
		});
	};
	return (
		<div className='video-wrapper'>
			<div className='video-controller-wrapper'>
				<BoxWrapper title='直播' className='video-list-wrapper'>
					<div className='video-list-content'>
						<div className='video-search-wrapper'>
							<input
								type='text'
								className='video-search-input'
								placeholder='请输入关键字搜索'
								value={state.filter}
								onChange={(event) => {
									event.persist();
									setState((preState) => ({
										...preState,
										filter: event.target.value,
										page: 1,
									}));
								}}
							/>
						</div>
						<div className='video-list-table'>
							<InfiniteScroll
								pageStart={chanleListState.preParams.page}
								threshold={100}
								initialLoad={false}
								useWindow={false}
								loadMore={handleLoadMoreVideoList}
								hasMore={!chanleListState.loading && chanleListState.hasMore}>
								{chanleListState.dataSource.map((element) => {
									return (
										<div
											className='chanle-record'
											key={element.id}
											onClick={() => {
												if (
													element.state === chanleStatus.online &&
													!element.checked
												) {
													handlePlayVideo(element);
												}
											}}
											data-online={element.state === chanleStatus.online}>
											<span>{element.name}</span>
										</div>
									);
								})}
							</InfiniteScroll>
						</div>
					</div>
				</BoxWrapper>
				<BoxWrapper title='云台控制' className='video-setUp-controller'>
					<div className='video-setUp-content'>
						<div className='video-basic-wrapper'>
							<div className='setup-wrapper'>
								{[
									{
										value: 0,
										type: 'up',
									},
									{
										value: 45,
										type: 'rightup',
									},
									{
										value: 90,
										type: 'right',
									},
									{
										value: 135,
										type: 'rightdown',
									},
									{
										value: 180,
										type: 'down',
									},
									{
										value: 225,
										type: 'leftdown',
									},
									{
										value: 270,
										type: 'left',
									},
									{
										value: 315,
										type: 'leftup',
									},
								].map((element) => {
									return (
										<div
											data-roate={element.value}
											className='video-arrow'
											key={element.type}
											onClick={() => {
												requestContollerChekcedVideo({
													ptz_type: element.type as any,
												});
											}}>
											<CaretUpOutlined></CaretUpOutlined>
										</div>
									);
								})}
								<button
									className='setup-stop'
									onClick={() => {
										requestContollerChekcedVideo({ ptz_type: 'stop' });
									}}>
									<PauseOutlined></PauseOutlined>
								</button>
							</div>
							<div className='video-sensitive-wrapper'>
								<div>
									<button
										onClick={() => {
											requestContollerChekcedVideo({ ptz_type: 'zoomin' });
										}}>
										<PlusOutlined></PlusOutlined>
									</button>
									<span className='video-sensitive-text'>变倍</span>
									<button
										onClick={() => {
											requestContollerChekcedVideo({ ptz_type: 'zoomout' });
										}}>
										<MinusOutlined></MinusOutlined>
									</button>
								</div>
								<div>
									<button
										onClick={() => {
											requestContollerChekcedVideo({ ptz_type: 'focusnear' });
										}}>
										<PlusOutlined></PlusOutlined>
									</button>
									<span className='video-sensitive-text'>聚焦</span>
									<button
										onClick={() => {
											requestContollerChekcedVideo({ ptz_type: 'focusfar' });
										}}>
										<MinusOutlined></MinusOutlined>
									</button>
								</div>
							</div>
						</div>
						<div className='video-rotating-set'>
							<p>云台转速</p>
							<Slider
								max={255}
								min={1}
								onChange={(value: number) => {
									handleChangePtzState((preState) => ({
										...preState,
										silderNum: value,
									}));
								}}
								className='video-rotating-slider'
								defaultValue={ptzState.silderNum}
							/>
						</div>
						<div className='video-position-wrapper'>
							<p>预置位</p>
							<Select
								defaultValue={ptzState.position}
								placeholder='请选择'
								className='video-position-select'
								dropdownClassName='video-position-dropdownselect'
								onChange={(value) => {
									handleChangePtzState((preState) => ({
										...preState,
										position: value,
									}));
								}}>
								{[1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map((element) => {
									return (
										<Option value={element} key={element}>
											{element}
										</Option>
									);
								})}
							</Select>
							<div
								className='video-setUp-btn video-btn'
								title='设置'
								onClick={() => {
									requestContollerChekcedVideo({
										ptz_type: 'setpos',
										ptz_param: ptzState.position,
									});
								}}></div>
							<div
								className='video-get-btn video-btn'
								title='调取'
								onClick={() => {
									requestContollerChekcedVideo({
										ptz_type: 'callpos',
										ptz_param: ptzState.position,
									});
								}}></div>
							<div
								className='video-remove-btn video-btn'
								title='删除'
								onClick={() => {
									requestContollerChekcedVideo({
										ptz_type: 'delpos',
										ptz_param: ptzState.position,
									});
								}}></div>
						</div>
					</div>
				</BoxWrapper>
			</div>
			<div className='video-show-wrapper'>
				<div
					className='video-window-wrapper'
					data-views={playState.playWindows.length}>
					{playState.playWindows.map((element, index) => {
						return (
							<div className='video-window-item' key={element.id}>
								<VideoPlayer
									checked={element.windowChecked}
									onClick={() => handleCheckPlayWindow(index)}
									sessionid={element.liveUrls?.sessionid || ''}
									autoplay
									controls
									sources={
										element.liveUrls
											? [
													{
														type: 'application/x-mpegURL',
														src: element.liveUrls?.hlsurl || '',
													},
													{
														type: 'rtmp/flv',
														src: element.liveUrls?.rtmpurl || '',
													},
											  ]
											: undefined
									}></VideoPlayer>
							</div>
						);
					})}
				</div>
				<div className='video-window-controller'>
					{controllerViews.map((element) => {
						return (
							<div
								data-checked={playState.playWindows.length === element.view}
								onClick={() => changeVidowWindow(element.view)}
								key={element.view}
								style={{ backgroundImage: `URL(${element.icon})` }}></div>
						);
					})}
				</div>
			</div>
		</div>
	);
};
export default videos;
