import React, { ReactNode, useEffect, useState } from "react";
// 使用ReactDOM.createPortal 动态创建弹窗
// 可以插入到dom任意节点，不限于父节点
import { CloseOutlined } from "@ant-design/icons";
import ReactDOM from "react-dom";
import "./dilog.less";
interface DilogModel {
  show: boolean;
  close: Function;
  children: ReactNode;
  maskClosable: boolean;
  title?: string;
  okText?: string;
}
const Dilog = (props: DilogModel) => {
  const [isShow, showState] = useState(false);
  useEffect(() => {
    showState(props.show);
    const onClick = (ev:MouseEvent) => {
      if (ev.target === document.getElementsByClassName("modal")[0]) {
        showState(false);
        props.close();
      }
    };
    const handleKeyword = (e:KeyboardEvent) => {
      if (e.eventPhase === 27) {
        showState(false);
        props.close();
      }
    };
    document.documentElement.addEventListener("click", onClick);
    document.documentElement.addEventListener("keydown", handleKeyword);
    return () => {
      document.documentElement.removeEventListener("click", onClick);
      document.documentElement.removeEventListener("keydown", handleKeyword);
    };
  }, [props.show]);
  const handleClose = () => {
    showState(false);
    props.close();
  };
  const childrens = (
    <div className="modal">
      <div className="modal-content">
        <div className="modal-header">
          <CloseOutlined className="close-btn" onClick={handleClose} />
        </div>
        <div className="model-cont">{props.children}</div>
        <div className="modal-footer">
          <button>{props.okText ?? "确认"}</button>
          <button>取消</button>
        </div>
      </div>
    </div>
  );
  return isShow
    ? ReactDOM.createPortal(
        childrens,
        document.getElementById("root") as Element
      )
    : null;
};

export default Dilog;
