index.js 8.95 KB
/**
 * 登录
 * @author: xuqi<qi.xu@yoho.cn>
 * @date: 2015/12/11
 */
var $ = require('yoho-jquery');
var EventProxy = require('../common/eventproxy');

var $account = $('#account'),
    $password = $('#password'),
    $captcha = $('#captcha'),
    $login = $('#login-btn'),
    $phone = $('#phone');

var $loginTip = $login.siblings('.login-fail-tip'),
    ep = new EventProxy();

var $countryCodeEm = $('#country-code'),
    $countryList = $('#country-list');

var $emailAutoComplete = $('#email-autocomplete');

var mailPhoneRegx = require('../common/mail-phone-regx');
var mailAc = require('../common/ac-email'); // 邮箱自动完成

var $remember = $('.remember-me');

var captchaUrl = '/passport/images?t='; // /passport/images?t=1454464125

var $captchaWrap = $('.captcha-wrap'),
    $captchaImg = $captchaWrap.find('#captcha-img');

// checkbox status unicode
var checkbox = {
    checked: '&#xe602;',
    unchecked: '&#xe601;'
};

var emailAcTime;

var $errTip = $('.tips');
var $errMsg = $errTip.find('.rectangle');

$captcha = $captchaWrap.find('#captcha');

require('../../plugins/tips');
require('yoho-jquery-placeholder');

function errTip(ele, msg) {
    var topLeft = ele.offset();

    $errMsg.text(msg);
    return $errTip.css({
        top: topLeft.top + ele.height() - 2,
        left: topLeft.left,
        width: ele.width() + 2,
        height: ele.height
    }).removeClass('hide');
}


// 验证账户名
function validateAccountLocal() {
    var account = $.trim($account.val()),
        countryCode = $countryCodeEm.val();

    if (account !== '') {
        if (/^[0-9]+$/.test(account)) {
            // 不是11位
            if (account.length !== 11) {
                ep.emit('phone', false);
                errTip($phone, '手机号码不正确,请重新输入');
                return false;
            }

            // 如果是纯数字,则作为手机号码处理
            if (countryCode !== '+86' ||
                mailPhoneRegx.phoneRegx[countryCode].test(account)) {
                ep.emit('phone', true);
                return true;
            } else {
                ep.emit('phone', false);
                errTip($phone, '手机号码不正确,请重新输入');
                return false;
            }
        } else {

            // 邮箱验证
            if (mailPhoneRegx.emailRegx.test(account)) {
                ep.emit('phone', true);
                return true;
            } else {
                ep.emit('phone', false);
                errTip($phone, '邮箱格式不正确,请重新输入');
                return false;
            }
        }

    } else {
        ep.emit('phone', false);
        errTip($phone, '请输入账号');
        return false;
    }
}

function validateAccountAsync() {
    return $.ajax({
        type: 'POST',
        url: '/passport/login/user',
        data: {
            phoneNum: $account.val(),
            area: $countryCodeEm.val().replace('+', '')
        }
    }).then(function(data) {
        if (data.code && data.code === 200) {
            ep.emit('phone', true);
            return true;
        } else {
            ep.emit('phone', false);
            errTip($phone, '账号不存在');
            return false;
        }
    });
}

function validateAccount() {
    var defer = $.Deferred(); // eslint-disable-line

    if (validateAccountLocal()) {
        validateAccountAsync().then(function(result) {
            defer.resolve(result);
        });
    } else {
        defer.resolve(false);
    }

    return defer.promise();
}

// 验证密码
function validatePasswordLocal() {
    var password = $.trim($password.val());
    var length = password.length;

    if (length !== 0) {
        if (length < 6) {
            ep.emit('password', false);
            errTip($password, '请输入长度为6-20字符的密码');
            return false;
        } else {
            ep.emit('password', true);
            return true;
        }
    } else {
        errTip($password, '请输入密码');
        ep.emit('password', false);
        return false;
    }
}

// 验证验证码
function validateCaptchaLocal() {
    var captcha = $.trim($captcha.val());
    var length = captcha.length;

    if ($captchaWrap.hasClass('hide')) {
        ep.emit('captcha', true);
        return;
    }

    switch (length) {
        case 0:
            errTip($captcha, '请输入验证码');
            ep.emit('captcha', false);
            break;
        case 4:
            ep.emit('captcha', true);
            break;
        default:
            errTip($captcha, '请输入长度为4字符的验证码');
            ep.emit('captcha', false);
            break;
    }
}

