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

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

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

  /* eslint-disable no-underscore-dangle */
  render() {
    // 判断是否从tob进入
    const searchPrams = getUrlSearchParams();
    const isTob = searchPrams.source === 'tob';
    if (isTob) {
      localStorage.set('tobToken', searchPrams.token || '');
      // role 类型 (platform:平台, enterprise:企业, pop:pop商)
      sessionStorage.set('role', searchPrams.role);
    }

    const { isReady } = this.state;
    let isLogin = true;
    // 你可以把它替换成你自己的登录认证规则（比如判断 token 是否存在）
    const { children, loading } = this.props;
    if (!getToken()) {
      isLogin = false;
    }
    console.log('getToken() :>> ', getToken());
    console.log('isLogin :>> ', isLogin);

    // 切换子应用布局
    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);
