'use strict';

let tip, checkPoint, validatePWD;
let $eyeBtn,
    $pwd,
    $nextBtn,
    $pwdLint,
    $pwdLintTxt;

let page;


require('common');
tip = require('plugin/tip');
checkPoint = require('./smslogin/check-point');
validatePWD = require('./password-check');

setTimeout(function() {
    checkPoint('YB_SET_PASSWORD_L');
}, 3000);

page = {
    registerCode: window.queryString.registerCode,
    init: function() {
        this.domInit();
        this.bindEvent();
    },
    domInit: function() {
        $eyeBtn = $('#eye');
        $pwd = $('#pwd');
        $nextBtn = $('#btn-next');
        $pwdLint = $('.js-password').find('.pwd-lint');
        $pwdLintTxt = $pwdLint.find('.pwd-lint-txt');
    },
    bindEvent: function() {
        let self = this;

        $eyeBtn.on('click', function() {
            self.togglePassword();
        });

        $nextBtn.on('click', function() {
            if (!self.registerCode) {
                return tip.show('非法请求');
            }
            self.setPasswordAndLogin();
        });

        $pwd.on('input', function() {
            let val = $.trim(this.value);
            let bool = validatePWD(val, function(res) {
                $pwdLint.css({visibility: res.valid ? 'hidden' : 'visible'});

                if (!res.valid) {
                    $pwdLintTxt.text(res.msg);
                }
            });

            $nextBtn
                .toggleClass('disable', !bool)
                .prop('disabled', !bool);
        });
    },

    togglePassword: function() {
        let bool = $eyeBtn.hasClass('close');

        $eyeBtn.toggleClass(function() {
            $pwd.attr('type', !bool ? 'password' : 'text');
            return 'close';
        }, !bool);
    },

    setPasswordAndLogin: function() {
        let password = $.trim($pwd.val());
        let self = this;

        if ($nextBtn.prop('disabled')) {
            return;
        }

        $nextBtn.prop('disabled', true);
        $.post('/passport/sms_login/password.json', {
            password: password,
            registerCode: self.registerCode
        })
            .done(function(res) {
                if (res.code === 200) {
                    checkPoint('YB_SET_PASSWORD_ENSURE_C'); // 埋点
                    // $nextBtn.off();
                    location.href = res.redirect;
                    return;
                }

                tip.show(res.message);
            })
            .fail(function() {
                tip.show('出错了, 请重试');
            })
            .always(function() {
                $nextBtn.prop('disabled', false);
            });
    }
};
$(function() {
    page.init();
});