import React from 'react'
import Login from 'ant-design-pro/lib/Login'
import { Alert, Checkbox } from 'antd'
import { Link, Redirect } from 'dva/router'
import { connect } from 'dva'
import * as service from '../../../services/index'
import URLS from '../../../constants/url'
import './login.less'

const { UserName, Password, Submit } = Login;

function authenticate(token, expireTime, user, cb) {
    window.localStorage.setItem("token", token);
    window.localStorage.setItem("expireTime", expireTime);

    window.localStorage.setItem("usercode", user.code);
    window.localStorage.setItem("account", user.account);
    // window.localStorage.setItem("password", user.password);
    window.localStorage.setItem("username", user.name);
    window.localStorage.setItem("userrole", user.role);

    setTimeout(cb, 100); // fake async
}

class LoginComponent extends React.Component {
    state = {
        notice: '',
        autoLogin: true,
        redirectToReferrer: false
    };

    onSubmit = (err, values) => {
        console.log('value collected ->', { ...values, autoLogin: this.state.autoLogin });
        this.setState({
            notice: '',
        }, () => {
            if (!err) {
                this.login(values.username, values.password);
            }
        });
    }
    changeAutoLogin = (e) => {
        this.setState({
            autoLogin: e.target.checked,
        });
    }

    login = (username, password) => {
        const { dispatch } = this.props;
        const self = this;
        let body = {
            userName: username,
            passWord: password
        };
        service.fetch({
            url: URLS.LOGIN,
            body: body
        }).then(r => {
            if(!r.err && r.data.code > 0) {
                return r.data.data;
            }else {
                self.setState({
                    notice: r.err || r.data.msg,
                });
                let obj = {};
                throw obj;
            }
        }).then(resData => {
            console.log('登录', body, resData);
            const token = resData.token;
            const expireTime = resData.times;
            const user = resData.user;
            const currentUser = {
                code: user.id,
                account: user.userName,
                password: user.passWord,
                name: user.name,
                role: user.role
            };
            dispatch({ type: 'main/setCurrentUser', user: currentUser });
            authenticate(token, expireTime, currentUser, () => {
                this.setState({ redirectToReferrer: true });
            });
        }).catch(ex => {
            console.error('fetch error', ex);
        });
    };

    render() {
        const { from } = this.props.location.state || { from: { pathname: "/" } };
        const { redirectToReferrer } = this.state;

        if (redirectToReferrer) {
            return <Redirect to={from} />;
        }

        return (
            <div className='container'>
                <div className='content'>
                    <div className='main'>
                        <h3>登录</h3>
                        <Login
                            className='login'
                            onSubmit={this.onSubmit}
                        >
                            {
                                this.state.notice &&
                                <Alert style={{ marginBottom: 24 }} message={this.state.notice} type="error" showIcon closable />
                            }
                            <UserName name="username" placeholder='输入用户名' />
                            <Password name="password" placeholder='输入密码'/>
                            <div>
                                <Checkbox checked={this.state.autoLogin} onChange={this.changeAutoLogin}>记住密码</Checkbox>
                                <a style={{ float: 'right' }} href="">忘记密码</a>
                            </div>
                            <Submit>登录</Submit>
                            <div>
                                <Link to="/register">
                                    <span style={{ float: 'right' }} href="">注册</span>
                                </Link>
                            </div>
                        </Login>
                    </div>
                </div>
            </div>
        );
    }
}

export default connect(({ present: { main } }) => ({ main }))(LoginComponent);
