import React, { useState, useCallback, useMemo, useEffect } from "react";
import classnames from "classnames";
import { observer } from "mobx-react";
import { toJS } from "mobx";
import { useDropzone } from "react-dropzone";

import style from "./index.module.css";
import MyDialog from "@/components/mui/MyDialog";
import { uuid } from "@/utils/util";
import { useMessage } from "@/components/MySnackbar";
import MyTable from "@/components/mui/MyTable";
import fileIcon from "@/assets/project/fileIcon.svg";
import noFile from "@/assets/project/noFile.svg";
import uploaderIcon from "@/assets/project/uploaderIcon.svg";
import { storageUnitFromB } from "@/utils/util";
import { useStores } from "@/store";
import useGlobalStore from "@/hooks/useGlobalStore";
import { APIOPTION, urlToken } from "@/api/fileserver/raysyncApi";
import UseTusUpload from "@/utils/Upload/tusUpload";
import MyButton from "@/components/mui/MyButton";

type IMoveFileProps = {
	uploaderDialogOpen: any;
	setUploaderDialogOpen: any;
	path: string;
	list: Array<any>;
};

const UpLoaderFile = observer((props: IMoveFileProps) => {
	const { path, list, uploaderDialogOpen, setUploaderDialogOpen } = props;
	const { fileListStore } = useStores();
	const message = useMessage();

	const [fileList, setFileList] = useState<any>([]);
	// list 是项目数据table的数据

	// 集合当前路径下的文件、文件夹、数据集   和已选择要上传的文件列表
	const nowNameList = useMemo(() => {
		return [...list, ...fileList];
	}, [list, fileList]);

	const currentProjectStore = toJS(useGlobalStore("currentProjectStore"));
	const uploadInfoStore = toJS(useGlobalStore("fileListStore"));
	const { uploadFile } = UseTusUpload(uploadInfoStore);

	const onDrop = useCallback(
		(acceptedFiles: any) => {
			// 获取重复的项目文件列表和要上传（名称不重复就上传）的文件
			const getRepeatFileAndGetUploderFileList = (
				acceptedFiles: Array<any>
			) => {
				let repeatFileList: any = [];
				let uploderFileList: any = [];
				acceptedFiles.forEach((fItem: any, index: number) => {
					if (
						nowNameList.some((nItem: any) => {
							return nItem.name === fItem.name;
						})
					) {
						repeatFileList.push(acceptedFiles[index]);
					} else {
						uploderFileList.push(acceptedFiles[index]);
					}
				});
				return {
					repeatFileList,
					uploderFileList,
				};
			};
			const repeatAndUploaderFileList =
				getRepeatFileAndGetUploderFileList(acceptedFiles);
			if (repeatAndUploaderFileList.repeatFileList.length > 0) {
				message.error(
					`“${repeatAndUploaderFileList.repeatFileList
						.map((i: any) => i.name)
						.join("、")}”文件已存在`
				);
			}

			// 插入新的文件列表
			const popLength = 10 - fileList.length;
			if (
				fileList.length + repeatAndUploaderFileList.uploderFileList.length >
				10
			) {
				message.error("最大支持同时上传10个文件");
			}
			let newFileList = [
				...repeatAndUploaderFileList.uploderFileList.slice(0, popLength),
				...fileList,
			];
			setFileList(newFileList);
		},
		[fileList, message, nowNameList]
	);

	const { getRootProps, getInputProps, isDragActive } = useDropzone({ onDrop });

	const getFileToken = useCallback(
		(newFileList: any) => {
			let url =
				APIOPTION() +
				"/parallelupload/" +
				urlToken(
					currentProjectStore?.currentProjectInfo?.filetoken || "",
					currentProjectStore?.currentProjectInfo?.id as string
				);

			newFileList?.forEach((item: any) => {
				uploadFile(
					item,
					item?.file,
					url,
					currentProjectStore?.currentProjectInfo?.filetoken || "",
					`${path}/${item?.file?.name}`
				);
			});
		},
		[
			currentProjectStore?.currentProjectInfo?.filetoken,
			currentProjectStore?.currentProjectInfo?.id,
			path,
			uploadFile,
		]
	);

	const handleSubmit = () => {
		const newFileList =
			fileList?.map((item: any) => {
				return {
					id: uuid(),
					path,
					list: [],
					file: item,
				};
			}) || [];
		toJS(fileListStore?.setNewFileList)(newFileList);
		if (newFileList?.length) {
			getFileToken(newFileList);
		}
		setUploaderDialogOpen(false);
	};

	useEffect(() => {
		if (uploaderDialogOpen) {
			setFileList([]);
		}
	}, [uploaderDialogOpen]);

	const fileListHeadCells = [
		{ id: "name", numeric: false, label: "名称", width: "60%" },
		{ id: "size", numeric: false, label: "大小", width: "25%" },
		{ id: "caozuo", numeric: false, label: "操作", width: "15%" },
	];

	const renderName = (item: any) => {
		return (
			<span className={style.fileIconBox}>
				<img className={style.fileIcon} src={fileIcon} alt="" />
				<span className={style.fileIconBoxText}>{item.name}</span>
			</span>
		);
	};
	const renderSize = (item: any) => {
		return <span>{item.size ? storageUnitFromB(Number(item.size)) : "-"}</span>;
	};

	const handleRowDelete = (index: number) => {
		fileList.splice(index, 1);
		setFileList([...fileList]);
	};

	const renderButtons = (item: any, index: number) => {
		return (
				<MyButton
					text='删除'
					style={{ position: "relative", left: "-18px" }}
					variant="text"
					size="small"
					color="error"
					onClick={() => handleRowDelete(index)}
				/>
		);
	};

	return (
		<MyDialog
			title="上传文件"
			okText="开始上传"
			showCancel={false}
			open={uploaderDialogOpen}
			onClose={() => setUploaderDialogOpen(false)}
			onConfirm={handleSubmit}
		>
			<div className={style.uploderBox}>
				<div className={style.uploderBoxLeft}>
					<div className={style.dropTitle}>添加文件</div>
					<div
						{...getRootProps()}
						className={classnames({
							[style.dropBox]: true,
							[style.dropBoxDragActive]: isDragActive,
						})}
					>
						<input {...getInputProps()} multiple />
						<img className={style.uploaderIcon} src={uploaderIcon} alt="" />
						<div className={style.uploderText1}>
							点击添加文件或将文件拖到此处添加
						</div>
						<div className={style.uploderText2}>一次最多添加10个文件</div>
					</div>
				</div>
				<div className={style.fileListBox}>
					<div className={style.dropTitle}>
						已添加文件
						<span
							className={classnames({
								[style.red]: fileList.length >= 10,
							})}
						>
							（{fileList.length}/10）
						</span>
					</div>
					<div className={style.tableBox}>
						<MyTable
							rowHover={true}
							stickyHeader={true}
							rows={fileList.map((item: any, index: number) => ({
								...item,
								name: renderName(item),
								size: renderSize(item),
								caozuo: renderButtons(item, index),
							}))}
							rowsPerPage={"99"}
							headCells={fileListHeadCells}
							footer={false}
							// headTableCellStyle={{
							// 	fontSize: "12px",
							// 	lineHeight: "20px",
							// 	color: "#8A9099",
							// }}
							tableContainerStyle={{
								maxHeight: "300px",
							}}
						/>
					</div>
					{fileList.length === 0 && (
						<div className={style.noFile}>
							<img className={style.noFileIcon} src={noFile} alt="" />
							<span className={style.noFileText}>暂无添加文件</span>
						</div>
					)}
				</div>
			</div>
		</MyDialog>
	);
});

export default UpLoaderFile;
