import {FC, PropsWithChildren} from 'react';
import {HOME_PATH, LOGIN_PATH} from '@routes';
import {useStore} from 'zustand';
import {userStore} from '@stores';
import {useLocation} from 'react-router-dom';

const LDAuthentication: FC<PropsWithChildren> = function({children}) {
  const hasParent = window.location !== parent.location;
  const token = useStore(userStore, state => state.token);
  const {pathname} = useLocation();
  const parentRoutes = [HOME_PATH, LOGIN_PATH];

  // 判断当前页面是否可以不在iframe中展示
  // 只有home和login可以 其他的如果没有parent重定向到首页
  if (!parentRoutes.includes(pathname) && !hasParent) {
    location.replace(HOME_PATH);

    return null;
  }

  // 判断是否登录
  if (!token) {
    hasParent
      ? parent.location.replace(LOGIN_PATH)
      : location.replace(LOGIN_PATH);

    return null;
  }

  return <>{children}</>;
};

export default LDAuthentication;
