import React from 'react';
import './App.css';
import 'bootstrap/dist/css/bootstrap.min.css';
import {Login} from './account/Login';
import {Cookies, withCookies} from 'react-cookie';
import {Main} from "./Main";
import {Register} from "./account/Register";
import {time_score, user_cookie, user_type_cookie, welcome_cookie} from "./account/PropCookie";
import {LoginRes} from "./result";

class App extends React.Component<
    {
      allCookies:any;
      cookies:Cookies
    },
    {
      page?:JSX.Element;
      welcome?:boolean;
    }> {


  constructor(props: Readonly<any>) {
    super(props);

    this.state={}

  }

  componentDidMount() {
    if((this.props.cookies.get(user_cookie)||"").length>0){
      this.setState({
        welcome:this.props.cookies.get(welcome_cookie)!==undefined
      })

      this.setState({
        page:<Main cookies={this.props.cookies} logout={()=>this.logout()}/>
      })
    }else{
      this.toLogin()
    }
  }

//注销登录
  logout(){
    this.props.cookies.remove(user_cookie)
    this.props.cookies.remove(user_type_cookie)
    this.props.cookies.remove(time_score)
    this.toLogin()
  }

  /**
   * 跳转注册
   */
  toRegister(){
    this.setState({
      page:<Register toLogin={()=>this.toLogin()}/>
    })
  }

  /**
   * 跳转登录
   */
  toLogin(){
    this.setState({
      page:<Login toRegister={()=>this.toRegister()} onLoginSuccess={(res:LoginRes)=> {
        this.props.cookies.set(user_cookie,res.userId)
        this.props.cookies.set(user_type_cookie,res.userType)
        this.props.cookies.set(welcome_cookie,res.userId)
        this.props.cookies.set(time_score,res.timeScore)
        this.setState({
          page:<Main logout={()=>this.logout()}  cookies={this.props.cookies}/>
        })
      }}/>
    })
  }


  render() {
    return (
        <div className="App">
          {this.state.page}
        </div>
    );
  }
}

export default withCookies(App);
