/**
 * Ant Design Pro v4 use `@ant-design/pro-layout` to handle Layout.
 * You can view component api by:
 * https://github.com/ant-design/ant-design-pro-layout
 */
import ProLayout from '@ant-design/pro-layout';
import React, { useEffect, useMemo } from 'react';
import { Link } from 'umi';
import { connect } from 'dva';
import { Icon, Result, Button } from 'antd';
import { formatMessage } from 'umi-plugin-react/locale';
import Authorized from '@/utils/Authorized';
import GlobalHeader from '@/components/GlobalHeader';
import GlobalFooter from '@/components/GlobalFooter';
import { isAntDesignPro, getAuthorityFromRouter } from '@/utils/utils';
import logo from '../assets/logo.svg';
const noMatch = (
  <Result
    status={403}
    title="403"
    subTitle="Sorry, you are not authorized to access this page."
    extra={
      <Button type="primary">
        <Link to="/user/login">Go Login</Link>
      </Button>
    }
  />
);

/** Use Authorized check all menu item */
const menuDataRender = (menuRoles) => (menuList) =>
  menuList.map((item) => {
    const needAuth = !!item.menuCode;

    const authority =
      (menuRoles.filter((x) => x.code === item.menuCode)[0] || {}).roles || [];

    const localItem = { ...item, children: item.children ? menuDataRender(menuRoles)(item.children) : [] };
    return Authorized.check(needAuth ? authority : undefined, localItem, null);
  });

const footerRender = () => <GlobalFooter />;

const BasicLayout = (props) => {
  const {
    // user,
    menus,
    dispatch,
    children,
    settings,
    history,
    location = {
      pathname: '/',
    },
  } = props;

  const handleMenuCollapse = (payload) => {
    if (dispatch) {
      dispatch({
        type: 'global/changeLayoutCollapsed',
        payload,
      });
    }
  }; // get children authority
  const routeItem = getAuthorityFromRouter(props.route.routes, location.pathname || '/')

  const authorized = useMemo(() => {
    if (!routeItem || !routeItem.menuCode) {
      return {
        authority: undefined,
      };
    }

    const authority = (menus.filter((x) => x.code === routeItem.menuCode)[0] || {}).roles;
    return {
      authority: authority && authority.length ? authority : ['any-string-for-no-right'],
    };
  })
  

  return (
    <ProLayout
      logo={logo}
      menuHeaderRender={(logoDom, titleDom) => (
        <Link to="/">
          {logoDom}
          {titleDom}
        </Link>
      )}
      onCollapse={handleMenuCollapse}
      menuItemRender={(menuItemProps, defaultDom) => {
        if (menuItemProps.isUrl || menuItemProps.children || !menuItemProps.path) {
          return defaultDom;
        }

        return <Link to={menuItemProps.path}>{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={footerRender}
      menuDataRender={menuDataRender(menus)}
      formatMessage={formatMessage}
      rightContentRender={() => <GlobalHeader title={routeItem?.name} history={history} location={location} />}//加非空判断
      {...props}
      {...settings}
    >
      <Authorized authority={authorized.authority} noMatch={noMatch}>
        {children}
      </Authorized>
    </ProLayout>
  );
};

export default connect(({ global, settings, user }) => ({
  collapsed: global.collapsed,
  settings,
  user: user.currentUser,
  menus: user.menuList,
}))(BasicLayout);
