import React, { useState, useRef, useEffect } from "react";
import PropTypes from "prop-types";
import ZerodMainContext from "../ZerodMainContext";
import ReactDOM from "react-dom";
import "./style.less";
import Loading from "../../lazyLoad/Loading";
const propTypes = {
	getScrollAreaWrapperEl: PropTypes.func,
	getInsertLocation: PropTypes.func,
	history: PropTypes.object,
	location: PropTypes.object,
	match: PropTypes.object,
};
export const ZiframeRoute = props => {
	const { getScrollAreaWrapperEl, getInsertLocation, location, match } = props;
	const boxElRef = useRef();
	const [iframeUrl, setIframeUrl] = useState("");
	const [wrapperEl, setWrapperEl] = useState(null);
	const [loading, setLoading] = useState(false);
	useEffect(() => {
		const insetLocaltion = getInsertLocation(boxElRef.current);
		const context = getScrollAreaWrapperEl(insetLocaltion);
		setWrapperEl(context.wrapperEl);
	}, []);
	useEffect(() => {
		setLoading(true);
		setIframeUrl(decodeURIComponent(match.params.url));
	}, [match]);
	return (
		<section ref={boxElRef}>
			{wrapperEl
				? ReactDOM.createPortal(
						<div className="z-iframe-route">
							{loading ? <Loading></Loading> : null}
							<iframe
								style={{ visibility: loading ? "hidden" : "visible" }}
								src={iframeUrl}
								frameBorder="0"
								seamless
								scrolling="auto"
								onLoad={() => {
									setLoading(false);
								}}
							/>
						</div>,
						wrapperEl,
				  )
				: null}
		</section>
	);
};
ZiframeRoute.propTypes = propTypes;
export default ZerodMainContext.setConsumer(ZiframeRoute);
