app.jsx 5.32 KB
Newer Older
wuhao's avatar
wuhao committed
1 2 3 4 5 6 7 8 9 10
import Footer from '@/components/Footer';
import RightContent from '@/components/RightContent';
import { SettingDrawer } from '@ant-design/pro-components';
import { history, Link, matchRoutes } from '@umijs/max';
import defaultSettings from '../config/defaultSettings';
import { queryCurrentUser, getMenu } from './services/login';
import TagView from '@/components/TagView';
import SiderMenu from '@/components/SiderMenu';
import * as Ant4Icons from '@ant-design/icons';
import { createElement } from 'react';
wuhao's avatar
wuhao committed
11
import routes from '../config/authRoutes';
wuhao's avatar
wuhao committed
12 13

const { LinkOutlined } = Ant4Icons;
TZW's avatar
TZW committed
14 15
// const isDev = process.env.NODE_ENV === 'development';
const isDev = true;
TZW's avatar
TZW committed
16
//console.log(isDev);
wuhao's avatar
wuhao committed
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
const loginPath = '/user/login';

/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
function strToHump(str) {
  let strArr = str.split('-');
  for (let i = 0; i < strArr.length; i++) {
    strArr[i] = strArr[i].charAt(0).toUpperCase() + strArr[i].substr(1);
  }
  let res = strArr.join('');
  return res + 'Outlined';
}

export async function getInitialState() {
  let token = localStorage.getItem('TOKENES');
  const fetchUserInfo = async () => {
    try {
      const msg = await queryCurrentUser();
      return msg.data;
    } catch (error) {
wuhao's avatar
wuhao committed
38
      // history.push(loginPath);
wuhao's avatar
wuhao committed
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
    }
    return undefined;
  }; // 如果是登录页面,不执行

  const getmenuData = async () => {
    try {
      const res = await getMenu();
      return res.data;
    } catch (error) {
      message.error(res.msg);
    }
    return undefined;
  }; // 如果是登录页面,不执行
  if (history.location.pathname !== loginPath && token) {
    const currentUserData = await fetchUserInfo();
    let menuData;
    if (currentUserData?.data?.userName) {
      menuData = await getmenuData();
    }
wuhao's avatar
wuhao committed
58 59 60 61 62 63 64 65 66
    /* isdev */
    if (isDev) {
      menuData = {
        recentUsePermList: [],
        collectPerm: [],
        userHavePermList: routes,
      };
    }

wuhao's avatar
wuhao committed
67 68 69 70 71 72 73 74 75
    return {
      fetchUserInfo,
      currentUser: currentUserData?.data,
      settings: defaultSettings,
      newMenu: menuData,
      getmenuData,
      collapsed: false,
    };
  }
TZW's avatar
TZW committed
76 77 78 79 80 81 82 83 84 85

  let menuData = {};
  if (isDev) {
    menuData = {
      recentUsePermList: [],
      collectPerm: [],
      userHavePermList: routes,
    };
  }

wuhao's avatar
wuhao committed
86 87 88 89 90 91
  return {
    fetchUserInfo,
    settings: defaultSettings,
    getmenuData,
    collapsed: false,
    tagList: [],
TZW's avatar
TZW committed
92
    newMenu: menuData,
wuhao's avatar
wuhao committed
93 94 95 96 97 98 99
  };
}

// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout = ({ initialState, setInitialState }) => {
  let token = localStorage.getItem('TOKENES');

wuhao's avatar
wuhao committed
100 101 102 103 104 105 106 107 108 109 110 111
  let menurender = isDev
    ? {}
    : {
        menuRender: (props, defaultDom) => {
          if (props.isMobile) {
            return defaultDom;
          } else {
            return <SiderMenu {...props} />;
          }
        },
      };

wuhao's avatar
wuhao committed
112 113 114 115 116 117 118 119 120 121 122 123 124
  return {
    disableContentMargin: false,
    waterMarkProps: {
      content: initialState?.currentUser?.name,
    },
    collapsed: initialState.collapsed,
    onCollapse: (cols) => {
      setInitialState((s) => ({ ...s, collapsed: cols }));
    },
    footerRender: () => <Footer />,
    onPageChange: () => {
      const { location } = history;
      // 如果没有登录,重定向到 login
wuhao's avatar
wuhao committed
125 126 127
      // if (!initialState?.currentUser && location.pathname !== loginPath) {
      //   history.push(loginPath);
      // }
wuhao's avatar
wuhao committed
128 129 130
    },
    links: isDev
      ? [
TZW's avatar
TZW committed
131 132 133 134
          // <Link key="openapi" to="/umi/plugin/openapi" target="_blank">
          //   <LinkOutlined />
          //   <span>OpenAPI 文档</span>
          // </Link>,
wuhao's avatar
wuhao committed
135 136 137 138 139 140 141 142 143
        ]
      : [],
    //接口获取菜单数据
    menu: {
      // 每当 initialState?.currentUser?.userid 发生修改时重新执行 request
      params: {
        userId: initialState?.currentUser?.id,
      },
      request: (params, defaultMenuData) => {
TZW's avatar
TZW committed
144
        //console.log(initialState);
wuhao's avatar
wuhao committed
145 146 147 148
        let lastArr = initialState?.newMenu?.userHavePermList
            ? JSON.parse(JSON.stringify(initialState?.newMenu?.userHavePermList))
            : [],
          newArr = [
TZW's avatar
TZW committed
149 150 151 152 153 154 155 156 157 158 159 160
            // {
            //   path: '/welcome',
            //   name: '首页',
            //   icon: 'smile',
            //   component: './Welcome',
            //   haveChildren: false,
            //   key: '000000',
            //   parentKey: '0',
            //   routes: [],
            //   children: null,
            //   title: null,
            // },
wuhao's avatar
wuhao committed
161 162 163 164 165 166 167 168 169 170 171 172 173
          ].concat(lastArr);

        return newArr.map((item, index) => {
          if (item.icon) {
            const icon = strToHump(item.icon),
              ItemIcon = Ant4Icons[icon];
            item.icon = createElement(ItemIcon);
          }
          return item;
        });
      },
      locale: false,
    },
wuhao's avatar
wuhao committed
174
    ...menurender,
wuhao's avatar
wuhao committed
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
    // 自定义 403 页面
    unAccessible: <div>unAccessible</div>,
    noFound: <div>noFound</div>,
    // 增加一个 loading 的状态
    childrenRender: (children, props) => {
      // if (initialState?.loading) return <PageLoading />;
      return (
        <>
          {initialState?.currentUser && location.pathname !== loginPath ? (
            <TagView home="/welcome">{children}</TagView>
          ) : (
            children
          )}
        </>
      );
    },
    ...initialState?.settings,
    layout: false,
    headerContentRender: () => <RightContent />,
    rightContentRender: () => null,
  };
};