import './login.scss'
import {useContext, useEffect, useState} from "react";
import {Root} from "../../dataCenter/Root";
import {useFormState} from "../../utils/hook";

function Login(props) {
    const {fetchData, dataCenter} = useContext(Root)
    const [needLogin,setNeedLogin] = useState(false)
    const [input, setInput] = useFormState()
    const getUser = ()=>{
        fetchData('/users/getUser', {uid:'100001'}, 'userInfo')
            .then(res => res.data.uid && (window.location.href = '/index'))
            .catch(res =>
                res.code === 70001 && setNeedLogin(true)
            )
    }
    const doLogin = () => {
        if (needLogin){
            fetchData('/users/login',{uid: '100001'})
                .then(()=>{
                    getUser()
                })
        }else {
            getUser()
        }
    }
    useEffect(() => {
        if (dataCenter.userInfo) {
            // window.location.href = '/index'
        }
    }, [dataCenter.userInfo])

    useEffect(() => {
        doLogin()
    }, [])
    return (
        <div className="login">
            <div className='loginDiv'>
                {
                    needLogin &&  <input type="text" onChange={e => setInput('uid',e.target.value)} defaultValue={input.uid}/>
                }
                <button className='btn-login' onClick={() => doLogin()}>登录</button>
            </div>

        </div>
    )
}

export default Login
