import React, { useEffect, ReactNode } from 'react';
// @ts-ignore
import PluginLayout from '@umijs/plugin-layout/lib/layout';
import { PageLoading } from '@ant-design/pro-layout';
// @ts-ignore
import { AuthPage } from '@kbse-frame/system';
// @ts-ignore
import { Link, useModel } from 'umi';
import cx from 'classnames';
import logo from './assets/logo.png';
import RightContent from './components/RightContent';
import { Footer } from '.';
import { getDefaultSettings, getGlobalTitle } from './utils/utils';
import WaterMark from './components/Watermark';
import styles from './BasicLayout.less';

interface Props {
  children: ReactNode;
  userConfig: any;
  className: string;
}

const BasicLayout: React.FC<Props> = ({ children, className, ...props }) => {
  const model = useModel('system');

  if (!model) {
    throw new Error('@kbse-frame/layout need @kbse-frame/system as slave');
  }
  const { routes, loading, fetch, resourcesData, env } = model;

  useEffect(fetch, []);

  if (loading && !resourcesData) {
    return <PageLoading />;
  }

  const layoutSettings = getDefaultSettings();

  // title i18n
  layoutSettings.title = getGlobalTitle();
  // footer
  if (layoutSettings.footerRender === true) {
    layoutSettings.footerRender = () => <Footer />;
  }

  // right render
  layoutSettings.rightRender = () => <RightContent />;

  // 子菜单加上icon
  const menuItemRender = (item: {
    icon: ReactNode;
    name: string;
    isUrl: boolean;
    target: string;
    itemPath: string;
  }) => {
    const { target, icon, name, itemPath, isUrl } = item;
    // Is it a http link
    if (isUrl) {
      return (
        <a href={itemPath} target={target}>
          {icon}
          <span>{name}</span>
        </a>
      );
    }
    return (
      <Link to={itemPath}>
        <span className="ant-pro-menu-item">
          {icon}
          <span className="ant-pro-menu-item-title">{name}</span>
        </span>
      </Link>
    );
  };

  return (
    <PluginLayout
      {...props}
      className={cx(styles.basicLayoutFixed, { [className]: !!className })}
      userConfig={layoutSettings}
      route={{ routes }}
      disableContentMargin
      menuItemRender={menuItemRender}
      logo={<img src={logo} style={{ width: 26, height: 26 }} alt="logo" />}
    >
      <WaterMark env={env}>
        <AuthPage>{children}</AuthPage>
      </WaterMark>
    </PluginLayout>
  );
};

export default BasicLayout;
