import React, { useState } from "react";

import MyDialog from "@/components/mui/MyDialog";
import { useMessage } from "@/components/MySnackbar";
import CloudEController from "@/api/fileserver/CloudEController";
import MySelect from "@/components/mui/MySelect";

type IDownloadProps = {
	type: string;
	projectId: string;
	token: string;
	fileToken: string;
	path: string;
	name: string;
	selectIds: Array<any>;
	open: boolean;
	setOpen: any;
};

const flieTypeMap = {
	SMILES: ".smi",
	SD: ".sdf",
	PDB: ".pdb",
	MOL: ".mol",
	MOL2: ".mol2",
};

const Download = (props: IDownloadProps) => {
	const {
		type,
		path,
		projectId,
		token,
		fileToken,
		selectIds,
		name,
		open,
		setOpen,
	} = props;
	const Message = useMessage();
	const [downloadType, setDownloadType] = useState("SMILES");
	const options = [
		{
			label: "SMILES",
			value: "SMILES",
		},
		{
			label: "SD",
			value: "SD",
		},
		{
			label: "PDB",
			value: "PDB",
		},
		{
			label: "MOL",
			value: "MOL",
		},
		{
			label: "MOL2",
			value: "MOL2",
		},
	];

	const handleChange = (e: any) => {
		setDownloadType(e);
	};

	const handleSubmit = () => {
		CloudEController.DownloadDatasetItems({
			type: type,
			projectId: projectId,
			token: token,
			filetoken: fileToken,
			name: name,
			path: path,
			id: selectIds.join(","),
			downloadType: downloadType,
		})
			?.then((res) => {
				// @ts-ignore
				const filename = `${name}${flieTypeMap[downloadType]}`;
				CloudEController.FunDownload(res.data, filename);
				setOpen(false);
			})
			?.catch((error) => {
				console.log(error);
				Message.error(error?.response?.data?.message || "文件服务发生错误!");
			});
	};

	return (
		<>
			<MyDialog
				open={open}
				onClose={() => setOpen(false)}
				onConfirm={handleSubmit}
				title="下载"
			>
				<div style={{ padding: "20px 0" }}>
					<MySelect
						value={downloadType}
						options={options}
						onChange={(e) => handleChange(e)}
						title="下载格式"
						isTitle={true}
						sx={{
							width: "388px",
						}}
					></MySelect>
				</div>
			</MyDialog>
		</>
	);
};

export default Download;
