/*
 * @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 { ThemeProvider, createTheme } from "@mui/material/styles";

interface IProps extends Omit<PopoverProps, "open"> {
	/** 触发行为 */
	trigger?: "hover" | "click";
	/** 触发dom */
	children: React.ReactNode;
	/** 显示内容 */
	content: React.ReactNode;
	/** 是否打开 */
	open?: boolean;
	/** open 修改 */
	changeOpen: (val: boolean) => void;
}
const theme = createTheme({
	components: {
		MuiPaper: {
			styleOverrides: {
				root: {
					boxShadow: "0px 3px 10px 0px rgba(0,24,57,0.14)",
				},
			},
		},
	},
});
// .css-3bmhjh-MuiPaper-root-MuiPopover-paper
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 (
		<ThemeProvider theme={theme}>
			<div>
				<div
					ref={ref}
					aria-owns={id}
					onClick={trigger === "click" ? handelClick : undefined}
					onMouseEnter={trigger === "hover" ? handlePopoverOpen : undefined}
					onMouseLeave={trigger === "hover" ? handlePopoverClose : undefined}
				>
					{children}
				</div>
				<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",
						}
					}
				>
					{content}
				</Popover>
			</div>
		</ThemeProvider>
	);
};

export default MyPopover;
