/**
 * 登录相关js
 *
 * @author CaiAoLin
 * @date 2017/6/1
 * @version
 */
let rules = {
    username: {
        required: true,
        minlength: 2
    },
    password:{
        required: true,
        minlength: 4
    }
};
$(document).ready(function() {
    console.log($('#password').val());
    $("#login-form").validate({
        rules: rules,
        errorPlacement: function(error, element) {
            error.addClass('help-block');
            let parentEle = $(element).parent();
            parentEle.parent().addClass('has-error');
            $(element).parent().after(error);
        },
        errorElement: "span",
        success: function(element) {
            $("#common-error").remove();
            $(element).parent().removeClass('has-error');
        }
    });

    // 登录操作
    let isLogin = false;
    $("#login").click(function() {
        if (isLogin) {
            return false;
        }
        // 验证数据
        if (!$("#login-form").valid()) {
            return false;
        }
        let username = $("#username").val();
        let password = $("#password").val();
        $.ajax({
            url: '/login/login',
            type: 'post',
            data: {username: username, password: password},
            dataType: 'json',
            error: function() {
                isLogin = false;
            },
            beforeSend: function() {
                isLogin = true;
            },
            success: function(response) {
                isLogin = false;
                if (response.error === 0) {
                    // 正确则跳转
                    window.location.href = '/dashboard';
                } else {
                    // 错误则提示
                    show_error(response.msg);
                }
            }
        });
    });
});
/**
 * 显示错误
 *
 * @param {string} msg
 * @return {void}
 */
function show_error(msg) {
    $("form > .form-group").addClass('has-error');
    $("input").last().parent().after('<span id="common-error" class="error help-block">'+ msg +'</span>');
}