import React, { useEffect, useState } from 'react';
import { Switch, Route, RouteProps } from 'react-router-dom';
import {YPageProps} from './page.interface';
import { useModuleStore } from '@/module';
import {YEmpty} from '@/layout';
import {YRouterItem} from '@/default.interface';

export const YPage: React.FC<YPageProps> = ({routers}) => {
  const [state] = useModuleStore();
  const [list, setList] = useState<string[]>([]);
  const FadingRoute = ({ component, ...rest }: RouteProps) => {
    if (!component) {
      return null;
    }
    const Comp: any = component;
    return (
      <Route
        {...rest}
        render={(routeProps: RouteProps) => (
          <Comp {...routeProps} state={state} />
        )}
      />
    );
  };

  const initRouters = (routers: YPageProps['routers'], menus: YRouterItem[]) => {
    let newList: string[] = [];
    menus.map((menu: YRouterItem) => {
      if(!menu.disable && (routers[menu.origion_url] || routers[`/${menu.origion_url}`])){
        newList.push(menu.origion_url)
      }
    });
    console.log('initRouters', newList);
    setList(newList);
  }

  useEffect(() => {
    if(state.menus && state.menus.length){
      initRouters(routers, state.menus)
    }
  }, [state.menus]);

  return (
    <>
      <Switch>
        <FadingRoute
          path="/"
          exact
          component={(state.defaultMenu?.component || !state.defaultMenu?.hidden) ? state.defaultMenu?.component : () => <YEmpty stage="no_permission" />}
        />
        {
          list.length && list.map((key: string) => {
            const router = routers[key];
            const path = key && key.indexOf('/') === 0 ? key : `/${key}`;
            return (
              <FadingRoute
                key={path}
                path={`${path}${router.param ? router.param : ''}`}
                exact
                component={router.component}
              />
            );
          })
        }
        {!list.length ? (
          <FadingRoute component={() => <YEmpty stage="no_permission" />} />
        ) : null}
      </Switch>
    </>
  )
}