import React from 'react';
import Cookies from 'js-cookie';
import { connect } from 'react-redux';
import { Redirect } from 'react-router-dom';
import { PageLoading } from '@ant-design/pro-layout';
import { stringify } from 'querystring';
import { getBaseName } from '../utils/utils';

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

  componentDidMount() {
    this.setState({
      isReady: true,
    });
    document.title = this.props.global.title;
  }

  render() {
    const { isReady } = this.state;
    const { children, global, loading } = this.props;
    const isLogin = Cookies.get('token') !== null && global.token !== null;
    const queryString = stringify({
      redirect: window.location.href,
    });

    if ((!isLogin && loading) || !isReady) {
      return <PageLoading />;
    }
    if (
      !isLogin &&
      window.location.pathname !== `/${getBaseName()}/user/login`
    ) {
      this.props.updateCurrentIndex && this.props.updateCurrentIndex(0);
      return (
        <Redirect to={`/user/login?client=${global.client}&${queryString}`} />
      );
    }
    return children;
  }
}

const mapStateToProps = state => ({
  global: state.getIn(['global', 'globalConfig']),
});
export default connect(
  mapStateToProps,
  null,
)(SecurityLayout);
