import ProLayout, { MenuDataItem, BasicLayoutProps as ProLayoutProps, WaterMark } from "@ant-design/pro-layout";
import React, { useState, useEffect } from "react";
import { useIntl, Link, history } from "umi";
import cookie from "js-cookie";
import RightContent from "@/components/GlobalHeader/RightContent";
import { Dispatch } from "@/models/connect";
import settings from "../../config/defaultSettings";
import logo from "./images/logo.png";
import GlobalFooter from "@/components/GlobalFooter";
import { userMenuApi, MenuItem } from "./api";
import { getUserInfo, UserInfo } from "@/pages/Login/api";
import { formatMenus } from "./entity";
import zhCN from "antd/lib/locale-provider/zh_CN";
import * as wasm from '@feewee/helper-wasm';
import { ConfigProvider } from "antd";
import "braft-editor/dist/index.css";
import "./common.less";

export interface BasicLayoutProps extends ProLayoutProps {
  breadcrumbNameMap: {
    [path: string]: MenuDataItem;
  };
  dispatch: Dispatch;
}
export type BasicLayoutContext = { [K in "location"]: BasicLayoutProps[K] } & {
  breadcrumbNameMap: {
    [path: string]: MenuDataItem;
  };
};

const BasicLayout: React.FC<BasicLayoutProps> = ({ dispatch, children, ...other }) => {
  const { formatMessage } = useIntl();
  const [currentUser, setCurrentUser] = useState<UserInfo>({});
  const [avatarLoading, setAvatarLoading] = useState<boolean>(true);
  const [collapsed, setCollapsed] = useState(false);
  const [menuData, setMenuData] = useState<MenuItem[]>([]);

  const token = cookie.get("fw-erp");

  if (!token) {
    history.replace("/user/login");
  }

  useEffect(() => {
    wasm.check_update();
    userMenuApi()
      .then((res) => {
        setMenuData(formatMenus(res.data!));
      })
      .catch((e) => {
        history.push("/user/login");
      });
  }, []);

  useEffect(() => {
    setAvatarLoading(true);
    getUserInfo()
      .then((infoRes) => {
        setCurrentUser(infoRes.data!);
        setAvatarLoading(false);
      })
      .catch((e) => {
        console.debug(e);
        setAvatarLoading(false);
      });
  }, []);

  return (
    <ConfigProvider locale={zhCN}>
      <ProLayout
        logo={logo}
        onCollapse={(playload) => setCollapsed(playload)}
        menuItemRender={(menuItemProps, defaultDom) => {
          if (menuItemProps.isUrl) {
            return defaultDom;
          }
          return (
            <Link to={menuItemProps.path ? `${menuItemProps.path}?fp_code=${menuItemProps.code}` : ""}>
              {defaultDom}
            </Link>
          );
        }}
        breadcrumbRender={(routers = []) => [
          {
            path: "/",
            breadcrumbName: formatMessage({
              id: "menu.home",
              defaultMessage: "Home",
            }),
          },
          ...routers,
        ]}
        itemRender={(route, params, routes, paths) => {
          const first = routes.indexOf(route) === 0;
          return first ? <Link to={paths.join("/")}>{route.breadcrumbName}</Link> : <span>{route.breadcrumbName}</span>;
        }}
        footerRender={() => <GlobalFooter />}
        menuDataRender={() => menuData as MenuDataItem[]}
        formatMessage={formatMessage}
        rightContentRender={(rightProps) => (
          <RightContent
            user={currentUser}
            loading={avatarLoading}
            theme={rightProps.navTheme}
            layout={rightProps.layout}
          />
        )}
        collapsed={collapsed}
        {...other}
        {...settings}
        navTheme={PROD_APP_ENV ? "dark" : "light"}
      >
        <WaterMark
          content={currentUser?.name ? `${currentUser.name} ${(currentUser?.mobile ?? "").slice(-4)}` : ""}
          fontSize={18}
        >
          {children}
        </WaterMark>
      </ProLayout>
    </ConfigProvider>
  );
};

export default BasicLayout;
