/**
 * 个人中心页-账号安全验证
 * @author:wsl<shuiling.wang@yoho.cn>
 * @date: 2016/02/23
 */
var $ = require('yoho-jquery'),
    Captcha = require('../plugins/captcha');

var dialog = require('../common/dialog');

var phoneRegx = require('../passport/mail-phone-regx');

var Alert = dialog.Alert;

var $checkUser = $('.check-user'),
    $checkInput = $checkUser.find('input').not('input[type=button],input[type=hidden],input[type=reset]'),
    canSend = true,
    canFlag = true,
    stime = 60;

var sInt,
    active;

var baseQs;

var captcha = new Captcha('.captcha-safe-form-r', {checkURI: ''}).init();

require('../common');

baseQs = window.queryString();

if (baseQs.checkCode) {
    baseQs.checkCode = encodeURIComponent(baseQs.checkCode);
}

$.ajaxSetup({
    async: false
});

if (!Array.prototype.indexOf) {// eslint-disable-line
    Array.prototype.indexOf = function(obj, start) {// eslint-disable-line
        var i,
            j;

        for (i = (start || 0), j = this.length; i < j; i++) {
            if (this[i] === obj) {
                return i;
            }
        }

        return -1;
    };
}

function showCaptchaImg() {
    captcha.show();
}

function errorInfoAction(opt, txt) {
    canFlag = false;
    opt.$checkInfo.html('<div class="form-error">' + txt + '</div>');
    if (opt.dom.attr('name') !== 'code' && opt.dom.attr('name') !== 'verifyCode') {
        opt.dom.addClass('input-error');
    }
    return false;
}

function successInfoAction(opt) {
    canFlag = true;
    opt.$checkInfo.html('<div class="form-success">&nbsp;</div>');
    if (opt.dom.attr('name') !== 'code' && opt.dom.attr('name') !== 'verifyCode') {
        opt.dom.removeClass('input-error');
    }
    return true;
}

function checkFormAjax(ajaxData) {
    var res;

    $.post(ajaxData.url, ajaxData.data, function(data) {
        if (typeof data.code !== 'undefined' && data.code === 200) {
            if (ajaxData.cb && typeof ajaxData.cb === 'function') {
                ajaxData.cb(data); // eslint-disable-line
            }
            res = successInfoAction(ajaxData.opt);
        } else {
            ajaxData.txt = ajaxData.txt !== '' && ajaxData.txt !== null ? ajaxData.txt : data.message;
            res = errorInfoAction(ajaxData.opt, ajaxData.txt);
        }
    });
    return res;
}

// 身份校验
function checkForm(dom) {
    var val = dom.val(),
        len = val.length,
        $domParent = dom.parent(),
        $checkInfo = $domParent.find('.check-info'),
        inputName = dom.attr('name'),
        regular = '',
        text = '',
        mobileValue = '',
        opt = {
            $checkInfo: $checkInfo,
            dom: dom
        },
        ajaxData = {
            opt: opt
        };

    $checkInfo.html('');

    if (inputName === 'password') {
        if (len === 0) {
            return errorInfoAction(opt, '密码不能为空!');
        } else {
            $.extend(ajaxData, {
                url: '/home/account/checkpassword',
                data: {
                    password: val
                },
                txt: '密码错误!'
            });
            return checkFormAjax(ajaxData);
        }
    } else if (inputName === 'email') {
        regular = phoneRegx.emailRegx;

        if (val.match(regular) === null) {
            return errorInfoAction(opt, '邮箱错误!');
        } else {
            $.extend(ajaxData, {
                url: '/home/account/checkemail',
                data: {
                    email: val
                },
                txt: ''
            });
            return checkFormAjax(ajaxData);
        }
    } else if (inputName === 'mobile') {
        regular = phoneRegx.phoneRegx;
        text = val.split('-');

        if (text.length === 1) {
            regular = val.match('^1[35847]{1}[0-9]{9}');
        } else {
            regular = regular['+' + text[0]].test(text[1]);
        }

        if (len === 0) {
            return errorInfoAction(opt, '手机号不能为空!');
        } else if (regular === null || !regular) {
            return errorInfoAction(opt, '手机号错误!');
        } else {
            $.extend(ajaxData, {
                url: '/home/account/checkmobile',
                data: {
                    mobile: val
                },
                txt: '手机号已经存在!'
            });
            return checkFormAjax(ajaxData);
        }
    } else if (inputName === 'newPwd') {
        regular = phoneRegx.pwdValidateRegx;

        if (!regular.test(val)) {
            return errorInfoAction(opt, '建议6~20个数字+字母组合!');
        } else {
            return successInfoAction(opt);
        }
    } else if (inputName === 'confirm_password') {
        if ($('#newPwd').val() !== val) {
            return errorInfoAction(opt, '两次密码不一致!');
        } else {
            return successInfoAction(opt);
        }

        // else if ($('#newPwd').val() !== '') {
        //     $('#newPwd').next().html('<div class="form-success">&nbsp;</div>');
        //     return successInfoAction(opt);
        // }
    } else if (inputName === 'code') {
        mobileValue = $('#realAccount').length > 0 ? $('#realAccount').val() : $('#mobilevalue').val();

        if (val !== '') {
            $.extend(ajaxData, {
                url: '/home/account/checkmobilemsg',
                data: {
                    mobile: mobileValue,
                    code: $('#inputcode').val(),
                    checkCode: baseQs.checkCode || ''
                },
                txt: '验证码错误!',
                cb: function(data) {
                    if (data.code === 200) {
                        baseQs.checkCode = data.data;
                    }
                }
            });
            return checkFormAjax(ajaxData);
        }
    } else {
        return true;
    }
}

