import React, { useState, useEffect } from 'react';
import { connect } from 'dva';
import { PageLoading } from '@ant-design/pro-layout';
import { Redirect } from 'umi';
import { stringify } from 'querystring';

const SecurityLayout = (props) => {
  const [isReady, setIsReady] = useState(false)

  const { children, loading, currentUser, history } = props;

  const isLogin = currentUser && currentUser.userId;

  const queryString = stringify({
    redirect: window.location.href,
  });
  
  useEffect(() => {
    setIsReady(true)
    props.dispatch({
      type: 'user/fetchCurrent',
    });
  }, [])

  if (loading || !isReady) {
    return <PageLoading />;
  }

  if (!isLogin) {
    return <Redirect to={`/user/login?${queryString}`} />;
  }

  return children;
}

export default connect(({ user, loading }) => ({
  currentUser: user.currentUser,
  loading: loading.models.user,
}))(SecurityLayout);
