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 _ from 'lodash';
import { store, helpers } from '@wisdom-utils/utils';
class SecurityLayout extends React.Component {
  state = {
    isReady: false,
  };

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

  componentWillReceiveProps(nextProps) {
    const products = (this.props.global.products || []).map(item => {
      if(item.PackageName === 'civweb4') {
        return 'web4_console'
      }
      return `${item.PackageName}-main`;
    });
    const location = this.props.location;
    const pathname = location.pathname;
    const argv = pathname.split('/');

    const nextPathname = nextProps.location.pathname;
    const nextArgv = nextPathname.split('/');
    console.log(argv[2], nextArgv[2])
    if(argv[2] !== nextArgv[2]) {
      Object.keys(products).forEach(item => {
        window[products[item]] && window[products[item]] && window[products[item]].unmount && window[products[item]].unmount({store: store});
      });
    }
    if(this.props.location.pathname !== nextProps.location.pathname) {
      store.set('event:globalConfig', {globalConfig: nextProps.global});
    }
   
  }

  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 (!Cookies.get('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 =  !_.isNull(generateType) && !_.isUndefined(generateType) && generateType !== 'undefined' ? `&generateType=${generateType}` : '';
      return (
        <Redirect
          to={`/user/login?client=${client}${generateType}`}
        />
      );
    }

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

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