/** @format */
import React, { memo, useEffect, useState } from "react";
import { Avatar, Card, Flex, message, Skeleton, Tooltip } from "antd";
import styles from "./index.module.less";
import ReactECharts from "echarts-for-react";
import { ProCard, ProList } from "@ant-design/pro-components";
import storage from "@/assets/icons/storage.svg";
import bucket from "@/assets/icons/bucket.svg";
import file from "@/assets/icons/file.svg";
import flux from "@/assets/icons/flux.svg";
import CalendarHeatmap from "react-calendar-heatmap";
import "react-calendar-heatmap/dist/styles.css";
import upload from "@/assets/icons/upload.svg";
import download from "@/assets/icons/download.svg";
import {
	getStorageAndBuckets,
	getUserDownloadFileDiagramPerMonth,
	getUserFileCount,
	getUserFileFlow,
	getUserFileHeatMap,
	getUserRecentPreviewFile,
	getUserRecentUploadFile,
	getUserUploadFileDiagramPerMonth,
} from "@/api/oss";
import { useNavigate } from "react-router-dom";
import { InfoCircleOutlined } from "@ant-design/icons";
import FileIcon from "@/constant/file-icon.ts";
import file_icon from "@/assets/icons/files/file.svg";
import { observer } from "mobx-react";
import useStore from "@/utils/store/useStore.tsx";

