import TreeView from "@mui/lab/TreeView";
import ArrowRightIcon from "@mui/icons-material/ArrowRight";
import ArrowDropDownIcon from "@mui/icons-material/ArrowDropDown";
import TreeItem from "@mui/lab/TreeItem";

interface TreeItemType {
	id: string;
	name: string;
	disabled?: boolean;
	subdirs?: readonly TreeItemType[];
}

type MyTreeViewProps = {
	treeData: Array<TreeItemType>;
	onNodeFocus?: (event: object, value: string) => void; // 点击某一项的回调
	onNodeSelect?: (event: object, value: Array<any> | string) => void; // 点击某一项的回调
	onNodeToggle?: (event: object, nodeIds: Array<any>) => void; // 点击某一项的回调
	renderLabel?: (node: any) => React.ReactNode;
	treeViewSx?: any;
	defaultExpanded?: Array<string>;
	idFunc?: (node: any) => string;
};

interface RenderTree {
	id: string | number;
	name: string;
	disabled?: boolean;
	subdirs?: readonly RenderTree[];
}

const MyTreeView = (props: MyTreeViewProps) => {
	const {
		treeData = [],
		renderLabel,
		treeViewSx,
		onNodeFocus,
		onNodeSelect,
		onNodeToggle,
		defaultExpanded,
		idFunc,
	} = props;

	const renderTreeObj = (nodes: RenderTree, index: number) => (
		<TreeItem
			key={nodes.id || `${nodes.name}${index}`}
			nodeId={String(
				idFunc ? idFunc(nodes) : nodes.id || `${nodes.name}${index}`
			)}
			label={renderLabel === undefined ? nodes.name : renderLabel(nodes)}
			disabled={nodes?.disabled ? true : false}
		>
			{Array.isArray(nodes.subdirs)
				? nodes.subdirs.map((node, i) => renderTreeObj(node, i))
				: null}
		</TreeItem>
	);

	return (
		<TreeView
			defaultCollapseIcon={<ArrowRightIcon />}
			defaultExpandIcon={<ArrowDropDownIcon />}
			onNodeFocus={onNodeFocus}
			onNodeSelect={onNodeSelect}
			onNodeToggle={onNodeToggle}
			defaultExpanded={defaultExpanded}
			sx={{ ...treeViewSx }}
		>
			{treeData.map((treeItem, index) => {
				return renderTreeObj(treeItem, index);
			})}
		</TreeView>
	);
};

export default MyTreeView;
