import React, { useImperativeHandle, useMemo } from "react";

import MyDialog from "@/components/mui/MyDialog";
import { useMessage } from "@/components/MySnackbar";
import { getDataFileDelPackage } from "@/api/project_api";
import useMyRequest from "@/hooks/useMyRequest";

const DeleteDialog = (props: any) => {
	const { path, projectId, currentOperateFile, selectIds, refresh, showList } =
		props;
	const Message = useMessage();
	let deleteFileDialogRef: any = React.createRef();
	const showDialog = () => {
		deleteFileDialogRef.current.handleClickOpen();
	};

	useImperativeHandle(props.onRef, () => {
		return {
			showDialog: showDialog,
		};
	});

	const { run: getDataFileDelPackageRun } = useMyRequest(
		getDataFileDelPackage,
		{
			onSuccess: (res: any) => {
				Message.success("删除成功！");
				deleteFileDialogRef?.current?.handleClose();
				refresh();
			},
		}
	);

	const deletePath = useMemo(() => {
		return path === "/" ? "/" : `${path}/`;
	}, [path]);

	// 要删除的文件数组
	const deleteList = useMemo(() => {
		if (currentOperateFile) {
			return [currentOperateFile];
		} else {
			return showList.filter((item: any) => {
				return selectIds.indexOf(item.name) !== -1;
			});
		}
	}, [currentOperateFile, selectIds, showList]);

	const packageNames = useMemo(() => {
		return deleteList
			.filter((item: any) => {
				return item.type !== "dataSet";
			})
			.map((item: any) => item.name)
			.join(",");
	}, [deleteList]);

	const dataSetNames = useMemo(() => {
		return deleteList
			.filter((item: any) => {
				return item.type === "dataSet";
			})
			.map((item: any) => item.name)
			.join(",");
	}, [deleteList]);

	// 删除
	const handleSubmit = () => {
		getDataFileDelPackageRun({
			projectId,
			packageNames,
			dataSetNames,
			path: deletePath,
		});
	};
	const submitloading = false;

	return (
		<MyDialog
			handleSubmit={handleSubmit}
			onRef={deleteFileDialogRef}
			title="提示"
			submitloading={submitloading}
		>
			{currentOperateFile
				? "确认删除该数据吗？"
				: `确认删除这${selectIds.length}条数据吗？`}
		</MyDialog>
	);
};

export default DeleteDialog;
