import React from 'react';
import Cookies from 'js-cookie';
import { connect } from 'react-redux';
import { Redirect } from '@wisdom-utils/runtime';
import { PageLoading } from '@ant-design/pro-layout';
import { event } from 'microser-data';
import { stringify } from 'querystring';
import { getBaseName } from '../utils/utils';
import _  from 'lodash';

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(_.isNull(global.token) || (global.hasGateWay && _.isNull(global.access_token))) {
      this.props.updateCurrentIndex && this.props.updateCurrentIndex(0);
      let client = global.client || Cookies.get('city');
      client =  client !== 'undefined' && !_.isNull(client) && !_.isUndefined(client) ? client: 'city';
      // event.emit(？'event:initConfig');
      let generateType = global.generateType;
      generateType = !_.isNull(generateType) && !_.isUndefined(generateType) && generateType !== 'undefined' ? `&generateType=${generateType}` : '';
      return (
        <Redirect to={`/user/login?client=${client}${generateType}`} render={() => window.location.reload()}/>
      );
    }


    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);
