import React from 'react'
import { LocaleProvider } from 'antd'
import { Router, Route, Switch } from 'dva/router'
import RootLayout from '../components/common/rootLayout'
import Login from '../components/common/login/login'
import Register from '../components/common/login/register'
import MainLayout from './mainLayout'
import ChartDesigner from '../components/chartDesigner/layout'
import DashboardDesigner from '../components/dashboardDesigner/layout'
// 由于 antd 组件的默认文案是英文，所以需要修改为中文
import zhCN from 'antd/lib/locale-provider/zh_CN'
import Demo from '../demo';
import Xiaomi from '../xiaomi'

function RouterConfig({ history }) {
    return (
        <LocaleProvider locale={zhCN}>
            <Router history={history}>
                <Switch>
                    <Route sensitive path='/login' component={Login} />
                    <Route sensitive path='/register' component={Register} />
                    <Route sensitive path='/demo' component={Demo} />
                    <Route sensitive path='/xiaomi' component={Xiaomi} />
                    <PrivateRoute sensitive path='/chart/:code' component={ChartDesigner} />
                    <PrivateRoute sensitive path='/dashboard/:code/' component={DashboardDesigner} />
                    <PrivateRoute path='/' component={MainLayout} />
                </Switch>
            </Router>
        </LocaleProvider>
    );
}

export default RouterConfig;

const PrivateRoute = ({ component: Component, ...rest }) => (
    <Route
        {...rest}
        render={props =>{

            if (!window.localStorage.getItem("token")) {
                window.localStorage.setItem("token", "false");
            }else {
                /**
                 * 是否过期
                 * 1.是-----设置isAuthenticated为false
                 */
                if(new Date(+window.localStorage.getItem("expireTime")) < new Date()) {
                    window.localStorage.setItem("token", "false");
                }
            }

            const isAuthenticated = window.localStorage.getItem("token") !== "false";
            return <RootLayout location={props.location} isAuthenticated={isAuthenticated}>
                <Component isAuthenticated={isAuthenticated} {...props} />
            </RootLayout>
        }}
    />
);
