import './style/global.less';
import React, {useEffect} from 'react';
import ReactDOM from 'react-dom';
import {ConfigProvider} from '@arco-design/web-react';
import zhCN from '@arco-design/web-react/es/locale/zh-CN';
import enUS from '@arco-design/web-react/es/locale/en-US';
import {BrowserRouter, Switch, Route} from 'react-router-dom';

import PageLayout from './layout';
import {GlobalContext} from './context';
import Login from './pages/login';
import checkLogin from './utils/checkLogin';
import changeTheme from './utils/changeTheme';
import useStorage from './utils/useStorage';
import {QueryClientProvider, QueryClient} from 'react-query';
import {useStore} from '@/store';

const queryClient = new QueryClient({
	defaultOptions: {
		queries: {
			retry: 0,
			refetchOnWindowFocus: false,
			keepPreviousData: true
		},
	}
});

function Index() {
	const [lang, setLang] = useStorage('arco-lang', 'zh-CN');
	const [theme, setTheme] = useStorage('arco-theme', 'light');
	const {fetchUserInfo, init} = useStore();

	function getArcoLocale() {
		switch (lang) {
			case 'zh-CN':
				return zhCN;
			case 'en-US':
				return enUS;
			default:
				return zhCN;
		}
	}

	useEffect(() => {
		init();
		if (checkLogin()) {
			fetchUserInfo();
		} else if (window.location.pathname.replace(/\//g, '') !== 'login') {
			window.location.pathname = '/login';
		}
	}, []);

	useEffect(() => {
		changeTheme(theme);
	}, [theme]);

	const contextValue = {
		lang,
		setLang,
		theme,
		setTheme
	};

	return (
		<BrowserRouter>
			<ConfigProvider
				locale={getArcoLocale()}
				componentConfig={{
					Card: {
						bordered: false
					},
					List: {
						bordered: false
					},
					Table: {
						border: {wrapper: true}
					},
					Form: {
						labelCol: {span: 5},
						wrapperCol: {span: 18},
					},
					Modal: {
						style: {width: '550px'},
						autoFocus: false,
						focusLock: false,
						escToExit: false
					}
				}}
			>
				<GlobalContext.Provider value={contextValue}>
					<Switch>
						<Route path="/login" component={Login}/>
						<QueryClientProvider client={queryClient}>
							<Route path="/" component={PageLayout}/>
						</QueryClientProvider>
					</Switch>
				</GlobalContext.Provider>
			</ConfigProvider>
		</BrowserRouter>
	);
}

ReactDOM.render(<Index/>, document.getElementById('root'));
