/**
 * 账号相关js
 *
 * @author CaiAoLin
 * @date 2018/1/26
 * @version
 */
$(document).ready(function() {
    try {
        if (user !== '') {
            $(".title-bar h2").text(user);
        }

        const options = {
            rules: '',
            errorPlacement: function(error, element) {
                $(element).addClass('is-invalid');
                $(element).after(error);
            },
            errorClass: "invalid-feedback",
            errorElement: "div",
            highlight: false,
            success: function(element) {
                $(element).prev('input').removeClass('is-invalid');
                $(element).remove();
            },
        };

        options.rules = {
            auth_mobile: {
                mobile: true,
                required: true,
            },
        };
        $("#mobile-form").validate(options);
        // 获取验证码
        let isPosting = false;
        $("#get-code").click(function() {
            if (isPosting) {
                return false;
            }
            if(!$("#mobile-form").valid()) {
                return false;
            }

            const mobile = $("input[name='auth_mobile']").val();
            const btn = $(this);

            $.ajax({
                url: '/profile/code?_csrf=' + csrf,
                type: 'post',
                data: { mobile: mobile },
                dataTye: 'json',
                error: function() {
                    isPosting = false;
                },
                beforeSend: function() {
                    isPosting = true;
                },
                success: function(response) {
                    isPosting = false;
                    if (response.err === 0) {
                        codeSuccess(btn);
                    } else {
                        alert(response.msg);
                    }
                }
            });
        });

        // 绑定按钮
        $("#bind-btn").click(function() {
            const code = $("input[name='code']").val();
            if (code.length < 6) {
                alert('请填写正确的验证码');
                return false;
            }
        });
    } catch (error) {
        console.log(error);
    }

});

/**
 * 获取成功后的操作
 *
 * @param {Object} btn - 点击的按钮
 * @return {void}
 */
function codeSuccess(btn) {
    let counter = 60;
    btn.addClass('disabled').text('重新获取 ' + counter + 'S');
    btn.parent().siblings('input').removeAttr('readonly').attr('placeholder', '输入短信中的5位验证码');
    const bindBtn = $("#bind-btn");
    bindBtn.removeClass('btn-secondary disabled').addClass('btn-primary');

    const countDown = setInterval(function() {
        const countString = counter - 1 <= 0 ? '' : ' ' + (counter - 1) + 'S';
        // 倒数结束后
        if (countString === '') {
            clearInterval(countDown);
            btn.removeClass('disabled');
        }
        const text = '重新获取' + countString;
        btn.text(text);
        counter -= 1;
    }, 1000);
}