// 校验表单
function checkAllForm() {
    var arr = [];

    $.each($checkInput, function(key, item) {
        arr[key] = checkForm($(item));
    });

    if (arr.indexOf(false) >= 0) {
        return false;
    } else {
        return true;
    }
}

// 切换验证码
function changeCode() {
    var timestamp = (new Date()).getTime();

    $('#the-code-img').attr('src', '/passport/imagesNode?len=6&time=' + timestamp);
}

// 重新发送倒计时
function code() {
    var sstring = '';

    if (stime > 0) {
        sstring = '重新发送' + stime + '秒';
        $('#sendButton').text(sstring);
        stime = stime - 1;
    } else {
        stime = 60;
        $('#sendButton').text('发送验证码');
        clearInterval(sInt);
        canSend = true;
    }
}

// 发送手机验证码ajax请求
function sendMobileMsg(mobileV) {
    var $code = $('#inputcode'),
        $ccheckInfo = $code.parent().find('check-info');
    var reqData = {
        mobile: mobileV
    };

    if (baseQs.checkCode) {
        reqData.checkCode = baseQs.checkCode;
    }

    reqData.verifyCode = captcha.getResults();

    $.post('/home/account/sendmobilemsg', reqData, function(result) {
        if (typeof result.code !== 'undefined' && result.code === 200) {
            canSend = false;
            sInt = setInterval(function() {
                code();
            }, 1000);
            $ccheckInfo.html('');
            captcha.hideTip();
        } else {
            if (result.data && result.data.needCaptcha) {
                showCaptchaImg();
            }
            if (result.code === captcha.errorCode) {
                captcha.showTip(result.message);
            } else {
                $ccheckInfo.html('<div class="form-error">' + result.message + '</div>');
            }
        }
    });
}

// 发送手机验证码
function sendcode() {
    var $mobile = $('#mobilevalue');

    var $mcheckInfo,
        mobileV,
        mobileObj;

    if ($mobile.length > 0) {
        $mcheckInfo = $mobile.next();
        mobileV = $mobile.val();
        mobileObj = mobileV.split('-');

        if (mobileObj.length === 1) {
            mobileObj = mobileV.match('^1[35847]{1}[0-9]{9}');
        } else {
            mobileObj = phoneRegx.phoneRegx['+' + mobileObj[0]].test(mobileObj[1]);
        }
    } else {
        mobileV = $('#realAccount').val();
    }

    if (canSend) {
        if ($mobile.length > 0) {
            if (mobileObj === null || !mobileObj) {
                $mcheckInfo.html('<div class="form-error">手机号错误!</div>');
                $mobile.addClass('input-error');
                return false;
            }

            if ($mcheckInfo.find('.form-success').length > 0) {
                sendMobileMsg(mobileV);
            }
        }

        if ($('#realAccount').length > 0) {
            sendMobileMsg(mobileV);
        }
    } else {
        return false;
    }
}

// 验证完成后倒计时跳转
function toHome() {
    window.location.href = '/home/account';
}

