import * as React from 'react';
import moment, { Moment } from 'moment';
import VideoPlayer from '../../compontens/videoPlayer';
import InfiniteScroll from 'react-infinite-scroller';
import BoxWrapper from '../../compontens/box';
import DataStatistics from './components/data-statistics';
import {
	DeviceState,
	DeviceStateString,
	useEnvironmentalDevicesList,
	useDeviceHistoryData,
	useEnvironmentalDeviceInfo,
	useDeviceAqiData,
} from '../../hooks/environmental';
import { useWarningList } from '../../hooks/device';
import {
	useChanleLiveUrl,
	useDeviceChanles,
	chanleStatus,
} from '../../hooks/video';
import './index.scss';
type DataStatisticType = 'pm25' | 'pm10' | 'b03';
const dataStatisticType: {
	text: string;
	key: DataStatisticType;
	unit: string;
}[] = [
	{ text: 'pm2.5', key: 'pm25', unit: 'μg/m³' },
	{ text: 'pm10', key: 'pm10', unit: 'μg/m³' },
	{ text: '噪音', key: 'b03', unit: 'dB' },
];
const Max_Aqi = 500;
//aqi旋转系数
const roatecoefficient = (315 - 45) / Max_Aqi;
const Environmental: React.FC = (props) => {
	//小时控制
	const [hoursState, setHoursState] = React.useState<{
		time: Moment;
		type: DataStatisticType;
	}>({
		time: moment(),
		type: 'pm25',
	});
	//天控制
	const [dayState, setDayState] = React.useState<{
		time: Moment;
		type: DataStatisticType;
	}>({
		time: moment(),
		type: 'pm25',
	});
	//月控制
	const [monthState, setMonthState] = React.useState<{
		time: Moment;
		type: DataStatisticType;
	}>({
		time: moment(),
		type: 'pm25',
	});

	//设备列表
	const [
		devicesState,
		changeListState,
		requestDevices,
	] = useEnvironmentalDevicesList();
	// 请求设备信息
	const [deviceInfoState, requestDevicesInfo] = useEnvironmentalDeviceInfo();
	// 预警信息
	const [warningListState, requestWarningList] = useWarningList();

	// 获取设备下的通道
	const [chanleState, requestChanle] = useDeviceChanles();
	// 直播地址
	const [liveUrlState, requestLiveUrl] = useChanleLiveUrl();
	const [aqiState, requestAqi] = useDeviceAqiData();

	// 设备历史数据(分钟)
	const [
		historyHoursDataState,
		requestHoursHistoryData,
	] = useDeviceHistoryData();
	// 设备历史数据(小时)
	const [historyDayDataState, requestDayHistoryData] = useDeviceHistoryData();
	// 设备历史数据(天)
	const [
		historyMonthDataState,
		requestMonthHistoryData,
	] = useDeviceHistoryData();

	React.useEffect(() => {
		requestDevices();
	}, []);
	/**
	 *
	 * @param record
	 * @description 切换选中的设备
	 */
	const handleChangeDevice = (record) => {
		changeListState((preState) => ({
			...preState,
			dataSource: {
				...preState.dataSource,
				list: preState.dataSource.list.map((element) => {
					return { ...element, checked: element.id === record.id };
				}),
			},
		}));
	};
	// 计算当前选中的元素
	const currentDevice = devicesState.dataSource.list.find((record) => {
		return !!record.checked;
	});

	React.useEffect(() => {
		if (currentDevice) {
			requestDevicesInfo({ sn: currentDevice.sn });
			requestWarningList({
				sn: currentDevice.sn,
				page: 1,
				filter: 0,
				page_size: 10,
			});
			requestAqi({ sn: currentDevice.sn });
			if (currentDevice.state === chanleStatus.online) {
				requestChanle({ sn: currentDevice.sn });
			}
		}
	}, [currentDevice]);
	//监听通道变化
	React.useEffect(() => {
		if (chanleState.dataSource.state === chanleStatus.online) {
			requestLiveUrl({ channel_no: chanleState.dataSource.channel_no });
		}
	}, [chanleState.dataSource.channel_no]);
	// 请求小时数据
	React.useEffect(() => {
		if (!!currentDevice) {
			requestHoursHistoryData({
				type: 0,
				sn: currentDevice.sn,
				time: hoursState.time.set('minute', 0).unix(),
			});
		}
	}, [currentDevice, hoursState.time]);
	// 请求天数据
	React.useEffect(() => {
		if (!!currentDevice) {
			requestDayHistoryData({
				type: 1,
				sn: currentDevice.sn,
				time: dayState.time
					.set('hours', 0)
					.set('minute', 0)
					.set('second', 0)
					.set('millisecond', 0)
					.unix(),
			});
		}
	}, [currentDevice, dayState.time]);
	//请求月数据
	React.useEffect(() => {
		if (!!currentDevice) {
			requestMonthHistoryData({
				type: 2,
				sn: currentDevice.sn,
				time: monthState.time
					.set('date', 1)
					.set('hours', 0)
					.set('minute', 0)
					.set('second', 0)
					.set('millisecond', 0)
					.unix(),
			});
		}
	}, [currentDevice, monthState.time]);

	const handleChangeState = (
		value: { time?: Moment; type?: DataStatisticType },
		stateType: 'hours' | 'day' | 'month'
	) => {
		switch (stateType) {
			case 'hours':
				setHoursState((preState) => ({ ...preState, ...value }));
				break;
			case 'day':
				setDayState((preState) => ({ ...preState, ...value }));
				break;
			default:
				setMonthState((preState) => ({ ...preState, ...value }));
		}
	};
	const onAsyncLoadWarningList = (page: number) => {
		if (currentDevice) {
			requestWarningList({
				page: page,
				filter: 0,
				sn: currentDevice.sn,
			});
		}
	};
	return (
		<div className='environmental-wrapper'>
			<div className='environmental-left'>
				<BoxWrapper
					title='设备列表'
					className='environmental-devices-wrapper'
					titleMore={
						<div className='devices-title-info'>
							<div>
								在线设备： <span>{devicesState.dataSource.online}</span>台
							</div>
							<div>
								离线设备：<span>{devicesState.dataSource.offline}</span>台
							</div>
						</div>
					}>
					<div className='devices-table-wrapper'>
						<div className='devices-table-header'>
							<div>设备名称</div>
							<div>状态</div>
						</div>
						<div className='devices-table-body'>
							{devicesState.dataSource.list.map((element) => {
								return (
									<div
										data-checked={element.checked}
										className='devices-record-wrapper'
										key={element.id}
										onClick={() => handleChangeDevice(element)}>
										<div>{element.name}</div>
										<div data-online={DeviceState.onLine === element.state}>
											{DeviceStateString[element.state]}
										</div>
									</div>
								);
							})}
						</div>
					</div>
				</BoxWrapper>
				<BoxWrapper title='AQI指数' className='aqi-wrapper'>
					<div className='aqi-content'>
						<div className='aqi-chart-content'>
							<div
								className='aqi-pointer-wrapper'
								style={{
									transform: ` translate(-50%, 0) rotate(${
										aqiState.dataSource.aqi * roatecoefficient + 45
									}deg)`,
								}}>
								<div className='aqi-pointer'></div>
							</div>
							<span>{aqiState.dataSource.aqi}</span>
						</div>
					</div>
				</BoxWrapper>
			</div>
			<div className='environmental-center'>
				{[
					{
						type: 'hours',
						dataState: historyHoursDataState,
						localState: hoursState,
					},
					{
						type: 'day',
						dataState: historyDayDataState,
						localState: dayState,
					},
					{
						type: 'month',
						dataState: historyMonthDataState,
						localState: monthState,
					},
				].map((box) => {
					const unit = dataStatisticType.find((item) => {
						return item.key === box.localState.type;
					})?.unit;
					return (
						<BoxWrapper
							key={box.type}
							title='数据统计'
							className='data-Statistics-wrapper'
							titleMore={
								<div className='data-statistics-controller'>
									{dataStatisticType.map((element) => {
										return (
											<span
												onClick={() => {
													handleChangeState(
														{ type: element.key },
														box.type as any
													);
												}}
												key={element.key}
												data-checked={box.localState.type === element.key}>
												{element.text}
											</span>
										);
									})}
								</div>
							}>
							<div className='data-statistics-content'>
								<DataStatistics
									unit={unit}
									defaultTime={box.localState.time}
									onChangeDate={(value, dateString) => {
										console.log('value', value);
										handleChangeState(
											{ time: value as Moment },
											box.type as any
										);
									}}
									dateType={box.type as any}
									dataSource={{
										xAxisData: box.dataState.dataSource.list.map(
											(element) => element.date
										),
										yAxisData: box.dataState.dataSource.list.map(
											(element) => element[box.localState.type]
										),
									}}
									className='data-statistics-charts'></DataStatistics>
							</div>
						</BoxWrapper>
					);
				})}
			</div>
			<div className='environmental-right'>
				<div className='environmental-device-live-wrapper'>
					<VideoPlayer
						autoplay
						controls
						sessionid={liveUrlState.dataSource.sessionid}
						sources={
							liveUrlState.dataSource.hlsurl
								? [
										{
											type: 'application/x-mpegURL',
											src: liveUrlState.dataSource.hlsurl,
										},
										{
											type: 'rtmp/flv',
											src: liveUrlState.dataSource.rtmpurl,
										},
								  ]
								: undefined
						}></VideoPlayer>
				</div>
				<div className='environmental-monitor-wrapper '>
					{[
						{ name: 'PM2.5', unit: 'μg/m³', key: 'pm25' },
						{ name: 'pm10', unit: 'μg/m³', key: 'pm10' },
						{ name: '噪音', unit: 'dB', key: 'b03' },
						{ name: '湿度', unit: '%', key: 'h01' },
						{ name: '风速', unit: 'm/s', key: 'w02' },
						{ name: 'TSP', unit: 'μg/m³', key: 'tsp' },
						{ name: '雨量', unit: 'μg/m²', key: 'r01' },
						{ name: '温度', unit: '℃', key: 't01' },
						{ name: '风向', unit: '°', key: 'w01' },
					].map((element) => {
						return (
							<div key={element.key} className='monitor-record-wrapper'>
								<span className='monitor-data-name'>{element.name}</span>
								<div>
									<span className='monitor-data-num'>
										{deviceInfoState.dataSource[element.key]}
									</span>
									{element.unit}
								</div>
							</div>
						);
					})}
				</div>
				<BoxWrapper title='预警信息' className='environmental-wraning-wrapper'>
					<div className='wraning-content'>
						<InfiniteScroll
							pageStart={1}
							hasMore={!warningListState.loading && warningListState.hasMore}
							initialLoad={false}
							useWindow={false}
							loadMore={(page) => {
								console.log('加载');
								onAsyncLoadWarningList(page);
							}}>
							{warningListState.dataSource.map((element) => {
								return (
									<div className='warning-record-wrapper' key={element.id}>
										<div className='warning-record-head'>
											<p>{element.name}</p>
											<p>{element.time}</p>
										</div>
										<div className='warning-record-reason'>
											{element.reason}
										</div>
									</div>
								);
							})}
						</InfiniteScroll>
					</div>
				</BoxWrapper>
			</div>
		</div>
	);
};
export default Environmental;
