/**
 * 新增银行卡
 * @author: wsl<shuiling.wang@yoho.cn>
 * @date: 2016/08/25
 */

let $ = require('yoho-jquery');
let tip = require('js/plugin/tip');
let checkCard = require('./bind-card-check');
let loading = require('js/plugin/loading');
let applyButton = $('.open-btn');
let flag = true;
let formData = {
    cardNo: '',
    mobile: '',
    bankName: '',
    bankCode: ''
};

let validateForm = function() {
    let ret = false;

    if (formData.cardNo &&
        formData.mobile.length === 11 &&
        formData.bankName &&
        formData.bankCode) {
        applyButton.removeClass('disabled');
        ret = true;
    } else {
        applyButton.addClass('disabled');
        ret = false;
    }

    return ret;
};

require('js/common');
require('./overdue-notice');

checkCard(formData);

// 定时更新模型,解决各种浏览器奇葩问题终极办法
setInterval(function() {
    $('input').each(function() {
        let name = $(this).attr('name');

        formData[name] = $(this).val();
    });
    validateForm();
}, 500);

applyButton.on('click', function() {
    if (!flag || $(this).hasClass('disabled') || !validateForm()) {
        return false;
    }

    if (!/^1[0-9]{10}$/.test(formData.mobile)) {
        tip.show('手机号输入不正确!');
        return false;
    }

    loading.showLoadingMask();

    flag = false;

    $.ajax({
        type: 'GET',
        url: '/home/installment/post-account',
        data: formData,
        success: function(data) {
            let params = {
                action: 'go.bindCardResult',
                params: {
                    status: 0
                }
            };

            let url = location.href + '&openby:yohobuy=';

            if (window.queryString.title) {
                params.params.name = $('.username').html();
            }

            if (data.code === 200) {
                params.params.status = 1;
            } else if (data.code === 500) {
                tip.show('连接超时');
                flag = true;
                params.params.message = '网络连接超时!';
            } else {
                params.params.message = data.message;
            }

            url += encodeURIComponent(JSON.stringify(params));

            loading.hideLoadingMask();

            $('body').append('<a href=' + url + ' style="display: none;"><span class="jump">&npsb;</span></a>');

            $('.jump').click();
        },
        error: function() {
            loading.hideLoadingMask();
            tip.show('网络断开连接了~');
            flag = true;
        }
    });
});


// 使用H5标签后 maxlength 标签失效
$('input[maxlength]').keyup(function() {
    let value = $(this).val(),
        length = $(this).attr('maxlength') || 20;

    $(this).val(value.slice(0, length));
});