/**
 * 登录相关js
 *
 * @author CaiAoLin
 * @date 2017/6/8
 * @version
 */
$(document).ready(function () {
    let referer = scUrlUtil.GetQueryString('referer');

    $("#login").click(function () {
        if (!valid()) {
            return false;
        }
        let account = $("#inputEmail").val();
        let pw = $("#inputPassword").val();

        $.ajax({
            url: '/login',
            type: 'post',
            data: {"account": account, "pw": pw},
            success: function (response) {
                if (response.error === 0) {
                    if (response.exist == 1) {
                        location.href = '/pm';
                    } else {
                        $('#ver').modal('show');
                    }
                    // if (referer) {
                    //     location.href = referer;
                    // } else {
                    //     location.href = '/';
                    // }
                } else {
                    let msg = response.msg !== undefined ? response.msg : '未知错误';
                    showError(msg, $("input"));
                }
            },
            error: function (result) {
                showError('内部程序错误', null);
            }
        });
    });

    $("input").blur(function () {
        cleanError();
    });

    $(".form-control").on('input', function () {
        $('#hint').html('&nbsp;');
    });

});

/**
 * 验证数据
 *
 * @return {boolean}
 */
function valid() {
    let result = true;
    let account = $("#inputEmail").val();
    if (account === undefined || account === '') {
        showError('用户名不能为空!', $("#inputEmail"));
        return false;
    }

    let password = $("#inputPassword").val();
    if (password === undefined || password === '') {
        showError('密码不能为空!', $("#inputPassword"));
        return false;
    }

    return result;
}

/**
 * 提示错误
 *
 * @param {string} msg
 * @param {object} element
 * @return {void}
 */
function showError(msg, element) {
    if (element !== null) {
        element.parent().addClass('has-danger');
    }
    $("#message").text(msg);
    $("#error-tips").show("fast");
}

/**
 * 清除错误提示
 *
 * @return {void}
 */
function cleanError() {
    $("input").parent().removeClass('has-danger');
    $("#message").text('');
    $("#error-tips").hide("fast");
}