'use strict';
import React, { useEffect, useRef } from 'react';
import { connect } from 'react-redux';
import { push } from 'react-router-redux';
import { Form, Button, Toast } from '@douyinfe/semi-ui';
import { login } from '../actions/auth';

const Login = props => {
    const { dispatch, user, error, isRequesting } = props
    const form = useRef();

    useEffect(() => {
        if (error) {
            Toast.error(error);
            form.current.setValue('password', '')
        }
    }, [error])

    useEffect(() => {
        if (user && user.authorized) {
            dispatch(push('/example/e1'));
        }
    }, [user])

    return (
        <div style={{
            height: '100vh',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
        }}>
            <div style={{
                width: 400,
                height: 410,
                padding: 30,
            }}>
                <p style={{ fontSize: 21, fontWeight: 'bold', textAlign: 'center' }}>飞尚物联</p>
                <Form
                    onSubmit={values => {
                        dispatch(login(values.username, values.password))
                    }}
                    getFormApi={formApi => form.current = formApi}
                >
                    <Form.Input field='username' label='用户名' />
                    <Form.Input field='password' mode="password" autoComplete="" label='密码' />
                    <Button htmlType='submit' block theme="solid" >登录</Button>
                </Form>
            </div>
        </div>
    );
}

function mapStateToProps (state) {
    const { auth } = state;
    return {
        user: auth.user,
        error: auth.error,
        isRequesting: auth.isRequesting
    }
}

export default connect(mapStateToProps)(Login);