// 密码错误次数,超过三次显示验证码
function showAccountErrTimes() {
    $captchaWrap.removeClass('hide');
    $captchaImg.attr('src', captchaUrl + $.now());
    $captcha.val('');
}

// 登录
function login() {
    $.ajax({
        url: '/passport/login/auth',
        type: 'POST',
        data: {
            areaCode: $countryCodeEm.val().replace('+', ''),
            account: $.trim($account.val()),
            password: $.trim($password.val()),
            captcha: $.trim($captcha.val()),
            isRemember: $remember.hasClass('checked') ? true : false
        },
        success: function(res) {
            if (res.code === 200) {
                if (res.data) {

                    // 防止data.data为undefined时下行语句执行出错而导致脚本不能走到complete去处理authing
                    location.href = res.data.session;
                }
            } else {
                if (res.data.errorType === 'captcha') {
                    $captcha.val('');
                } else {
                    $loginTip.removeClass('hide').children('em').html(res.message);
                    $password.val('');
                }

                // 验证错误次数
                if (res.data && res.data.needCaptcha) {
                    showAccountErrTimes();
                }
            }
        }
    });
}

mailAc($account, function() {
    function validateUser() {
        return $.ajax({
            url: '/passport/login/account',
            type: 'GET',
            data: {
                account: $.trim($account.val())
            }
        });
    }

    $.when(validateAccount()).then(function(result) {
        if (result) {
            return $.when(validateUser());
        } else {
            return $.when(false);
        }
    }).then(function(res) {
        if (!res) {
            return;
        }

        if (res.data && res.data.needCaptcha) {
            showAccountErrTimes();
        }
    });
});

$account.on('focus', function() {
    $phone.addClass('focus');
}).on('blur', function() {
    $phone.removeClass('focus');
});

$('[placeholder]').placeholder();

$countryList.change(function() {
    var $this = $(this);

    $countryCodeEm.text($this.val());
});

// 密码
$password.on('blur', function() {
    $password.removeClass('focus');
    validatePasswordLocal();
    $captcha.trigger('blur');
}).on('focus', function() {
    $password.addClass('focus');
});

// 验证码
$captcha.on('blur', function() {
    $captcha.removeClass('focus');
    validateCaptchaLocal();
}).on('focus', function() {
    $captcha.addClass('focus');
});

// 邮箱自动完成列表项点击
$emailAutoComplete.on('click', 'li', function() {
    clearTimeout(emailAcTime); // 清空默认关闭
    $account.val($(this).text()).focus();
    $emailAutoComplete.addClass('hide');
});

// 记住登录状态
$remember.on('click', function() {
    var $this = $(this);

    $this.toggleClass('checked');

    if ($this.hasClass('checked')) {
        $this.children('span').html(checkbox.checked);
    } else {
        $this.children('span').html(checkbox.unchecked);
    }
});

// focus到输入框则隐藏错误提示和样式
$('.va').on('focus', function() {
    var $this = $(this);

    $this.siblings('.err-tip').addClass('hide');
});

// 验证码刷新
$captchaWrap.on('click', '.change-captcha, .captcha-img', function() {
    $captchaImg.attr('src', captchaUrl + $.now());
});

// 初始:只带账户名的页面,密码输入获得焦点
if (($account.val() !== '' || $account.val() === $account.attr('placeholder')) &&
    $password.val() === '') {
    $password.focus();
}

ep.tail('phone', 'password', 'captcha', function(phoneAuth, passwordAuth, captchaAuth) {
    if (phoneAuth && passwordAuth && captchaAuth) {
        $login.removeClass('auth_ok');
    } else {
        $login.addClass('auth_ok');
    }
});

ep.on('phone', function(auth) {
    if (auth) {
        $errTip.addClass('hide');
    }
});

ep.on('password', function(auth) {
    if (auth) {
        $errTip.addClass('hide');
    }
});

ep.on('captcha', function(auth) {
    if (auth && !$captchaWrap.hasClass('hide')) {
        $errTip.addClass('hide');
    }
});

// 登录
$login.on('click', function() {
    if ($login.hasClass('auth_ok')) {
        return;
    }

    login();
});

// Enter登录
$('input.va').on('keypress', function(e) {
    if (e.which === 13) {
        login();
    }
});