// ajax公共处理模块
function ajaxAction(opt, flag) {
    $.post(opt.url, opt.data, function(data) {
        if (data.code === 200) {
            if (flag) {
                opt.hrefUrl += '&checkCode=' + data.data;
            }
            window.location.href = opt.hrefUrl;
        } else {
            canFlag = true;
            active = new Alert(data.message);
            active.show();
            return false;
        }
    }, 'json');
}

// 提交表单
function submitForm() {
    var step = $('.progress-bar .cur').index(),
        verifyType = $('#verifyType').val(),
        curType = '',
        opt = {};

    if ($('.email').length > 0) {
        curType = 'email';
    }

    if ($('.mobile').length > 0) {
        curType = 'mobile';
    }

    if ($('.userpwd').length > 0) {
        curType = 'userpwd';
    }

    /*
     * step 0: 验证身份 1:验证第二步骤 2:验证第三步骤
     * verifyType 验证身份的状态 1:登录密码验证 2:邮箱的身份验证 3:手机的身份验证
     */
    if (step === 0) {
        if (verifyType === '1') {
            opt = {
                url: '/home/account/verifypassword',
                data: $('#pwdform').serialize(),
                hrefUrl: '/home/account/' + curType + '?step=2'
            };

            ajaxAction(opt, 'step1');

            // if (!ajaxAction(opt)) {
            //     $("input[type=reset]").trigger("click");
            // }
        } else if (verifyType === '2') {
            opt = {
                url: '/home/account/sendemail',
                data: {
                    checkType: curType,
                    email: $('#realAccount').val()
                },
                hrefUrl: '/home/account/sendemailsuccess?email=' + $('#realAccount').val() +
                        '&type=1&checkType=' + curType
            };
            ajaxAction(opt);
        } else {
            opt = {
                url: '/home/account/checkmobilemsg',
                data: {
                    mobile: $('#realAccount').val(),
                    code: $('#inputcode').val(),
                    checkCode: baseQs.checkCode || ''
                },
                hrefUrl: '/home/account/' + curType + '?step=2'
            };
            ajaxAction(opt, 'step1');
        }
    } else if (step === 1) {
        if (curType === 'userpwd') {
            opt = {
                url: '/home/account/modifypwd',
                data: $('#pwdform').serialize(),
                hrefUrl: '/home/account/userpwd?step=3&success=true'
            };

            opt.data += '&checkCode=' + baseQs.checkCode;

            ajaxAction(opt);
        } else if (curType === 'email') {
            opt = {
                url: '/home/account/modifyemail',
                data: {
                    email: $('#email').val(),
                    checkCode: baseQs.checkCode || ''
                },
                hrefUrl: '/home/account/sendemailsuccess?email=' + $('#email').val() +
                        '&type=2&checkType=email'
            };
            ajaxAction(opt);
        } else {
            opt = {
                url: '/home/account/modifymobile',
                data: {
                    mobile: $('#mobilevalue').val(),
                    code: $('#inputcode').val(),
                    checkCode: baseQs.checkCode || ''
                },
                hrefUrl: '/home/account/mobile?step=3&success=true'
            };
            ajaxAction(opt);
        }
    }
}

$(function() {

    if ($('.res-info').length > 0) {
        setTimeout(function() {
            toHome();
        }, 5000);
    }

    // changeCode();

    $('#pwdform').submit(function() {
        return false;
    });

    $checkInput.blur(function() {
        checkForm($(this));
    });

    $('.sub-btn').on('click', function() {
        if (canFlag === false) {
            return false;
        }

        if (checkAllForm()) {
            submitForm();
        } else {
            return false;
        }
    });

    $('input[name=verifyCode]').keydown(function(e) {
        if (e.keyCode === 13) {
            if (canFlag === false) {
                return false;
            }

            if (checkAllForm()) {
                submitForm();
            } else {
                return false;
            }
        }
    });

    $('.the-code').on('click', function() {
        changeCode();
    });

    $('#send-mobile-code').on('click', function() {
        sendcode();
    });

    if ($('#newPwd').length > 0) {
        $('#newPwd').on('input', function() {
            var $confirm = $('input[name=confirm_password]'),
                confirmV = $confirm.val(),
                newPwdV = $('#newPwd').val(),
                opt = {
                    dom: $confirm,
                    $checkInfo: $confirm.next()
                };

            if (confirmV.length > 0 && newPwdV !== confirmV) {
                errorInfoAction(opt, '两次密码不一致!');
            }
        });
    }
});