import React from 'react'
import Login from 'ant-design-pro/lib/Login'
import { Alert, Checkbox, Icon } 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, autoLogin, cb ) {
    window.localStorage.setItem("loginTime", new Date().getTime());
    window.localStorage.setItem("token", token);
    window.localStorage.setItem("expireTime", expireTime);

    window.localStorage.setItem("usercode", user.code);
    autoLogin ? window.localStorage.setItem("autoLogin", 'true') : window.localStorage.setItem("autoLogin", 'false');
    autoLogin ? window.localStorage.setItem("account", user.account) : window.localStorage.removeItem('account');
    autoLogin ? window.localStorage.setItem("password", user.password) : window.localStorage.removeItem('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: window.localStorage.getItem('autoLogin') ? window.localStorage.getItem('autoLogin') === 'true' : true,
        redirectToReferrer: false,
        fetching: false
    };

    onSubmit = (err, values) => {
        this.setState({
            notice: '',
        }, () => {
            if (!err && !!values.username && !!values.password) {
                this.login(values.username, values.password);
            }
        });
    }
    changeAutoLogin = (e) => {
        this.setState({
            autoLogin: e.target.checked,
        });
    }

    login = (username, password) => {
        const { dispatch } = this.props;
        const { autoLogin } = this.state;

        const self = this;
        let body = {
            userName: username,
            passWord: password
        };
        this.setState({
            fetching: true
        }, () => {
            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,
                    });
                    throw (r.err || r.data.msg);
                }
            }).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, autoLogin, () => {
                    this.setState({
                        redirectToReferrer: true,
                        fetching: false
                    });
                });
            }).catch(ex => {
                this.setState({
                    fetching: false
                });
                console.error('登录失败', ex);
            });
        });
    };

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

        const defaultAccount = window.localStorage.getItem('account');
        const defaultPassword = window.localStorage.getItem('password');

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

        return (
            <div className='container'>
                <div className='content'>
                    <div className='main'>
                        <h3>登录</h3>
                        <Login
                            className='login'
                            onSubmit={this.onSubmit}
                        >
                            {
                                notice &&
                                <Alert style={{ marginBottom: 24 }} message={notice} type="error" showIcon closable />
                            }
                            <UserName
                                name="username"
                                disabled={fetching}
                                placeholder='输入用户名'
                                defaultValue={autoLogin ? defaultAccount : ''}
                                onChange={() => {
                                    this.setState({
                                        notice: ''
                                    });
                                }}
                                rules={[{
                                    required: true,
                                    message: '用户名不能为空'
                                }]}
                                onPressEnter={(e) => {
                                    document.getElementsByClassName('antd-pro-login-submit')[0].click();
                                }}
                            />
                            <Password
                                name="password"
                                disabled={fetching}
                                placeholder='输入密码'
                                defaultValue={autoLogin ? defaultPassword : ''}
                                onChange={() => {
                                    this.setState({
                                        notice: ''
                                    });
                                }}
                                rules={[{
                                    required: true,
                                    message: '密码不能为空'
                                }]}
                                onPressEnter={(e) => {
                                    document.getElementsByClassName('antd-pro-login-submit')[0].click();
                                }}
                            />
                            <div>
                                <Checkbox defaultChecked={autoLogin} onChange={this.changeAutoLogin}>记住密码</Checkbox>
                                <a style={{ float: 'right' }} href="">忘记密码</a>
                            </div>
                            <Submit disabled={fetching}>
                                {fetching && <Icon type="loading" theme="outlined" />}
                                {fetching ? '登录中...' : '登录'}
                            </Submit>
                            <div>
                                <Link to="/register">
                                    <span style={{ float: 'right' }} href="">注册</span>
                                </Link>
                            </div>
                        </Login>
                    </div>
                </div>
            </div>
        );
    }
}

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