router-view.js 2.8 KB
import React, { useState, useEffect } from 'react'
import { Switch, Route, useHistory } from 'react-router-dom'
import { Guards } from './guards'
import { APP } from '@/config'
import connect from '../store/modules/route/connect'
import { getAllRouter } from '../libs/utilts'
import { getToken } from 'xbd-cookie'
import Layout from '@/components/Layout'
import { show, hide } from 'loading-bar'
import http from '@/libs/fetch'
import { getMenu } from '@/api/user'
import { Modal } from 'antd'

import error401 from "@/view/error/401"
import error404 from "@/view/error/404" 

/** 获取全部路由的路径 */
const getAllRouterName = route => route.map(e => e.url)

/** 路由视图 */
const RouterView = ({basisRoute = [], serviceRoute = [], userRoute = [], userSatatus, SYSTEM_LOGIN}) => {
    const [openRoute, setOpenRoute] = useState([])
    const history = useHistory()

    useEffect(() => {
        // 二级路由转一级路由
        const allRoute = getAllRouter(userRoute)
        const allName = getAllRouterName(serviceRoute)

        const newRoutes = allRoute.map(e => {
            const index = serviceRoute.findIndex(service => service.url === e.url)
            const newE = {...e}

            if (index !== -1)
                newE.component = serviceRoute[index].component
            else {
                const indexOfName = allName.findIndex(url => url === e.url)
                if (indexOfName !== -1)
                    newE.component = serviceRoute[index].component
                else 
                    newE.component = () => {
                        // location.href = APP.othreDomain + newE.url
                        return (<>{newE.url}</>)
                    }  
            }
                
            return newE
        })

        setOpenRoute(newRoutes)
    }, [userRoute, serviceRoute])

    useEffect(() => {
        const token = getToken()

        if (userSatatus) 
            return 
        else if (token) {
            show()
            http.setHeader('sessionid', token)
            getMenu()
                .then(res => {
                    hide()
                    SYSTEM_LOGIN(res)
                })
                .catch(err => {
                    hide()
                    Modal.error({ title: '错误', content: err, onOk: () => history.replace('/login') })
                })
        } else 
            history.replace('/login')
    }, [])

    return (
        <Layout>
            <Switch>
                    {basisRoute.map(e => <Route path={e.url} exact={e.exact} component={Guards(e.component)}  key={e.url} />)}
                    {openRoute.map(e => <Route path={e.url} exact={e.exact} component={Guards(e.component)} key={e.url} />)}
                    <Route component={error401} />
            </Switch>
        </Layout>
    )
}

export default connect(RouterView)