import React from 'react';
import { connect } from 'dva';
import { Redirect } from 'umi';
import PageLoading from '@/components/PageLoading';
import localStorage from '@/utils/localStorage';

class SecurityLayout extends React.Component {
  state = {
    isReady: false,
  };

  componentDidMount() {
    const { dispatch } = this.props;
    if (dispatch) {
      dispatch({
        type: 'user/fetchCurrent',
      });
    }
    const delaySet = () => this.setState({ isReady: true });
    setTimeout(() => {
      delaySet();
    }, 0);
  }

  /* eslint-disable no-underscore-dangle */
  render() {
    const { isReady } = this.state;
    let isLogin = true;
    // 你可以把它替换成你自己的登录认证规则（比如判断 token 是否存在）
    const { children, loading } = this.props;
    if (!localStorage.get('token')) {
      isLogin = false;
    }

    // 切换子应用布局
    if (window.__POWERED_BY_QIANKUN__) {
      const container = document.querySelector('#container');
      container.classList.add('micro-layout');
    }

    if ((!isLogin && loading) || !isReady) {
      return <PageLoading />;
    }
    if (!isLogin) {
      if (window.__POWERED_BY_QIANKUN__) {
        window.location.href = `${window.origin}/access/login`;
        return undefined;
      }

      return <Redirect to="/user/login"></Redirect>;
    }
    return children;
  }
}

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