import React, {Component} from 'react';
import {Router, Route, Redirect, Switch} from "react-router-dom";
import './App.scss';
import {withTranslation} from "react-i18next";
import { history as browserHistory } from './common/history';
import {  syncHistoryWithStore } from 'mobx-react-router';
import {  Provider } from 'mobx-react';
import { rootRouter } from './router/rootRouter';
import NotFound from './page/404';
import {routerStore} from "./store/routerStore";
import mobxStore from './store/index';

const history = syncHistoryWithStore(browserHistory, routerStore);

class App extends Component {
    state = {};

    render() {
        return (
            <Provider { ...mobxStore }>
                <Router history={history}>
                    <Switch>
                        <Redirect exact from={'/'} to={'/zh/login'}/>
                        {/*定义URL上第一个字段来定义语言*/}
                        <Route path={'/:lan'} children={({ match,...params }) => {
                            if(!match.params) {
                                return <Redirect to={'/zh/login'}/>
                            }
                            let lan = match.params.lan;
                            return (
                                <Switch>
                                    {
                                        rootRouter.map(({path, component, ...otherProps},index) => {
                                            return <Route path={`/${lan+path }`} component={component} {...otherProps} key={index}/>
                                        })
                                    }
                                    <Route path={'*'} component={NotFound}/>
                                </Switch>
                            );
                        }}/>
                        <Route path={'*'} component={NotFound}/>
                    </Switch>
                </Router>
            </Provider>
        );
    }

    componentDidMount() {
        // this.setLanguage();
    }

    setLanguage() {
        let { i18n } = this.props;
        try {
            let lan = window.location.pathname.split('/')[1];
            i18n.changeLanguage(lan);
        }catch (e) {

        }
    }
}

export default withTranslation()(App);