var checkPattern = function ($this) {
    var val = $this.val(), pattern = $this.attr('x-pattern'), b = true;
    if (val && pattern) {
        b = new RegExp(pattern).test(val);
    }
    return b;
};

var app = {
    loading: function (is, position) {
        app.isLoading = is;
        toastr.clear();
        $('#loading').css('display', is ? 'block' : 'none');
        is && position && ($('#loading').addClass(position));
    },
    info: function (message, title, position) {
        toastr.clear();
        toastr.info(message, title, {
            positionClass: 'toast-' + (position || 'top-center'),
            timeOut: 5000
        });
    },
    error: function (message, title, position) {
        toastr.clear();
        toastr.error(message, title, {
            positionClass: 'toast-' + (position || 'top-center')
        });
    },
    /**
     * 禁用/启用发送验证码按钮
     * @param el
     * @param value
     */
    enableCheckcode: function () {
        var telInput = $('[name=mobile]'), checkcodeBtn = $('.x-btn-checkcode');
        var nameInput = $("[name=name]");

        function updateEnable() {
            var timeout = localStorage.getItem('checkcodeTimeOut');
            if (!(timeout && timeout > 0) && telInput.val() && checkPattern(telInput) && nameInput.val() && checkRealLen(nameInput.val()) < 20 && $("#adminTel_help").css("display") == "block") {
                checkcodeBtn.removeAttr('disabled');
            } else {
                checkcodeBtn.attr('disabled', 'disabled');
            }
        };
        telInput.bind('blur', function (event) {
            if (/^[\d-]{8,11}$/.test(this.value)) {
                $.ajax({
                    url: 'sso/user/checkTelEnable',
                    type: 'GET',
                    dataType: 'json',
                    data: {
                        uid: this.value
                    },
                    success: function (data) {
                        if (data.error) {
                            toggleError(telInput, false, "该手机号已被注册");
                        } else {
                            updateEnable();
                        }
                    }
                });
            }
        });
        nameInput.bind('blur', function (event) {
            updateEnable();
        });
    },
    /**
     * 获取验证码
     * @param e
     */
    getCheckcode: function (e) {
        var me = $(this);
        app.loading(true);
        $.get('sso/user/checkcode', {
            tel: $('[name=mobile]').val(),
            pageToken: $('[name=pageToken]').val()
        }, function (res) {
            app.loading(false);
            if (res && res.success) {
                me.attr('disabled', 'disabled');
                $('[name=checkcode]').show();
                $('[name=checkcode]').data('token', res.content.token);
                $('[name=checkcodeToken]').val(res.content.token);
                app.checkcodeTimeout(60);
                app.info('验证码已经发送到您的手机，请注意查收');
            } else {
                app.error(res.errMsg || '程序错误')
            }
        });
    },
    /**
     * 获取验证码倒计时
     * @param time
     */
    checkcodeTimeout: function (time) {
        var localStorageKey = 'checkcodeTimeOut';
        time = time || localStorage.getItem(localStorageKey);
        if (time > 0) {
            $('.x-timeout-word').show().siblings().hide();
            app.checkcodeInterval = setInterval(function () {
                $('.x-timeout-num').text(time);
                time--;
                localStorage.setItem(localStorageKey, time);
                if (time < 0) {
                    app.removeCheckcodeInterval();
                }
            }, 1000);
        }
    },
    /**
     * 验证验证码是否正确
     * @param el
     * @param val
     */
    checkCheckcode: function (el, code) {
        var token = el.data('token');
        var tel = $("input[name='mobile']").val();
        if (token) {
            $.post('sso/user/checkcode', {
                token: token,
                code: code,
                tel: tel,
            }, function (res) {
                if (res.success) {
                    // app.info('验证码正确');
                    //app.onCheckSuccess();
                } else {
                    // app.error(res.errMsg);
                    el.addClass('x-error');
                    toggleError(el, false, res.errMsg);
                }
            });
        } else {
            app.error('请先获取验证码');
            el.addClass('x-error');
        }
    },

    removeCheckcodeInterval: function () {
        localStorage.removeItem('checkcodeTimeOut');
        $('.x-timeout-word').hide().siblings().show();
        clearInterval(app.checkcodeInterval);
        var telInput = $('[name=mobile]'), checkcodeBtn = $('.x-btn-checkcode');
        if (telInput.val() && checkPattern(telInput)) {
            checkcodeBtn.removeAttr('disabled');
        }
    },
    onCheckSuccess: function () {
        var interval = app.checkcodeInterval;
        if (interval) {
            // clear interval
            app.removeCheckcodeInterval();
        }
        // 验证码没问题，且未修改手机号情况下，不应该继续点击“获取验证码”
        $('.x-btn-checkcode').attr('disabled', 'disabled');
    },
    init: function () {
        app.loading(false);
        $('#x-reg-question').popover();
        app.enableCheckcode();
        // 提交注册表单
        $('.reg-form').validation({
            // 允许没校验过的情况下点击按钮，这样可以提示错误在哪
            disable: false,
            success: function (form, data) {
                if (!data.agree) {
                    app.error('您还未同意优软平台服务协议');
                } else {
                    // 提交用户注册
                    var interval = app.checkcodeInterval;
                    if (interval) {
                        // clear interval
                        app.removeCheckcodeInterval();
                    }
                    app.registerUer(data);
                }
            },
            error: function (form, errEl, errMsg) {
                app.error(errMsg);
            },
            listeners: {
                'checkcode': app.checkCheckcode,
                'name': function (el, val) {
                    if (checkRealLen(val) > 20) {
                        toggleError(el, false, "请勿超过20个字符");
                        el.addClass('x-error');
                    }
                }
            }
        });
        $('.x-btn-checkcode').click(app.getCheckcode);
        app.checkcodeTimeout();

        var pwdForm = $('.pwd-form');
        // 设置密码表单
        pwdForm.validation({
            disable: false,
            success: function (form, data) {
                // 提交设置密码
                app.setPassword(data);
            },
            error: function (form, errEl, errMsg) {
                app.error(errMsg);
            },
            listeners: {
                'password': function (el, val) {
                    var oth = pwdForm.find('input[name=passwordConfirm]');
                    if (oth.val() && val != oth.val()) {
                        // app.error('密码不一致');
                        $('#passwordConfirm_err').show();
                        $('#passwordConfirm_help').hide();
                    }
                },
                'passwordConfirm': function (el, val) {
                    var oth = pwdForm.find('input[name=password]');
                    if (val != oth.val()) {
                        //el.addClass('x-error');
                        // app.error('密码不一致');
                        $('#passwordConfirm_err').show();
                        $('#passwordConfirm_help').hide();
                    }
                }
            }
        });
    },
    /**
     * 提交用户注册
     * @param formData
     */
    registerUer: function (formData) {
        app.loading(true);
        $.ajax('sso/user/register', {
            data: formData,
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                app.loading(false);
                if (data.success) {
                    window.location.reload();
                } else if (data.errMsg) {
                    if (data.errMsg == 'registed') {
                        app.registedModal(formData.mobile);
                    } else
                        app.error(data.errMsg);
                }
            },
            error: function (res) {
                app.loading(false);
                console.log(res);
            }
        });
    },
    /**
     * 设置密码
     * @param formData
     */
    setPassword: function (formData) {
        app.loading(true);
        $.ajax('sso/user/applyApp', {
            data: formData,
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                app.loading(false);
                if (data.success) {
                    // TODO 设置跳转路径
                    window.location.href = 'sso/login?appId=mall&returnURL='+data.content.returnUrl;
                } else if (data.errMsg) {
                    app.error(data.errMsg);
                }
            },
            error: function (res) {
                app.loading(false);
            }
        });
    },
    registedModal: function (t) {
        $('#registedModal').modal({}).find('.x-registed-mobile').text(t);
    }
};
$(document).ready(function () {
    app.init();
    $("#password").change(function () {
        if (this.value.length == 0) {
            $(".level1").hide();
            $(".level2").hide();
            $(".level3").hide();
            return;
        }
        if (this.value.length < 8 || /^[0-9]*$/.test(this.value) || /^[A-Za-z]*$/.test(this.value)) {
            $(".level1").show();
            $(".level2").hide();
            $(".level3").hide();
            return;
        }
        if (/^[A-Z0-9]{8,20}$/.test(this.value) || /^[a-z0-9]{8,20}$/.test(this.value)) {//达到8位，且 仅有数字+英文小写 或 仅有数字+英文大写
            $(".level1").show();
            $(".level2").show();
            $(".level3").hide();
            return;
        }
        if (/^(?=.*[0-9].*)(?=.*[A-Z].*)(?=.*[a-z].*).{8,20}$/.test(this.value)) {
            $(".level1").show();
            $(".level2").show();
            $(".level3").show();
            return;
        }
    });

    $("#agree").change(function () {
        if (this.checked) {
            $('#default-check-box').addClass('active');
        } else {
            $('#default-check-box').removeClass('active');
        }
    })
    initKeyboard('.softkeys1');
    initKeyboard('.softkeys2');
    $('#keyboard1').on('click', function (event) {
        event.stopPropagation();
        var keyboard = $('.softkeys1');
        if (keyboard.is(":hidden")) {
            keyboard.show();
        } else {
            keyboard.hide();
            // app.checkPassword();
            $('#password').focus();
            $('#password').blur();
        }
    });
    $('#keyboard2').on('click', function (event) {
        event.stopPropagation();
        var keyboard = $('.softkeys2');
        if (keyboard.is(":hidden")) {
            keyboard.show();
        } else {
            keyboard.hide();
        }
    });
    $('.x-content').on('click', function () {
        if (!$('.softkeys1').is(":hidden")) {
            // app.checkPassword();
            $('#password').focus();
            $('#password').blur();
        } else if (!$('.softkeys2').is(":hidden")) {
            $('#passwordConfirm').focus();
            $('#passwordConfirm').blur();
        }
        $('.softkeys').hide();
    })
    $('.softkeys').on('click', function (event) {
        event.stopPropagation();
    })
});
function initKeyboard(str) {
    $(str).softkeys({
        target: $(str).data('target'),
        layout: [
            [
                ['`', '~'],
                ['1', '!'],
                ['2', '@'],
                ['3', '#'],
                ['4', '$'],
                ['5', '%'],
                ['6', '^'],
                ['7', '&'],
                ['8', '*'],
                ['9', '('],
                ['0', ')'],
                ['-', '_'],
                ['=', '+'],
                'delete'
            ],
            [
                'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p',
                ['[', '{'],
                [']', '}']
            ],
            [
                'capslock',
                'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l',
                [';', ':'],
                ["'", '"'],
                ['\\', '|']
            ],
            [
                'shift',
                'z', 'x', 'c', 'v', 'b', 'n', 'm',
                [',', '<'],
                ['.', '>'],
                ['/', '?'],
                ['@']
            ]
        ]
    });
}
var goHref = function (url) {
    window.location.href = url;
}

var checkRealLen = function (str) {
    var len = 0;
    for (var i = 0; i < str.length; i++) {
        if (str.charCodeAt(i) > 127 || str.charCodeAt(i) == 94) {
            len += 2;
        } else {
            len++;
        }
    }
    return len;
}