/*
 * @Author: 吴永生#A02208 yongsheng.wu@wholion.com
 * @Date: 2022-06-11 09:33:46
 * @LastEditors: 吴永生 15770852798@163.com
 * @LastEditTime: 2022-09-01 19:34:26
 * @FilePath: /bkunyun/src/components/mui/MyPopover.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { useRef, useEffect, useState } from "react";
import Popover, { PopoverProps } from "@mui/material/Popover";
import Typography from "@mui/material/Typography";

interface IProps extends Omit<PopoverProps, "open"> {
	/** 触发行为 */
	trigger?: "hover" | "click";
	/** 触发dom */
	children: React.ReactNode;
	/** 显示内容 */
	content: React.ReactNode;
	/** 是否打开 */
	open?: boolean;
	/** open 修改 */
	changeOpen: (val: boolean) => void;
}

const MyPopover = (props: IProps) => {
	const [anchorEl, setAnchorEl] = useState<any | null>(null);
	const ref = useRef(null);

	const {
		trigger = "click",
		children,
		content,
		anchorOrigin,
		transformOrigin,
		open = false,
		changeOpen,
	} = props;

	const handlePopoverOpen = (event: any) => {
		changeOpen(true);
		setAnchorEl(event.currentTarget);
	};

	const handelClick = (event: any) => {
		changeOpen(true);
		setAnchorEl(event?.currentTarget);
	};

	const handlePopoverClose = () => {
		changeOpen(false);
		setAnchorEl(null);
	};

	useEffect(() => {
		if (open) {
			setAnchorEl(ref.current);
		}
	}, [open]);

	const id = open ? "simple-popover" : undefined;

	return (
		<div>
			<Typography
				ref={ref}
				aria-owns={id}
				onClick={trigger === "click" ? handelClick : undefined}
				onMouseEnter={trigger === "hover" ? handlePopoverOpen : undefined}
				onMouseLeave={trigger === "hover" ? handlePopoverClose : undefined}
			>
				{children}
			</Typography>
			<Popover
				id={id}
				open={open}
				anchorEl={anchorEl}
				onClose={handlePopoverClose}
				sx={{
					pointerEvents: trigger === "hover" ? "none" : undefined,
				}}
				anchorOrigin={
					anchorOrigin || {
						vertical: "bottom",
						horizontal: "center",
					}
				}
				transformOrigin={
					transformOrigin || {
						vertical: "top",
						horizontal: "center",
					}
				}
			>
				<Typography sx={{ p: 1 }}>{content}</Typography>
			</Popover>
		</div>
	);
};

export default MyPopover;
