import { Button, Space, Spin } from "antd";
import { useEffect, useState } from "react";
import { throttle } from "throttle-debounce";
import HeaderBack from "../HeaderBack";

/**
 * 页面布局组件
 */
function Page(props) {
  const {
    headerTitle,
    history,
    isShowHeader = true,
    headerPrevious = true,
    isShowFooter = true,
    isShowAllAction = true,
    loading = false,
    backButtonText = "关闭",
    contentPadding = "20px",
    customActionButtons,
    extraActionButtons,
    children,
  } = props;

  const [pageWidth, setPageWidth] = useState(window.innerWidth);

  const getPageWidth = throttle(50, () => {
    const pageDom = document.querySelector("#page-layout");
    if (!pageDom)
      return;
    setPageWidth(pageDom.offsetWidth);
  });

  useEffect(() => {
    const timer = setTimeout(() => {
      getPageWidth();
    }, 0);
    if (isShowAllAction && isShowFooter) {
      window.addEventListener("resize", getPageWidth);
    }

    return () => {
      if (isShowAllAction && isShowFooter) {
        window.removeEventListener("resize", getPageWidth);
      }
      clearTimeout(timer);
    };
  }, [isShowAllAction, isShowFooter]);

  return (
    <Spin spinning={loading}>
      <div className="page-layout" id="page-layout">
        {(isShowAllAction && isShowHeader) && <HeaderBack title={headerTitle} history={history} previous={headerPrevious} />}
        <div style={{ padding: contentPadding }}>
          {children && typeof children === "function" ? children() : children}
          {
            (isShowAllAction && isShowFooter) && (
              <div className="page-layout-footer" style={{ position: "relative", zIndex: "9" }}>
                <div style={{ height: "52px" }}></div>
                <div style={{ textAlign: "center", backgroundColor: "rgb(241, 241, 242)", padding: "10px 0", position: "fixed", bottom: "0", width: pageWidth, margin: "0px -20px" }}>
                  {customActionButtons || (
                    <Space>
                      {extraActionButtons}
                      <Button
                        onClick={() => {
                          history?.goBack ? history.goBack() : window.history.back();
                        }}
                      >
                        {backButtonText}
                      </Button>
                    </Space>
                  )}
                </div>
              </div>
            )
          }
        </div>
      </div>
    </Spin>
  );
}

Page.displayName = "Page";

export default Page;