const MainHome: React.FC = observer(() => {
	const navigate = useNavigate();
	const [loading, setLoading] = useState(true);
	const [loadingEChart, setLoadingEChart] = useState(true);
	const [loadingHeatmap, setLoadingHeatmap] = useState(true);
	const [loadingRecentFile, setLoadingRecentFile] = useState(true);
	const [loadingPreviewFile, setLoadingPreviewFile] = useState(true);
	const [storageCount, setStorageCount] = useState<any>(null);
	const [bucketCount, setBucketCount] = useState<any>(null);
	const [fileHeatmap, setFileHeatmap] = useState<any>([]);
	const [downloadFlow, setDownloadFlow] = useState<any>(null);
	const [uploadFlow, setUploadFlow] = useState<any>(null);
	const [uploadFile, setUploadFile] = useState<any>(null);
	const [downloadFile, setDownloadFile] = useState<any>(null);
	const [monthUpload, setMonthUpload] = useState<any>([]);
	const [monthDownload, setMonthDownload] = useState<any>([]);
	const [recentUploadFile, setRecentUploadFile] = useState<any>([]);
	// const [recentDownloadFile, setRecentDownloadFile] = useState<any>([]);
	const [recentPreviewFile, setRecentPreviewFile] = useState<any>([]);
	const userStore = useStore("user");
	const userId: any = userStore.getUserId();
	// 获取存储同和存储商的个数
	async function getStorageAndBucketsCount() {
		return getStorageAndBuckets(userId).then((res: any) => {
			if (res && res.success && res.data) {
				const from: any = Array.from(res.data);
				setStorageCount(from.length);
				const count = from.reduce(
					(count: any, item: any) => (count += item.bucketCount),
					0,
				);
				setBucketCount(count);
			}
		});
	}
	// 获取文件上传热力图
	async function getFileHeatMap() {
		return getUserFileHeatMap(userId).then((res: any) => {
			if (res && res.success && res.data) {
				setFileHeatmap(res.data.upload);
			}
		});
	}
	// 获取文件上传下载流量
	async function getUploadDownloadFlux() {
		return getUserFileFlow(userId).then((res: any) => {
			if (res && res.success && res.data) {
				setUploadFlow(res.data.uploadflow);
				setDownloadFlow(res.data.downloadflow);
			}
		});
	}
	// 获取文件上传下载个数
	async function getUploadDownloadCount() {
		return getUserFileCount(userId).then((res: any) => {
			if (res && res.success && res.data) {
				setUploadFile(res.data.upload);
				setDownloadFile(res.data.download);
			}
		});
	}
	// 获取每月用户下载数量
	async function getDownloadCountByMonth() {
		getUserDownloadFileDiagramPerMonth(userId).then((res: any) => {
			if (res && res.success && res.data) {
				setMonthDownload(res.data);
			}
		});
	}

	// 获取每月用户上传数量
	async function getUploadCountByMonth() {
		getUserUploadFileDiagramPerMonth(userId).then((res: any) => {
			if (res && res.success && res.data) {
				setMonthUpload(res.data);
			}
		});
	}
	// 获取用户最近上传文件
	async function getRecentUploadFile() {
		getUserRecentUploadFile(userId).then((res: any) => {
			if (res && res.success && res.data) {
				setRecentUploadFile(res.data);
			}
		});
	}
	//获取用户最近下载文件
	// async function getRecentDownloadFile() {
	// 	getUserRecentDownloadFile(userId).then((res: any) => {
	// 		if (res && res.success && res.data) {
	// 			setRecentDownloadFile(res.data);
	// 		}
	// 	});
	// }
	//获取用户最近预览文件
	async function getRecentPreviewFile() {
		getUserRecentPreviewFile(userId).then((res: any) => {
			if (res && res.success && res.data) {
				setRecentPreviewFile(res.data);
			}
		});
	}
	const option = {
		tooltip: {
			trigger: "axis",
		},
		legend: {
			color: ["#F58080", "#47D8BE", "#F9A589"],
			data: ["上传", "下载"],
			left: "center",
			bottom: "bottom",
		},
		grid: {
			top: "middle",
			left: "3%",
			right: "4%",
			bottom: "3%",
			height: "80%",
			containLabel: true,
		},
		xAxis: [
			{
				type: "time",
				// data: month,
				axisLine: {
					lineStyle: {
						color: "#999",
					},
				},
			},
		],
		yAxis: {
			type: "value",

			splitLine: {
				lineStyle: {
					type: "dashed",
					color: "#DDD",
				},
			},
			axisLine: {
				show: false,
				lineStyle: {
					color: "#333",
				},
			},
			nameTextStyle: {
				color: "#999",
			},
			splitArea: {
				show: false,
			},
		},
		series: [
			{
				name: "下载",
				type: "line",
				data: monthDownload,
				color: "#F58080",
				lineStyle: {
					width: 5,
					color: {
						type: "linear",

						colorStops: [
							{
								offset: 0,
								color: "#FFCAD4", // 0% 处的颜色
							},
							{
								offset: 0.4,
								color: "#F58080", // 100% 处的颜色
							},
							{
								offset: 1,
								color: "#F58080", // 100% 处的颜色
							},
						],
						globalCoord: false, // 缺省为 false
					},
					shadowColor: "rgba(245,128,128, 0.5)",
					shadowBlur: 10,
					shadowOffsetY: 7,
				},
				itemStyle: {
					color: "#F58080",
					borderWidth: 10,
					/*shadowColor: 'rgba(72,216,191, 0.3)',
					 shadowBlur: 100,*/
					borderColor: "#F58080",
				},
				smooth: true,
			},
			{
				name: "上传",
				type: "line",
				data: monthUpload,
				lineStyle: {
					width: 5,
					color: {
						type: "linear",

						colorStops: [
							{
								offset: 0,
								color: "#AAF487", // 0% 处的颜色
							},
							{
								offset: 0.4,
								color: "#47D8BE", // 100% 处的颜色
							},
							{
								offset: 1,
								color: "#47D8BE", // 100% 处的颜色
							},
						],
						globalCoord: false, // 缺省为 false
					},
					shadowColor: "rgba(71,216,190, 0.5)",
					shadowBlur: 10,
					shadowOffsetY: 7,
				},
				itemStyle: {
					color: "#AAF487",
					borderWidth: 10,
					/*shadowColor: 'rgba(72,216,191, 0.3)',
						 shadowBlur: 100,*/
					borderColor: "#AAF487",
				},
				smooth: true,
			},
		],
	};

	useEffect(() => {
		getStorageAndBucketsCount().then(() => {
			getUploadDownloadFlux().then(() => {
				getUploadDownloadCount().then(() => {
					setLoading(false);
				});
			});
		});
	}, []);

	useEffect(() => {
		getFileHeatMap().then(() => {
			setLoadingHeatmap(false);
		});
	}, []);

	useEffect(() => {
		getDownloadCountByMonth().then(() => {
			getUploadCountByMonth().then(() => {
				setLoadingEChart(false);
			});
		});
	}, []);

	useEffect(() => {
		getRecentUploadFile().then(() => {
			setLoadingRecentFile(false);
		});
		getRecentPreviewFile().then(() => {
			setLoadingPreviewFile(false);
		});
	}, []);
	function getFileExtension(filename: any): string {
		const dotIndex = filename.lastIndexOf(".");
		return dotIndex !== -1 ? filename.slice(dotIndex + 1) : "";
	}
	return (
		<>
			<div className={styles.home_content_main}>
				<div className={styles.home_content_head}>
					<div className={styles.home_content_head_left}>
						<Card
							style={{ width: "200px", height: "150px" }}
							loading={false}
							bordered
							hoverable>
							<Skeleton loading={loading} active avatar>
								<Flex vertical={true}>
									<Flex
										vertical={false}
										align={"center"}
										justify={"space-between"}>
										<Flex vertical={false} align={"center"}>
											<Avatar
												src={storage as any}
												shape={"square"}
												size={"large"}></Avatar>
											<span
												style={{
													marginLeft: 10,
													fontSize: 18,
													fontWeight: "bolder",
												}}>
												{" "}
												存储
											</span>
										</Flex>
										<Flex vertical={false} align={"center"}>
											<span style={{ fontSize: 15 }}>
												{
													<span
														style={{
															fontSize: 30,
															color: "coral",
															fontWeight: "bolder",
														}}>
														{storageCount || 0}
													</span>
												}
												/个
											</span>
										</Flex>
									</Flex>
									<Flex
										vertical={false}
										align={"center"}
										justify={"flex-end"}
										style={{ marginTop: 50 }}>
										<Tooltip
											title={"存储商个数，点击查看详情"}
											color={"#47D8BE"}>
											<InfoCircleOutlined
												onClick={() => {
													navigate("/main/setting");
												}}
												className={styles.home_content_icon}
											/>
										</Tooltip>
									</Flex>
								</Flex>
							</Skeleton>
						</Card>
						<Card
							style={{ width: "200px", height: "150px" }}
							loading={false}
							bordered
							hoverable>
							<Skeleton loading={loading} active avatar>
								<Flex vertical={true}>
									<Flex
										vertical={false}
										align={"center"}
										justify={"space-between"}>
										<Flex vertical={false} align={"center"}>
											<Avatar
												src={bucket as any}
												shape={"square"}
												size={"large"}></Avatar>
											<span
												style={{
													marginLeft: 10,
													fontSize: 18,
													fontWeight: "bolder",
												}}>
												{" "}
												存储桶
											</span>
										</Flex>
										<Flex vertical={false} align={"center"}>
											<span style={{ fontSize: 15 }}>
												{
													<span
														style={{
															fontSize: 30,
															color: "lightblue",
															fontWeight: "bolder",
														}}>
														{bucketCount || 0}
													</span>
												}
												/个
											</span>
										</Flex>
									</Flex>
									<Flex
										vertical={false}
										align={"center"}
										justify={"flex-end"}
										style={{ marginTop: 50 }}>
										<Tooltip
											title={"存储桶个数，点击查看详情"}
											color={"#47D8BE"}>
											<InfoCircleOutlined
												onClick={() => {
													navigate("/main/bucket");
												}}
												className={styles.home_content_icon}
											/>
										</Tooltip>
									</Flex>
								</Flex>
							</Skeleton>
						</Card>
						<Card
							style={{ width: "200px", height: "150px" }}
							loading={false}
							bordered
							hoverable>
							<Skeleton loading={loading} active avatar>
								<Flex vertical={true}>
									<Flex
										vertical={false}
										align={"center"}
										justify={"space-between"}>
										<Flex vertical={false} align={"center"}>
											<Avatar
												src={file as any}
												shape={"square"}
												size={"large"}></Avatar>
											<span
												style={{
													marginLeft: 10,
													fontSize: 18,
													fontWeight: "bolder",
												}}>
												{" "}
												文件
											</span>
										</Flex>
									</Flex>
									<Flex vertical={true} style={{ marginLeft: 8, marginTop: 10 }}>
										<Flex vertical={false} align={"center"}>
											<Avatar
												src={upload as any}
												shape={"square"}
												size={"small"}>
												{" "}
											</Avatar>
											<span
												style={{
													fontSize: 18,
													color: "orange",
													marginLeft: 5,
												}}>
												{uploadFile || 0}
											</span>
										</Flex>
										<Flex vertical={false} align={"center"}>
											<Avatar
												src={download as any}
												shape={"square"}
												size={"small"}>
												{" "}
											</Avatar>
											<span
												style={{
													fontSize: 18,
													color: "green",
													marginLeft: 5,
												}}>
												{downloadFile || 0}
											</span>
										</Flex>
									</Flex>
								</Flex>
							</Skeleton>
						</Card>
						<Card
							style={{ width: "200px", height: "150px" }}
							loading={false}
							bordered
							hoverable>
							<Skeleton loading={loading} active avatar>
								<Flex vertical={true}>
									<Flex
										vertical={false}
										align={"center"}
										justify={"space-between"}>
										<Flex vertical={false} align={"center"}>
											<Avatar
												src={flux as any}
												shape={"square"}
												size={"large"}></Avatar>
											<span
												style={{
													marginLeft: 10,
													fontSize: 18,
													fontWeight: "bolder",
												}}>
												{" "}
												流量
											</span>
										</Flex>
									</Flex>
									<Flex vertical={true} style={{ marginLeft: 8, marginTop: 10 }}>
										<Flex vertical={false} align={"center"}>
											<Avatar
												src={upload as any}
												shape={"square"}
												size={"small"}>
												{" "}
											</Avatar>
											<span
												style={{
													fontSize: 18,
													color: "orange",
													marginLeft: 5,
												}}>
												{uploadFlow || 0}
											</span>
										</Flex>
										<Flex vertical={false} align={"center"}>
											<Avatar
												src={download as any}
												shape={"square"}
												size={"small"}>
												{" "}
											</Avatar>
											<span
												style={{
													fontSize: 18,
													color: "green",
													marginLeft: 5,
												}}>
												{downloadFlow || 0}
											</span>
										</Flex>
									</Flex>
								</Flex>
							</Skeleton>
						</Card>
					</div>
					<div style={{ width: "55%" }}>
						<ProCard bordered boxShadow>
							<Skeleton
								loading={loadingEChart}
								active
								paragraph={{
									rows: 7,
								}}>
								<ReactECharts option={option} />
							</Skeleton>
						</ProCard>
					</div>
				</div>
				<div>
					<ProCard
						bordered
						boxShadow
						style={{
							marginTop: "30px",
						}}
						title={"文件上传热力图"}>
						<Skeleton
							loading={loadingHeatmap}
							active
							paragraph={{
								rows: 3,
							}}>
							<CalendarHeatmap
								startDate={new Date(`${new Date().getFullYear()}-01-01`)}
								endDate={new Date(`${new Date().getFullYear()}-12-31`)}
								showMonthLabels={true}
								horizontal={true}
								showWeekdayLabels={false}
								onClick={(value: any) => {
									if (value !== null) {
										message
											.open({
												content: (
													<>
														<Flex vertical={true}>
															<Flex vertical={false} align={"center"}>
																日期：{value.date}
															</Flex>
															<Flex vertical={false} align={"center"}>
																数量：{value.count}
															</Flex>
														</Flex>
													</>
												),
												type: "success",
												duration: 2,
											})
											.then();
									}
								}}
								monthLabels={[
									"一月",
									"二月",
									"三月",
									"四月",
									"五月",
									"六月",
									"七月",
									"八月",
									"九月",
									"十月",
									"十一月",
									"十二月",
								]}
								weekdayLabels={[
									"周日",
									"周一",
									"周二",
									"周三",
									"周四",
									"周五",
									"周六",
								]}
								gutterSize={3}
								values={fileHeatmap}></CalendarHeatmap>
						</Skeleton>
					</ProCard>
				</div>
				<div className={styles.home_content_list}>
					<ProCard bordered boxShadow style={{ width: "49%" }}>
						<Skeleton
							loading={loadingRecentFile}
							active
							paragraph={{
								rows: 8,
							}}>
							<ProList
								rowKey="id"
								headerTitle="最近上传文件"
								dataSource={recentUploadFile}
								metas={{
									title: {
										dataIndex: "fileName",
									},
									avatar: {
										render: (_: any, record: any) => {
											if (record.fileName) {
												return (
													<>
														<Avatar
															src={
																FileIcon[
																	getFileExtension(
																		record.fileName,
																	)
																] || file_icon
															}
															shape={"square"}
															size={"large"}
														/>
													</>
												);
											} else {
												return (
													<>
														<Avatar
															src={file_icon as any}
															shape={"square"}
															size={"large"}
														/>
													</>
												);
											}
										},
									},
									description: {
										dataIndex: "size",
										valueType: "text",
									},
									content: {
										dataIndex: "time",
									},
								}}
							/>
						</Skeleton>
					</ProCard>
					<ProCard bordered boxShadow style={{ width: "49%" }}>
						<Skeleton
							loading={loadingPreviewFile}
							active
							paragraph={{
								rows: 8,
							}}>
							<ProList
								rowKey="id"
								headerTitle="最近浏览文件"
								dataSource={recentPreviewFile}
								metas={{
									title: {
										dataIndex: "fileName",
									},
									avatar: {
										render: (_: any, record: any) => {
											if (record.fileName) {
												return (
													<>
														<Avatar
															src={
																FileIcon[
																	getFileExtension(
																		record.fileName,
																	)
																] || file_icon
															}
															shape={"square"}
															size={"large"}
														/>
													</>
												);
											} else {
												return (
													<>
														<Avatar
															src={file_icon as any}
															shape={"square"}
															size={"large"}
														/>
													</>
												);
											}
										},
									},
									description: {
										dataIndex: "size",
										valueType: "text",
									},
									content: {
										dataIndex: "time",
									},
								}}
							/>
						</Skeleton>
					</ProCard>
				</div>
			</div>
		</>
	);
});
export default memo(MainHome);
