import React from 'react';
import Cookies from 'js-cookie';
import { connect } from 'react-redux';
import { Redirect, history } from '@wisdom-utils/runtime';
import { PageLoading } from '@ant-design/pro-layout';
import _ from 'lodash';
import { stringify } from 'querystring';
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('/');
    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 tk = Cookies.get('token') || global.token;
    const isLogin = tk !== null && tk !== 'undefined' && tk !== (void 0);
    if (!isLogin && window.location.pathname !== '/civbase/user/login' || (global.hasOwnProperty('size') && global.size === 0)) {
      const { query = {}, search, pathname } = history.location;
      const { redirect } = query;
      // const queryString = stringify({
      //   redirect: pathname + search,
      // });
      this.props.updateCurrentIndex && this.props.updateCurrentIndex(0);
      let client = global.client || Cookies.get('client');
      client = client !== 'undefined' && !_.isNull(client) && !_.isUndefined(client) ? client : 'city';
      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);
