import React from 'react';
import { PageLoading } from '@ant-design/pro-layout';
import { Redirect, connect, ConnectProps, StateType } from 'umi';
import { stringify } from 'querystring';
import { ConnectState } from '@/models/connect';
import { CurrentUser } from '@/models/user';
import login from '@/pages/user/login';
import { getCookie } from '@/utils/method';

interface SecurityLayoutProps extends ConnectProps {
  loading?: boolean;
  currentUser?: CurrentUser;
  login?: StateType;
}

interface SecurityLayoutState {
  token:String,
  isReady: boolean;
}

class SecurityLayout extends React.Component<SecurityLayoutProps, SecurityLayoutState> {
  state: SecurityLayoutState = {
    isReady: false,
    token:"abc123",
  };

  componentDidMount() {
    this.setState({
      isReady: true,
    });
    const { dispatch ,login} = this.props;
    // console.log("安全登录中")
    // console.log(login)
    if (dispatch) {
      // dispatch({
      //   type: 'user/fetchCurrent',
      //   playload: {
      //     userName: login.userName,
      //     password: login.password
      //   }
      // });
    }
  }

  render() {
    const { isReady,token } = this.state;
    const { children, loading, currentUser,login } = this.props;
    // You can replace it to your authentication rule (such as check token exists)
    // 你可以把它替换成你自己的登录认证规则（比如判断 token 是否存在）    

    // console.log("是否已登录" + getCookie("token"))    

   // const isLogin = currentUser && currentUser.name;//isLogin为关键点
    var isLogin = false
    if (getCookie("token").length!=0) {
      isLogin=true
    }

    const queryString = stringify({
      redirect: window.location.href,
    });


    if ((!isLogin && loading) || !isReady) {
      // console.log("页面加载")
      return <PageLoading />;
    }
    if (!isLogin && window.location.pathname !== '/user/login') {
      return <Redirect to={`/user/login?${queryString}`} />;
    }
    return children;
  }
}

export default connect(({ user, loading,login}: ConnectState) => ({
  currentUser: user.currentUser,
  loading: loading.models.user,
  login: login
  
}))(SecurityLayout);
