import ProLayout, {
  MenuDataItem,
  BasicLayoutProps as ProLayoutProps,
  Settings,
} from '@ant-design/pro-layout';
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { Link, connect, Dispatch, history, Outlet, useLocation, useKeepOutlets } from '@umijs/max';
import { Result, Button, message } from 'antd';
import Authorized from '@/utils/Authorized';
import RightContent from '@/components/GlobalHeader/RightContent';
import { ConnectState } from '@/models/connect';
import { getMatchMenu } from '@umijs/route-utils';
import { getMenu } from './services'
import logo from '../assets/logo.svg';
import { getSessionRoleData, getSessionUserData } from '@/utils/session';

import {
  HomeOutlined,
  DesktopOutlined,
  NotificationOutlined,
  BookOutlined,
  ProfileOutlined,
  CommentOutlined,
  MacCommandOutlined,
  ProjectOutlined,
  PartitionOutlined,
  PayCircleOutlined,
  ContactsOutlined,
  WalletOutlined,
  AppstoreOutlined,
  ShopOutlined,
  FundProjectionScreenOutlined,
  PlaySquareOutlined,
  BankOutlined,
  IdcardOutlined,
} from '@ant-design/icons';

const menuIconMap = {
  "HomeOutlined": <HomeOutlined />,
  "ContactsOutlined": <ContactsOutlined />,
  "DesktopOutlined": <DesktopOutlined />,
  "NotificationOutlined": <NotificationOutlined />,
  "BookOutlined": <BookOutlined />,
  "ProfileOutlined": <ProfileOutlined />,
  "CommentOutlined": <CommentOutlined />,
  "MacCommandOutlined": <MacCommandOutlined />,
  "ProjectOutlined": <ProjectOutlined />,
  "PartitionOutlined": <PartitionOutlined />,
  "PayCircleOutlined": <PayCircleOutlined />,
  "WalletOutlined": <WalletOutlined />,
  "AppstoreOutlined": <AppstoreOutlined />,
  "ShopOutlined": <ShopOutlined />,
  "FundProjectionScreenOutlined": <FundProjectionScreenOutlined />,
  "PlaySquareOutlined": <PlaySquareOutlined />,
  "BankOutlined": <BankOutlined />,
  "IdcardOutlined": <IdcardOutlined />,
}

const noMatch = (
  <Result
    status={403}
    title="403"
    subTitle="对不起，您没有访问本页面的权限。"
    extra={
      <Button type="primary">
        {/* <Link to="/user/login">Go Login</Link> */}
        <Link to="/usercooper/login">登录</Link>
      </Button>
    }
  />
);

export interface BasicLayoutProps extends ProLayoutProps {
  breadcrumbNameMap: {
    [path: string]: MenuDataItem;
  };
  route: ProLayoutProps['route'] & {
    authority: string[];
  };
  settings: Settings;
  dispatch: Dispatch;
}
export type BasicLayoutContext = { [K in 'location']: BasicLayoutProps[K] } & {
  breadcrumbNameMap: {
    [path: string]: MenuDataItem;
  };
};
const menuDataRender = (menuList: MenuDataItem[]): MenuDataItem[] =>
  menuList.map((item) => {
    const localItem = {
      ...item,
      children: item.children ? menuDataRender(item.children) : undefined,
    };
    return Authorized.check(item.authority, localItem, null) as MenuDataItem;
  });
const BasicLayout: React.FC<BasicLayoutProps> = (props) => {
  const {
    dispatch,
    settings,
  } = props;
  const location = useLocation()
  const [menuData, setMenuData] = React.useState<any>();
  const [menuShow, setmenuShow] = React.useState<any>(false);
  const menuDataRef = useRef<MenuDataItem[]>([]);
  const mall3_token: any = sessionStorage.getItem('Authorization');//当前登录token
  const userData: any = getSessionUserData();//当前登录人信息
  const children = useKeepOutlets();
  useEffect(() => {
    if (getSessionRoleData()?.roleId) {
      let params = {
        roleIdList: [getSessionRoleData()?.roleId]
      }
      getMenu(params).then(res => {
        if (res.code == 200) {
          setMenuData(res.data || [])
          if (dispatch) {
            dispatch({
              type: 'user/saveMenuData',
              payload: res.data || [],
            });
          }
          setmenuShow(true)
        } else {
          message.error("数据错误请联系管理员")
        }
      })
    }
  }, []);

  const menuICon = (menus: any[]): any[] =>
    menus && menus.map(({ icon, ...item }) => ({
      ...item,
      icon: icon && menuIconMap[icon as string],
    }));

  const handleMenuCollapse = (payload: boolean): void => {
    if (dispatch) {
      dispatch({
        type: 'global/changeLayoutCollapsed',
        payload,
      });
    }
  };
  const authorized = useMemo(
    () =>
      getMatchMenu(location.pathname || '/', menuDataRef.current).pop() || {
        authority: undefined,
      },
    [location.pathname],
  );
  return menuShow ? (<ProLayout
    menuDataRender={() => menuICon(menuData)}
    logo={logo}
    // formatMessage={formatMessage}
    onCollapse={handleMenuCollapse}
    onMenuHeaderClick={() => history.push('/')}
    menuItemRender={(menuItemProps, defaultDom) => {
      if (menuItemProps.isUrl || !menuItemProps.path) {
        return defaultDom;
      }
      if (menuItemProps.projectType != undefined) {
        menuItemProps.path = menuItemProps.path + `?projectType=${menuItemProps.projectType}`;
      }
      if (menuItemProps.frame && menuItemProps.frame == 'N') {
        return <Link to={menuItemProps.path}>{defaultDom}</Link>;
      } else if (menuItemProps.frame && menuItemProps.frame == 'Y') {
        return <Link onClick={() => window.open(menuItemProps.path)} to="#">{defaultDom}</Link>;
      } else if (menuItemProps.frame && menuItemProps.frame == 'S') {
        const initPath = menuItemProps.path;
        const rePath = initPath?.replace("{mall3_token}", mall3_token).replace("{loginName}", userData.loginName).replace("{organizationId}", userData.organizationId);
        return <Link onClick={() => window.open(rePath)} to="#">{defaultDom}</Link>;
      } else {
        return <Link to={menuItemProps.path}>{defaultDom}</Link>;
      }
    }}
    breadcrumbRender={(routers = []) => [
      {
        path: '/',
        breadcrumbName: '首页',
      },
      ...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>
      );
    }}
    rightContentRender={() => <RightContent />}
    postMenuData={(menuData) => {
      menuDataRef.current = menuData || [];
      return menuData || [];
    }}
    contentStyle={{
      backgroundColor: '#F5F7FA',
    }}
    {...props}
    {...settings}
  >
    <Authorized authority={authorized!.authority} noMatch={noMatch}>
      <div style={{ width: "100%" }}>
        {children}
      </div>
    </Authorized>
  </ProLayout>) : null
}

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