/**
 * 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 { ConnectProps, ConnectState, Dispatch } from '@/models/connect';
import ProLayout, {
  MenuDataItem,
  BasicLayoutProps as ProLayoutProps,
  Settings,
  SettingDrawer,
} from '@ant-design/pro-layout';
import React, { useState, useEffect } from 'react';
import Authorized from '@/utils/Authorized';
import Link from 'umi/link';
import router from 'umi/router';

import RightContent from '@/components/GlobalHeader/RightContent';
import { connect } from 'dva';
import { formatMessage } from 'umi-plugin-react/locale';
import { isAntDesignPro } from '@/utils/utils';
import { message } from 'antd';
import store from '@/utils/store';
import { async } from 'q';
export interface BasicLayoutProps extends ProLayoutProps, Omit<ConnectProps, 'location'> {
  breadcrumbNameMap: {
    [path: string]: MenuDataItem;
  };
  settings: Settings;
}
export type BasicLayoutContext = { [K in 'location']: BasicLayoutProps[K] } & {
  breadcrumbNameMap: {
    [path: string]: MenuDataItem;
  };
};
/**
 * use Authorized check all menu item
 */

const menuDataRender = (menuList: MenuDataItem[]): MenuDataItem[] =>
  menuList.map(item => {
    // 遍历给所有的children加上了[]
    const localItem = { ...item, children: item.children ? menuDataRender(item.children) : [] };
    // 检查菜单项是否有权限
    return Authorized.check(item.authority, localItem, null) as MenuDataItem;
  });

// footer渲染
const footerRender: BasicLayoutProps['footerRender'] = (_, defaultDom) => {
  if (!isAntDesignPro()) {
    return defaultDom;
  }

  return (
    <>
      {defaultDom}
      <div
        style={{
          padding: '0px 24px 24px',
          textAlign: 'center',
        }}
      >
        <a href="https://www.netlify.com" target="_blank" rel="noopener noreferrer">
          <img
            src="https://www.netlify.com/img/global/badges/netlify-color-bg.svg"
            width="82px"
            alt="netlify logo"
          />
        </a>
      </div>
    </>
  );
};

const loadInitData = (dispatch: Dispatch) => {
  return Promise.all([
    dispatch({ type: 'user/getCurrent' }),
    dispatch({ type: 'settings/getSettings' }),
  ]);
};

const BasicLayout: React.FC<BasicLayoutProps> = props => {
  const { dispatch, children, settings } = props;
  /**
   * constructor
   */
  const [loaded, setLoaded] = useState(false);

  useEffect(() => {
    if (dispatch) {
      // 查看当前用户是否在登录状态
      dispatch({
        type: 'user/checkLoginStatus',
      }).then(async ({ code, data = false }: { code: string; data: boolean }) => {
        if (code === 'sys.success') {
          // 登录成功
          if (data) {
            await loadInitData(dispatch);
            setLoaded(true);
          } else if (store.get('userId')) {
            store.set('token', '');
            store.set('userId', '');
            message.error('登录已过期,请重新登录!');
            router.push('/user/login');
          } else {
            // 此处应该跳转到404或者403页面为佳
            // message.error("用户未登录,请先登录系统!");
            router.push('/404');
          }
        }
      });
    }
  }, []);
  /**
   * init variables
   */

  const handleMenuCollapse = (payload: boolean): void =>
    dispatch &&
    dispatch({
      type: 'global/changeLayoutCollapsed',
      payload,
    });

  return (
    loaded && (
      <div className="kim-layout">
        <ProLayout
          siderWidth={200}
          logo={false}
          navTheme="dark"
          onCollapse={handleMenuCollapse}
          menuItemRender={(menuItemProps, defaultDom) => (
            <Link to={menuItemProps.path}>{defaultDom}</Link>
          )}
          breadcrumbRender={(routers = []) => [
            {
              path: '/',
              breadcrumbName: formatMessage({
                id: 'menu.home',
                defaultMessage: 'Home',
              }),
            },
            ...routers,
          ]}
          footerRender={false} // 不显示footer
          menuDataRender={menuDataRender} // 渲染导航菜单列表
          formatMessage={formatMessage}
          rightContentRender={rightProps => <RightContent {...rightProps} />}
          {...props}
          {...settings}
        >
          {children}
        </ProLayout>
        {/* 主题设置抽屉 */}
        <SettingDrawer
          settings={settings}
          onSettingChange={config => {
            dispatch({
              type: 'settings/saveSettings',
              payload: config,
            });
            dispatch({
              type: 'settings/changeSetting',
              payload: config,
            });
          }}
        />
      </div>
    )
  );
};

export default connect(({ global, settings }: ConnectState) => ({
  collapsed: global.collapsed,
  settings,
}))(BasicLayout);
