/**
 * Created by skywing on 2017/9/8.
 */
$(document).ready(function () {

    var phoneReg = /^1\d{10}$/;
    var numCodeReg = /^[0-9]{4,6}$/;
    var psdReg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$/;
    var emailReg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;

    var phone = "";
    var rc = "";
    var loginType = "", hasImgCode = false;
    var hostName="//www.haitou.cc";
    function getUrl () {
        return window.location.href;
    }
    //短信倒计时
    var timerCount = "";
    function timeCount (allTime, getBtn) {
        getBtn.attr("disabled", true).val(allTime-1 + "s后重获").addClass("border-sending");
        timerCount = setInterval(function()
        {
            allTime--;
            getBtn.attr("disabled", true).val(allTime-1 + "s后重获").addClass("border-sending");//设置
            if(allTime <= 1){
                clearInterval(timerCount);
                getBtn.attr("disabled", false).val("重新获取").removeClass("border-sending");
            }
        },1000);
    }

    var loginAction = {
        phoneCheck: function (phone, fn) {
            if (phone == "" || phone.trim().length == 0) {
                var text = "请先输入手机号码";
                loginAction.showErrorMsg($(".inputs-phone-code"), text);
                return false;
            } else if (!phoneReg.test(phone)) {
                var text = "输入正确的手机号码";
                loginAction.showErrorMsg($(".inputs-phone-code"), text);
                return false;
            } else {
                // loginAction.numCodeCheck(rc,phone);
                fn()
            }
        },
        // numCodeCheck
        numCodeCheck: function () {
            rc = $("#code-login-code").val();
            phone = $("#code-login-phone").val();
            if (rc == "" || rc.trim().length == 0) {
                var text = "请先获取验证码";
                loginAction.showErrorMsg($(".inputs-numcode-code"), text);
                return false;
            } else if (!numCodeReg.test(rc)) {
                var text = "请输入正确的验证码";
                loginAction.showErrorMsg($(".inputs-numcode-code"), text);
                return false;
            } else {
                // 登录
                $.ajax({
                    url: "/system/quick-login?phone=" + phone + "&rc=" + rc ,
                    data: "",
                    type: "GET",
                    success: function (data) {
                        if (data.status == "success") {
                            console.log(data);
                            // location.href = getUrl();
                            // window.location.reload();
                            // 不是公司用户且信息不完整的需要完善个人信息
                            // if (!data.infoFlag && !data.company) {
                            //     $("#userModal").modal('hide');
                            //     $("#infoModal").modal();
                            // } else {
                            //     window.location.reload();
                            // }

                            if(data.role == 2){
                                // 企业用户不再自动点击投递按钮
                                location.href = location.href.replace('#/submitResume', '');
                                return ;
                            }
                            // if(!data.infoFlag){
                            //     // 信息不完整
                            //     $("#userModal").modal('hide');
                            //     $("#infoModal").modal();
                            //     return ;
                            // }
                            window.location.reload();

                        } else if (data.status == "error") {
                            if (data.errcode) {
                                ajaxErrorMsgShow("", data)
                            }
                        }
                    }
                })
            }
        },
        loginGetCode: function (phone, imgCodeSend) {
            $.ajax({
                url: "/system/pre-quick-login?phone=" + phone  + imgCodeSend,
                type: "GET",
                success: function (data) {
                    if (data.status == "error") {
                        clearInterval(timerCount);
                        $(".btn-code").attr("disabled", false).val("重新获取").removeClass("border-sending");
                        if (data.errcode && !data.need_captcha) {
                            ajaxErrorMsgShow("", data)
                        }
                        // 默认增加图形验证码
                        if (data.need_captcha && data.need_captcha == 1) {
                            hasImgCode = true;
                            $(".code-login-imgcode").show();
                            $(".code-login-imgcode").find("img").attr("src", "/system/captcha");
                            loginAction.showErrorMsg($(".code-login-imgcode"), data.message);
                        }
                    }
                    else if (data.status == "success") {
                        // console.log(data);
                    }
                },
                error: function () {
                    clearInterval(timerCount);
                    $(".btn-code").attr("disabled", false).val("重新获取").removeClass("border-sending");
                }
            })
        },
        // 发送验证码
        phoneCodeAjax: function () {
            var self = this;
            var imgCode = $("#code-login-input").val();
            // var imgCodeSend = hasImgCode ? "&captcha=" + imgCode : "";
            var imgCodeSend = "&captcha=" + imgCode;
            // if(hasImgCode) {
                if(imgCode == "" || imgCode.trim().length == 0) {
                    loginAction.showErrorMsg($(".code-login-imgcode"), "请输入验证码");
                    return;
                }
            // }
            timeCount(60, $(".btn-code"));
            loginAction.loginGetCode(phone, imgCodeSend);
        },
        // account-loginajax
        accountLoginAjax: function (loginType, account, password) {
            $.ajax({
                url: "/system/login?" + loginType + "=" + account,
                data: {"password": $.md5(password)},
                type: "POST",
                success: function (data) {
                    if (data.status == "success") {
                        console.log('accountLoginAjax', data)
                        if(data.role == 2){
                            // 企业用户不再自动点击投递按钮
                            location.href = location.href.replace('#/submitResume', '');
                            return ;
                        }
                        // if(!data.infoFlag){
                        //     // 信息不完整
                        //     $("#userModal").modal('hide');
                        //     $("#infoModal").modal();
                        //     return ;
                        // }
                        window.location.reload();

                    } else if (data.status == "error") {
                        if (data.errcode) {
                            ajaxErrorMsgShow("", data);
                        }
                    }
                }
            })
        },
        // show error messages
        showErrorMsg: function (ele, text) {
            ele.find("label").text(text);
            ele.find("label").removeClass("remove-error").addClass("error");
            if (ele.attr("class") == "input-psd") {
                $(".input-psd span").css("opacity", "0");
            }
            // 当前输入框获取焦点，隐藏错误信息
            ele.find("input").on("focus input", function (event) {
                $(this).siblings("label").removeClass("error").addClass("remove-error");
                if (event.target.id == "set-password") {
                    $(".input-psd span").css("opacity", "1");
                }
            })
        },
        // 回车事件绑定
        enterPress: function (parentEle, triggerEle) {
            $(document).on("keydown", function (event) {
                if (parentEle.css("display") == "block") {
                    event = event || window.event;
                    if (event.keyCode == 13) {
                        triggerEle.trigger("click");
                    }
                }
            })
        }
    }

    // label 标签点击输入框获取焦点
    $(document).on("click","label", function () {
        $(this).siblings("input").focus();
    })
    // $("label").on("click", function () {
    //     $(this).siblings("input").focus();
    // })

    // 点击获取验证码
    $(document).on("click", ".btn-code", function () {
        var getCodeBtn = $(".btn-code");
        var loginValEle = $("#code-login-phone");
        phone = loginValEle.val();
        // 正则验证手机号码并发送验证码
        loginAction.phoneCheck(phone, loginAction.phoneCodeAjax);
    })

    // 点击快速登录
    $(document).on("click",".inputs-login-now input", function () {
        var loginValEle = $("#code-login-phone");
        phone = loginValEle.val();
        rc = $("#code-login-code").val();
        loginAction.phoneCheck(phone, loginAction.numCodeCheck);
    })

    // 点击账号登录
    $(document).on("click", ".inputs-login input", function () {
        var account = $("#account-login-phone").val();
        var password = $("#account-login-psd").val();
        if (account == "" || account.trim().length == 0) {
            var text = "账号不能为空";
            loginAction.showErrorMsg($(".inputs-phone-account"), text);
        } else if (!phoneReg.test(account) && !emailReg.test(account)) {
            var text = "账号格式错误";
            loginAction.showErrorMsg($(".inputs-phone-account"), text);
        } else if (password == "" || password.trim().length == 0) {
            var text = "请输入密码";
            loginAction.showErrorMsg($(".inputs-password-account"), text);
        } else {
            if (phoneReg.test(account)) {
                loginType = "phone";
            } else if (emailReg.test(account)) {
                loginType = "email";
            }
            loginAction.accountLoginAjax(loginType, account, password);
        }
    })

    // 请求错误验证提示
    function ajaxErrorMsgShow(showEleParent, data) {
        //用户不存在
        if (data.errcode == "001") {
            showEleParent = $(".inputs-phone-account")
            loginAction.showErrorMsg(showEleParent, data.message);
        } else if (data.errcode == "003") {
        // 密码错误
            var showEleParent = $(".inputs-password-account");
            loginAction.showErrorMsg(showEleParent, data.message);
        } else if (data.errcode == "004") {
        // 请输入正确的短信验证码
            showEleParent = $(".inputs-numcode-code")
            loginAction.showErrorMsg(showEleParent, data.message);
        } else if (data.errcode == "006") {
        //  短信系统忙
            showEleParent = $(".inputs-numcode-code")
            loginAction.showErrorMsg(showEleParent, data.message);
        } else if (data.errcode == "007") {
        // 已注册
            showEleParent = $(".inputs-phone-code")
            loginAction.showErrorMsg(showEleParent, data.message);
        } else if (data.errcode == "009") {
        // 验证码已发送，请勿重复发送
            showEleParent = $(".inputs-numcode-code")
            loginAction.showErrorMsg(showEleParent, data.message);
        }
    }



    // wechat page switch to send ajax
    var setIntervalFun = '';
    function ifQrAjax() {
        $.ajax({
            url: "/system/wechat-qrcode?redirect_url="+getUrl(),
            type: "GET",
            data: "",
            success: function (data) {
                // console.log(data);
                if (data.status == "success") {
                    $(".wechat-qrcode img").attr("src", data['qrimg']);
                    $('#wechat_reg').attr('data-scene', data['scene_id']);
                    setweixin();
                    setTimeout(function () {
                        clearInterval(setIntervalFun);
                        $(".failed-mask").show();
                        $('.failed-msg').css('color', 'red').text('二维码失效，点击刷新！');
                    }, 300000);
                } else {
                    return false;
                }
            }
        });
    }

    //    点击刷新二维码
    $(document).on("click", ".btn-refresh", function () {
        ifQrAjax();
        $(".failed-mask").hide();
    });

    //微信轮询
    function setweixin() {
        //由setInterval执行遍历
        setIntervalFun = setInterval(function () {
            //ajax向后台查询，如果查询到数据这条登录数据，返回成功后则销除数据库储存的那条数据。
            var scene_id = $('#wechat_reg').attr('data-scene'); //在页面生成的scene_id
            $.ajax({
                type: "get",
                url: "/system/wechat-find-scene?scene_id=" + scene_id,
                data: '',
                dataType: "json",
                success: function (data) {
                    // console.log(data);
                }
            });
        }, 2000);
    };


    // 点击关闭span关闭弹框。
    $(document).on("click", "span.btn-close", function () {
        $(".ht-modal").css({"transform": "translateY(-80px)", "opacity": 0});
    })

    // 弹框关闭数据初始化
    initModal ($("#userModal"));
    // initModal ($("#infoModal"));
    function initModal (parentModal) {
        var modalHtml = "";
        var wechatFlag = false;
        parentModal.on("show.bs.modal", function () {
            modalHtml = $(this).html();
            //初始化二维码请求
            $(".wechat-btn").on("click", function () {
                if(!wechatFlag) ifQrAjax();
                wechatFlag = true;
            })
            loginTypeChange();
        //   登录回车事件触发
            loginAction.enterPress($(".ht-modal.code-login"), $(".login-now-btn"));
            loginAction.enterPress($(".ht-modal.account-login"), $(".inputs-login input"));
        }).on("hide.bs.modal", function () {
            setTimeout(function () {
                $(this).html(modalHtml);
            }.bind($(this)),200);
            //清除微信轮循的定时器；
            clearInterval(setIntervalFun);
            //清除sense_id
            $('#wechat_reg').attr('data-scene', "");
            //删除hash
            changehash();
            wechatFlag = false;
        });
    }

    //关闭添加简历modal页面刷新
    $("#resumeModal").on("hide.bs.modal", function () {
        window.location.reload();
    })

    // 登录方式切换函数
    function loginTypeChange() {
        var clickEle = $(".ht-modal-footer").children("div").find("a");
        var quickLoginPage = $(".ht-modal.code-login");
        var accountLoginPage = $(".ht-modal.account-login");
        var wechatLoginPage = $(".ht-modal.qrcode-login");
        //点击切换
        clickEle.on("click", function (event) {
            if ($(this).parent().attr("class") == "to-login-wechat") {
                wechatLoginPage.show();
                quickLoginPage.hide();
                accountLoginPage.hide();
            } else if ($(this).parent().attr("class") == "to-login-account") {
                accountLoginPage.show();
                quickLoginPage.hide();
                wechatLoginPage.hide();
            } else if ($(this).parent().attr("class") == "to-login-numcode") {
                quickLoginPage.show();
                accountLoginPage.hide();
                wechatLoginPage.hide();
            }
        })
    }

//    clode mdoal and slide hash
    function changehash () {
        if(window.location.hash) {
           window.location.hash = "";
        }
    }
})
    // 点击显示模态框
    function modalShow() {
        $(".ht-modal").css({"transform": "translateY(80px)", "visibility": "visible", "opacity": 1})
    }
