// @ts-ignore
import React, { useEffect, Suspense, useMemo } from 'react';
// @ts-ignore
import * as ReactDOM from 'react-dom';
// @ts-ignore
import { YRouter } from '@ywfe/router';
// @ts-ignore
import { useGetAPI22504 } from '@generated/API22504.ts';
// @ts-ignore
import RootRouter from '@cli/@ywfe/yw-router';
// @ts-ignore
import { routerConfig } from '@/vite-serve/index';
// @ts-ignore
import { Switch, Route, BrowserRouter } from '@cli/react-router-dom';
import Container from './container';

const env = window.localStorage.getItem('env')
// 17020002 和 1000两个code都表示token失效
const isTokenLose = (code) => code === 17020002 || code === 1000;
const getToken = () => {
  const url = new URL(window.location.href);
  const token = url.searchParams.get('token') || window.localStorage.getItem('token') || ''
  return token;
};
const redirectLogin = () => {
  window.location.href = `https://yun-${env}.ywwl.com/login?redirectUrl=${window.location.origin}`;
};
const fetchInfo = () => {
  fetch(
    `https://${env}-gateway.ywwl.com/ywwl-admin/user/current/info`,
    {
      headers: {
        'X-TOKEN': getToken(),
      },
    }
  )
    .then((res) => res.json())
    .then((res) => {
      if (isTokenLose(res.code)) {
        return redirectLogin();
      }
      window.localStorage.setItem('token', getToken() );
      window.localStorage.setItem(
        'userId',
        res && res.data && res.data.userId
      );

      ReactDOM.render(
        <YRouter config={{ useGetModuleDataByName: useGetAPI22504 }}>
          {/* @ts-ignore */}
          <App pathName={location.pathname} />
        </YRouter>,
        document.getElementById('app'),
      );
    });
};

if (!getToken()) {
  redirectLogin();
} else {
  fetchInfo();
}

// @ts-ignore
const App: React.FC = ({ pathName }) => {
  const [noMenu, setNoMenu] = React.useState(false);

  const target = useMemo(() => {
    return Object.keys(routerConfig)?.find(route => route === pathName);
  }, [pathName]);

  useEffect(() => {
    // 是否要展示菜单， 默认本地启动有侧边菜单
    const noMenu = localStorage.getItem('VITE_SERVE_HAS_MENU') === 'false';
    setNoMenu(noMenu);
  }, []);

  return (
    <Suspense fallback={<div>Loading...</div>}>
      {noMenu ? (
        <>
        {target ? <BrowserRouter>
            <Switch>
              {Object.keys(routerConfig).map(key => {
                return (
                  <Route
                    exact
                    path={key}
                    render={() => (
                      <Container component={routerConfig[key]?.component} />
                    )}
                  />
                );
              })}
            </Switch>
          </BrowserRouter>: <div>未定义路由，访问地址请带上当前项目下的页面路由</div>}
        </>
      ) : (
        <>
          <RootRouter routerConfig={routerConfig} />
        </>
      )}
    </Suspense>
  );
};
