import * as React from "react";
import { useEffect } from "react";
import { ConfigProvider } from "antd";
import { DndProvider } from "react-dnd";
import moment from "moment";
import { Provider } from "mobx-react";
import zhCN from "antd/lib/locale/zh_CN";
import { HTML5Backend } from "react-dnd-html5-backend";
import { connect, IRouteComponentProps, useModel } from "umi";
import BaseLayout from "./BaseLayout";
import BlankLayout from "./BlankLayout";
import UserLayout from "./UserLayout";
import { IRouterProps, RouterContext } from "./RouterContext";
import { layoutConfig } from "@/layouts/config";
import stores from "@/store";
import "moment/locale/zh-cn";
import "antd/dist/antd.variable.min.css";

moment.locale("zh-cn");

const Layout = ({ children, location, route, history, match }: IRouteComponentProps) => {
  const props = { children, location, route, history, match };
  const { query } = location;
  const embed = {
    hideHead: !!(query.hideHead && query.hideHead === "true"),
    hideSide: !!(query.hideSide && query.hideSide === "true"),
    hideFoot: !!(query.hideFoot && query.hideFoot === "true"),
    hideAll: !!(query.hideAll && query.hideAll === "true")
  };
  const masterProps = useModel("@@qiankunStateFromMaster");
  let containerStyle: React.CSSProperties = {};
  if (masterProps?.hideAll) {
    embed.hideAll = true;
    containerStyle = masterProps?.containerStyle || {};
  }

  const routerProps: IRouterProps = { ...embed };

  useEffect(() => {
    // API.SettingService.initSystemParam();
  }, []);

  let layout;
  if (embed.hideAll) {
    layout = <BlankLayout {...props} style={containerStyle}/>;
  } else {
    let { pathname } = location;
    pathname = pathname.startsWith("/") ? pathname : `/${pathname}`;
    let type = layoutConfig[pathname];
    if (!type) {
      type = _.find(layoutConfig, (v: any, k: any) => new RegExp(k).test(pathname));
    }

    if (type) {
      switch (type) {
        case "user":
          layout = <UserLayout {...props} />;
          break;
        case "blank":
          layout = <BlankLayout {...props} />;
          break;
        default:
          layout = <BaseLayout {...props} />;
          break;
      }
    } else {
      layout = <BaseLayout {...props} />;
    }
  }

  return (
    <Provider {...stores}>
      <DndProvider backend={HTML5Backend}>
        <RouterContext.Provider value={routerProps}>
          <ConfigProvider locale={zhCN}>{layout}</ConfigProvider>
        </RouterContext.Provider>
      </DndProvider>
    </Provider>
  );
};

export default connect()(Layout);
