//返回顶部按钮
function reback() {
    $('body,html').animate({scrollTop: 0}, 500);
}
var mobileInt;
var loginLayer; // 登录弹窗


//获取url地址
function getQueryVariable(variable){
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i=0;i<vars.length;i++) {
        var pair = vars[i].split("=");
        if(pair[0] == variable){return pair[1];}
    }
    return(false);
}


function timerMobileValCode(intDiff, sendBefoBtnId, sendafterBtnId, waitsecondId) {
    mobileInt = window.setInterval(function () {
        var second = 60;
        if (intDiff > 0) {
            second = intDiff;
        } else if (intDiff == 0) {
            $("#" + sendafterBtnId).hide();
            $("#" + sendBefoBtnId).show();
            window.clearInterval(mobileInt);
        }
        if (second <= 9)
            second = '0' + second;
        $('#' + waitsecondId).html(second);
        intDiff--;
    }, 1000);
}

function isMobile(mobile) {
    var reg = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
    return reg.test(mobile);
}

function isPass(pass) {
    var reg = /^(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[^a-zA-Z0-9]).{4,16}$/;
    var isJudge = reg.test(pass);
    return isJudge;
}

function isName(userName) {
    var reg = /^[\u4E00-\u9FA5A-Za-z0-9]{2,11}$/;
    var isJudge = reg.test(userName);
    return isJudge;
}


function sendYzm(memUserId, id) {
    $.ajax({
        type: 'Get',
        url: "/login/sendMobileYzm",
        data: {
            phone: memUserId
        },
        success: function (res) {
            if (res.code == 200) {
                var beforeId = "verification", dafterId = "djstime", waritId = "waittime";
                if (id == "regVerification") {
                    beforeId = "regVerification", dafterId = "regDjstime", waritId = "regWaittime";
                }
                if (id == "bindVerification") {
                    beforeId = "bindVerification", dafterId = "bindDjstime", waritId = "bindWaittime";
                }
                if (id == "editVerification") {
                    beforeId = "editVerification", dafterId = "editDjstime", waritId = "editWaittime";
                }
                $("#" + beforeId).hide();
                $("#" + dafterId).show();
                timerMobileValCode(59, beforeId, dafterId, waritId);
            }
        },
        error: function (data) {
            alert("验证码发送失败");
        }
    });
}

//微信扫码后绑定手机号
$(".bindBtn").click(function (){
    bindPhone(this);
})
$('#bindVerification').click(function (){
    var id = $(this).attr("id");
    var mobile = $("#bindMobile").val();
    if (mobile == "") {
        layer.msg('请填写手机号', {
            offset: 't',
            anim: 6
        });
        return;
    }
    if (!isMobile(mobile)) {
        layer.msg('请填写正确的手机号码', {
            offset: 't',
            anim: 6
        });
        return;
    }
    sendYzm(mobile, id);
})

$('.bindClose').click(function (){
    $(".navbindBox").hide();
    var nowUrl = window.location.href;
    if(nowUrl.indexOf('/index/index') == -1){
        window.location.href = serverHttp +'/index/index?from=web';
    }
})

function bindPhone(_this) {
    //要求用户勾选用户协议
    var getCheckStatus = $(".agreementBtnBind").is(":checked");
    if (getCheckStatus == true) {
        $(_this).removeAttr("disabled")
    } else {
        layer.msg('请勾选用户协议', {
            offset: 't',
            anim: 6
        });
        return false;
    }

    let valCode1 = $(".bindCode").val();
    let memMobile1 = $(".bindMobile").val();
    if (memMobile1 == '') {
        layer.msg('请输入手机号', {
            offset: 't',
            anim: 6
        });
        return;
    }
    if (!isMobile(memMobile1)) {
        layer.msg('请填写正确的手机号码', {
            offset: 't',
            anim: 6
        });
        return;
    }
    if (valCode1 == '') {
        layer.msg('请输入验证码', {
            offset: 't',
            anim: 6
        });
        return;
    }

    var data = {}
    data = {
        memMobile: memMobile1,
        valCode: valCode1,
        memRegisterSource: 2,
        operationName: 'signInWithPhone'
    }
    //获取扫码登录信息
    if(getQueryVariable("wxId") != false){
        data.wxId=getQueryVariable("wxId");
        data.memNickname=getQueryVariable("memNickname");
        data.memHeadimg=getQueryVariable("memHeadimg");
    }
    $.ajax({
        type: 'POST',
        url: "/login/webLogin",
        data: data,
        async: false,
        success: (res) => {
            if (res.code == 200) {
                $(".navbindBox").hide()
                // 首次登录加积分
                $.ajax({
                    type: 'POST',
                    url: "/user/isFinishFirstLoginTask",
                    data: data,
                    async: false,
                    success: (res) => {
                        if (res.code == 200) {
                            if (res.data.finish) {
                                playMusiclogin("首次登录", 200)
                            }
                        }
                    }
                })
                findUserBaseInfo() // 获取用户信息
                setTimeout(() => {
                    window.location.reload();
                }, 4000)
            } else {
                alert(res.message);
            }
        },
        error: function (data) {

        }
    });
}

function isLogin() {
    $.ajax({
        type: 'post',
        url: serverHttp + "/index/isLogin",
        async: false,
        success: function (res) {
            if (res.code == 200) {
                return true;
            } else {
                return false;
            }
        },
        error: function (data) {
            return false;
        }
    });
}


function login(_this) {
    var type = $(_this).attr("statue");
    console.log(type);
    //要求用户勾选用户协议
    if (type == "code") {
        var getCheckStatus = $(".agreementBtn").is(":checked");
    } else {
        var getCheckStatus = $(".agreementBtn2").is(":checked");
    }
    if (getCheckStatus == true) {
        $(_this).removeAttr("disabled")
    } else {
        layer.msg('请勾选用户协议', {
            offset: 't',
            anim: 6
        });
        return false;
    }

    let valCode = $(".yzm").val();
    let memMobile = $(".tel").val();
    let phoneNum = $(".phone").val();
    let passwd = $(".pass").val();

    //获取白名单
    var getWhitelist = [];
    $.ajax({
        type: 'get',
        url: "/login/getWhitelist",
        async: false,
        success: (res) => {
            if (res.code == 200) {
                getWhitelist = res.data;
            }
        }
    });

    if (type == "code") {
        if (memMobile == '') {
            layer.msg('请输入手机号', {
                offset: 't',
                anim: 6
            });
            return;
        }
        if (!isMobile(memMobile)) {
            layer.msg('请填写正确的手机号码', {
                offset: 't',
                anim: 6
            });
            return;
        }
        if (valCode == '') {
            layer.msg('请输入验证码', {
                offset: 't',
                anim: 6
            });
            return;
        }
    } else if (type == "pass") {
        if (phoneNum == '') {
            layer.msg('请输入用户名', {
                offset: 't',
                anim: 6
            });
            return;
        }
        if (passwd == '') {
            layer.msg('请输入密码', {
                offset: 't',
                anim: 6
            });
            return;
        }
        if(getWhitelist.indexOf(phoneNum) == -1){
            if (!isName(phoneNum)) {
                layer.msg('请输入2-11位数字、字母、汉字的用户名', {
                    offset: 't',
                    anim: 6
                });
                return;
            }
            if (!isPass(passwd)) {
                layer.msg('密码格式有误，请输入8位包含数字、字母和符号的密码', {
                    offset: 't',
                    anim: 6
                });
                return;
            }
        }
    }
    // else {
    //     return;
    // }
    var data = {}
    if (type == "code") {
        data = {
            memMobile: memMobile,
            valCode: valCode,
            memRegisterSource: 2,
            operationName: 'signInWithPhone'
        }
    } else {
        data = {
            memMobile: phoneNum,
            passwd: md5(passwd),
            memRegisterSource: 2,
            operationName: 'signInWithPassword'
        }
    }
    $.ajax({
        type: 'POST',
        url: "/login/webLogin",
        data: data,
        async: false,
        success: (res) => {
            if (res.code == 200) {
                layer.close(loginLayer) // 关闭登录弹窗
                // 首次登录加积分
                $.ajax({
                    type: 'POST',
                    url: "/user/isFinishFirstLoginTask",
                    data: data,
                    async: false,
                    success: (res) => {
                        if (res.code == 200) {
                            if (res.data.finish) {
                                // saveUserDorecWeb(1, 2, 29, 1, 2)
                                playMusiclogin("首次登录", 200)
                            }
                        }
                    }
                })
                findUserBaseInfo() // 获取用户信息

                setTimeout(() => {
                    window.location.reload();

                }, 4000)

                //}
            } else {
                alert(res.message);
            }
        },
        error: function (data) {

        }
    });
}

function findUserBaseInfo() {
    $.ajax({
        type: 'POST',
        url: "/user/findUserBaseInfo",
        async: false,
        success: (res) => {
            if (res.code == 200) {
                localStorage.setItem('isVip', res.data.isVip)
                // console.log(res.data, 'fdsfdsfd')
            }
        },
        error: function (data) {

        }
    });
}

function register(_this) {
    //要求用户勾选用户协议
    var getCheckStatusre = $(".agreementBtn3").is(":checked");
    if (getCheckStatusre == true) {
        $(_this).removeAttr("disabled")
    } else {
        layer.msg('请勾选用户协议', {
            offset: 't',
            anim: 6
        });
        return false;
    }
    let userName = $("#reg-userName").val();
    let memMobile = $("#reg-memMobile").val();
    let passwd = $("#reg-passwd").val();
    let passwdRe = $("#reg-passwdRe").val();
    let valCode = $("#reg-valCode").val();
    var data = {
        userName: userName,
        memMobile: memMobile,
        valCode: valCode,
        passwd: md5(passwd),
        memRegisterSource: 2,
    }
    if (userName == "") {
        layer.msg('请输入用户名', {
            offset: 't',
            anim: 6
        });
        return;
    } else {
        if (!isName(userName)) {
            layer.msg('请输入2-11位数字、字母、汉字的用户名', {
                offset: 't',
                anim: 6
            });
            return;
        }
    }
    if (memMobile == "") {
        layer.msg('请输入手机号', {
            offset: 't',
            anim: 6
        });
        return;
    } else {
        if (!isMobile(memMobile)) {
            layer.msg('手机号格式输入有误，请重新输入', {
                offset: 't',
                anim: 6
            });
            return;
        }
    }
    if (passwd == "") {
        layer.msg('请输入密码', {
            offset: 't',
            anim: 6
        });
        return;
    } else {
        if (!isPass(passwd)) {
            layer.msg('密码格式有误，请输入4-16位包含数字、字母和符号的密码', {
                offset: 't',
                anim: 6
            });
            return;
        }
    }
    if (passwdRe == "") {
        layer.msg('请输入确认密码', {
            offset: 't',
            anim: 6
        });
        return;
    } else {
        if (passwdRe !== passwd) {
            layer.msg('密码与确认密码输入不一致', {
                offset: 't',
                anim: 6
            });
            return;
        }
    }

    if (valCode == "") {
        layer.msg('请输入验证码', {
            offset: 't',
            anim: 6
        });
        return;
    }
    data.passwd = md5(passwd);
    data.operationName = 'signInWithPassword';
    $.ajax({
        type: 'POST',
        url: "/register/mobilReg",
        data: data,
        success: function (res) {
            // toLogin();
            if (res.code == 200) {
                layer.msg(res.message, {
                    offset: 't',
                    anim: 6
                });
                toLogin();
            } else {
                layer.msg(res.message, {
                    offset: 't',
                    anim: 6
                });
                $("#registerBox input").val('');
                return;
            }
        },
        error: function (data) {

        }
    });
}

$('.navlogorebox').on('click', function () {
    loginLayer = layer.tab({
        type: 1,
        area: ['640px', '570px'],
        skin: 'layui-layer-molv',
        offset: ['20%', ' calc(50% - 260px)'],
        closeBtn: 0,
        // shadeClose: true,
        tab: [
            {
                title: '验证码登录', content: '<div id="cideBox" class="loginbox">\n' +
                    '    <div class="loginboxleft">\n' +
                    // '        <span class="bindPhone"></span> \n' +
                    '        <p><label>+86</label><input id="memMobile" name="memMobile" type="text" class="tel" autocomplete="off" placeholder="请输入手机号码" /></p>\n' +
                    '        <p><label></label><input id="valCode" name="valCode" autocomplete="off" type="text" class="yzm" placeholder="请输入验证码" /><button name="Abutton1"\n' +
                    '            type="button" id="verification">获取验证码</button><span id="djstime" style="display: none;">重新发送(<em id="waittime">60</em>&nbsp;)</span></p>\n' +
                    '        <button name="Abutton1" type="button" class="loginBtn" statue="code">登录</button>\n' +
                    '        <div>点击按钮即表示您同意并愿意遵守<a href="/user/registration?from=web">《服务协议》</a>和<a href="/user/privacy?from=web">《隐私条款》</a></div>\n' +
                    '        <div class="com-info" style="margin-top: 10px;">\n' +
                    '           <input class="agreementBtn" style="width: 15px;height: 15px;vertical-align: middle;" type="checkbox" value=""> <a href="/user/userinfo?from=web">《用户信息保护及对策声明》</a>\n' +
                    '       </div>\n' +
                    '    </div>\n' +
                    '</div>'
            },
            {
                title: '密码登录', content: '<div id="passBox" class="loginbox">\n' +
                    '    <div class="loginboxleft">\n' +
                    '        <p><label></label><input id="memMobile" name="memMobile" type="text" class="phone" autocomplete="off" placeholder="请输入手机号码" /></p>\n' +
                    '        <p><label></label><input id="passwd" name="passwd" type="password" class="pass" autocomplete="new-password" autocomplete="off" placeholder="请输入密码" /></p>\n' +
                    '        <button name="Abutton1" type="button" class="loginBtn" statue="pass" style="margin-top: 16px;">登录</button>\n' +
                    '        <p style="height: auto;background:transparent;text-align: right;"><span style="color:#01AB84" id="toReg">注册>></span></p>\n' +

                    '        <div>点击按钮即表示您同意并愿意遵守<a href="/user/registration?from=web">《服务协议》</a>和<a href="/user/privacy?from=web">《隐私条款》</a></div>\n' +
                    '        <div class="com-info" style="margin-top: 10px;">\n' +
                    '               <input class="agreementBtn2" style="width: 15px;height: 15px;vertical-align: middle;" type="checkbox" value=""> <a href="/user/userinfo?from=web">《用户信息保护及对策声明》</a>\n' +
                    '         </div>\n' +
                    '    </div>\n' +
                    // '    <div class="loginboxright"></div>\n' +
                    '</div>'
            },
            {
                title: '<img src="/static/images/wxdl.png">', content: '<div id="wxBox" style="padding-top: 0 !important;" class="loginbox">\n' +
                    '    <div class="loginboxleft">\n' +
                    '        <div id="wx-qrcode" style="margin:0px auto;"></div>\n' +
                    '</div>'
            },
            {
                title: '注册', content: '<div id="registerBox" class="loginbox" style="padding-top:10px;">\n' +
                    '    <div class="loginboxleft">\n' +
                    '        <p><label></label><input id="reg-userName" name="userName" type="text" class="userName" autocomplete="off" placeholder="请输入用户名" /></p>\n' +
                    '        <p><label>+86</label><input id="reg-memMobile" name="memMobile" type="text" class="phone" autocomplete="off" placeholder="请输入手机号码" /></p>\n' +
                    '        <p><input id="reg-valCode" name="valCode" autocomplete="off" type="text" class="yzm" placeholder="请输入验证码" /><button name="Abutton1"\n' +
                    '            type="button" id="regVerification">获取验证码</button><span id="regDjstime" style="display: none;">重新发送(<em id="regWaittime">60</em>)</span></p>\n' +
                    '        <p><input id="reg-passwd" name="passwd" type="password" class="pass" autocomplete="off" placeholder="请输入密码" /></p>\n' +
                    '        <p><input id="reg-passwdRe" name="passwd" type="password" class="pass" autocomplete="off" placeholder="请输入确认密码" /></p>\n' +
                    '        <button name="Abutton1" type="button" id="registerBtn" statue="pass" style="margin-top:10px">注册</button>\n' +
                    '        <div>点击按钮即表示您同意并愿意遵守<a href="/user/registration?from=web">《服务协议》</a>和<a href="/user/privacy?from=web">《隐私条款》</a></div>\n' +
                    '        <div class="com-info" style="margin-top: 10px;">\n' +
                    '               <input class="agreementBtn3" style="width: 15px;height: 15px;vertical-align: middle;" type="checkbox" value=""> <a href="/user/userinfo?from=web">《用户信息保护及对策声明》</a>\n' +
                    '         </div>\n' +
                    '    </div>\n' +
                    // '    <div class="loginboxright"></div>\n' +
                    '</div>'
            },
        ],
        success: function (layero) {
            // var arr = ['codeNav', 'passNav', 'wxNav', 'registerNav']
            var arr = ['codeNav', 'passNav', 'wxNav', 'registerNav']
            var titleList = $(layero).find(".layui-layer-title").children()
            for (var x = 0; x < 5; x++) {
                var obj = $(titleList[x]);
                obj.attr("id", arr[x]);
            }
            // $(layero).find("#codeNav").css({"margin-left": "100px"});

            $(layero).find(".layui-layer-title span").css({"cursor": "pointer"});
            $(layero).find(".layui-layer-title span").click(function () {
                var id = $(this).attr("id");
                if (id !== "wxNav") {
                    window.clearInterval(wxLoginSoleCodeGetTimer);
                }
                if (id !== "registerNav") {
                    $("#registerNav").hide()
                }
            })
            $("#registerNav").hide()
            $("#toReg").click(function () {
                toRegister()
            })
            $("#toLog").click(function () {
                toLogin()
            })
            $("#wxNav").click(function () {
                //暂时注释扫码登录
                createQRCode();
            })
            $(layero).prev().click(function () {
                window.clearInterval(wxLoginSoleCodeGetTimer);
            })
            // 验证
            $('#verification,#regVerification').click(function () {
                var id = $(this).attr("id");
                var mobile = $(".tel").val();
                if (id == "regVerification") {
                    mobile = $("#reg-memMobile").val();
                }
                if (id == "bindVerification") {
                    mobile = $("#bindMobile").val();
                }
                if (mobile == "") {
                    layer.msg('请填写手机号', {
                        offset: 't',
                        anim: 6
                    });
                    return;
                }
                if (!isMobile(mobile)) {
                    layer.msg('请填写正确的手机号码', {
                        offset: 't',
                        anim: 6
                    });
                    return;
                }
                sendYzm(mobile, id);
            })

            $('.loginBtn').click(function () {
                login(this);
            })

            $("#cideBox .tel").keypress(function(event){
                if(event.which === 13) {
                    var _this = $("#cideBox .loginBtn")
                    login(_this);
                }
            })
            $("#cideBox #valCode").keypress(function(event){
                if(event.which === 13) {
                    var _this = $("#cideBox .loginBtn")
                    login(_this);
                }
            })
            $('#cideBox').keydown(function (event) {
                if (event.keyCode == '13') {
                    var _this = $("#cideBox .loginBtn")
                    login(_this);
                }
            })
            $("#passBox .phone").keypress(function(event){
                if(event.which === 13) {
                    var _this = $("#passBox .loginBtn")
                    login(_this);
                }
            })
            $("#passBox #passwd").keypress(function(event){
                if(event.which === 13) {
                    var _this = $("#passBox .loginBtn")
                    login(_this);
                }
            })
            $('#passBox').keydown(function (event) {
                if (event.keyCode == '13') {
                    var _this = $("#passBox .loginBtn")
                    login(_this);
                }
            })

            $("#registerBtn").click(function () {
                register(this)
            })
            $("#reg-memMobile").keypress(function(event){
                if(event.which === 13) {
                    var _this = $("#registerBtn")
                    register(_this);
                }
            })
            $("#reg-passwd").keypress(function(event){
                if(event.which === 13) {
                    var _this = $("#registerBtn")
                    register(_this);
                }
            })
            $("#reg-passwdRe").keypress(function(event){
                if(event.which === 13) {
                    var _this = $("#registerBtn")
                    register(_this);
                }
            })
            $("#reg-valCode").keypress(function(event){
                if(event.which === 13) {
                    var _this = $("#registerBtn")
                    register(_this);
                }
            })
            $('#registerBox').keydown(function (event) {
                if (event.keyCode == '13') {
                    var _this = $("#registerBtn")
                    register(_this);
                }
            })

            // $(document).keyup(function (event) {
            //     console.log(event)
            //     if (event.keyCode == 13) {
            //         login();
            //     }
            // });

            //添加关闭按钮 关闭登录框跳转到首页
            $(layero).find('.layui-layer-setwin').append('<a id="closeLoginBtn" class="layui-layer-ico layui-layer-close layui-layer-close2" href="javascript:;"></a>');
            $("#closeLoginBtn").click(function (){
                var nowUrl = window.location.href;
                if(nowUrl.indexOf('/index/index') == -1){
                    window.location.href = serverHttp +'/index/index?from=web';
                }
            })
        },
    })
});


//用户登录后获取用户头像和积分
$(function () {
    $.ajax({
        type: 'post',
        url: '/user/loginUserImgWeb',
        success: function (res) {
            if (res.code == 200) {
                var integral = res.data.memTotalPoints;
                var userImg = res.data.memHeadimg;
                if (res.data.yh) {
                    playMusiclogin("首次登录", 200)
                }
                $('.navlogorebox').hide();
                $('.touxiang').attr('src', userImg);
                $('.userpho img').attr('src', userImg);
                var userLevel = ''
                if (integral >= 0 && integral <= 3000) {
                    userLevel = '/static/web/img/yizhe@2x.png';
                } else if (integral > 3000 && integral <= 6000) {
                    userLevel = '/static/web/img/yiling@2x.png';
                } else if (integral > 6000 && integral <= 9000) {
                    userLevel = '/static/web/img/yizun@2x.png';
                } else if (integral > 9000 && integral <= 12000) {
                    userLevel = '/static/web/img/yisheng@2x.png';
                } else if (integral > 12000 && integral <= 15000) {
                    userLevel = '/static/web/img/yishen@2x.png';
                } else {
                    userLevel = '/static/web/img/yixian@2x.png';
                }
                $('.xunzhang').attr('src', userLevel);
                // $('.txmask').attr('src', userLevel);
                $('.userpic').show();
            } else {
                $('.navlogorebox').show();
                $('.userpic').hide();
            }
        }
    })

    $.ajax({
        type: 'POST',
        url: "/user/getUserInfoWeb",
        success: function (res) {
            if (res.code == 200) {
                if (res.data.smrzFlag == 1) {
                    $('#smrzIconTrue').show()
                    $('#smrzIconFalse').hide()
                } else {
                    $('#smrzIconTrue').hide()
                    $('#smrzIconFalse').show()
                }
                if (res.data.ysrzFlag == 1) {
                    $('#ysrzIconTrue').show()
                    $('#ysrzIconFalse').hide()
                } else {
                    $('#ysrzIconTrue').hide()
                    $('#ysrzIconFalse').show()
                }
            }
        }
    })
    // header高亮
    if (document.URL.indexOf('index/index') > -1) {
        $('#indexHeader').addClass('navonclick')
    } else if (document.URL.indexOf('course/index') > -1) {
        $('#courseHeader').addClass('navonclick')
    } else if (document.URL.indexOf('live/index') > -1 || document.URL.indexOf('live/detail') > -1) {
        $('#liveHeader').addClass('navonclick')
    } else if (document.URL.indexOf('meeting/index') > -1 || document.URL.indexOf('meeting/details') > -1) {
        $('#meetingHeader').addClass('navonclick')
    } else if (document.URL.indexOf('course/index') > -1 || document.URL.indexOf('course/courseDetails') > -1 || document.URL.indexOf('/course/coursePrefectureList') > -1) {
        $('#courseHeader').addClass('navonclick')
    } else if (document.URL.indexOf('view/index') > -1 || document.URL.indexOf('view/detail') > -1) {
        $('#viewHeader').addClass('navonclick')
    } else if (document.URL.indexOf('courseware/index') > -1) {
        $('#coursewareHeader').addClass('navonclick')
    }
// 积分音效
    $('#conMusicBtn').on("click", () => {
        let au = document.getElementById('conMusic')
        au.play();
    })
})

function toPayWeb(objType, objId, objCount, orderId) {
    window.location.href = serverHttp + "/pay/pay?from=web&objType=" + objType + "&objId=" + objId + "&objCount=" + objCount + "&orderId=" + orderId;
}

function isregister(){
    $.ajax({
        type: 'get',
        url: "/register/isRegister",
        async: false,
        data:{
            wxId:getQueryVariable("wxId")
        },
        success: function (res) {
            if(res.code == 200){
                //未注册
                if(res.data.isRegister == false){
                    $(".navbindBox").show()
                }
            }
        },
        error: function (data) {

        }
    });
}

function gotoLogin(){
    if(getQueryVariable("wxId")){
        isregister();
    }else{
        $('.navlogorebox').trigger('click')
    }
}
// 判断web是否登录
function checkWebLogin() {
    var flag = false
    $.ajax({
        type: 'POST',
        url: "/index/isLogin",
        async: false,
        success: function (res) {
            if(res.code == 200){
                flag = true
            }else if(res.code == 10008){
                // $('.navlogorebox').trigger('click')
                gotoLogin();
                flag = false
            }else if(res.code == 10029){
                //在另一设备登录，重新登录
                flag = false
                layer.open({
                    title:"提示",//标题信息
                    content: '您的账号在另一台设备登录，如需继续使用，请重新登录',//内容区域
                    shift: 0,
                    offset: ['calc(50% - 80px)', 'calc(50% - 200px)'],
                    // shadeClose: true,
                    btn: ['登录'],
                    btn1: function(index){
                        layer.close(index)
                        $('.navlogorebox').trigger('click');
                    },
                    // 右上角关闭按钮的点击事件
                    cancel: function(index){
                        layer.close(index);
                        // $('.navlogorebox').trigger('click');
                        window.location.href = serverHttp + '/index/index?from=web'
                    }

                });
            }
        },
        error: function (data) {

        }
    });
    return flag
}

// 判断web是否登录
function againWebLogin() {
    var flag = false
    $.ajax({
        type: 'POST',
        url: "/index/isLogin",
        async: false,
        success: function (res) {
            if(res.code == 200){
                flag = true
            }else if(res.code == 10008){
                if(getQueryVariable("wxId")){
                    isregister();
                }
                flag = true
            }else if(res.code == 10029){
                //在另一设备登录，重新登录
                flag = false
                layer.open({
                    title:"提示",//标题信息
                    content: '您的账号在另一台设备登录，如需继续使用，请重新登录',//内容区域
                    shift: 0,
                    offset: ['calc(50% - 80px)', 'calc(50% - 200px)'],
                    // shadeClose: true,
                    btn: ['登录'],
                    btn1: function(index){
                        layer.close(index)
                        $('.navlogorebox').trigger('click');
                    },
                    // 右上角关闭按钮的点击事件
                    cancel: function(index){
                        layer.close(index);
                        // $('.navlogorebox').trigger('click');
                        window.location.href = serverHttp + '/index/index?from=web'
                    }

                });
            }
        },
        error: function (data) {

        }
    });
    return flag
}


//登出
$('.loginOut').on('click', function () {
    $.ajax({
        type: 'GET',
        url: "/login/logOutWeb",
        success: function (res) {
            localStorage.removeItem('isVip')

            //支付页面登出之后弹出登录框
            var currentUrl = window.location.href;
            if(currentUrl.indexOf('/pay/pay') != -1){
                $('.navlogorebox').trigger('click')
            } else if(currentUrl.indexOf('/user/') != -1){
                window.location.href = serverHttp + '/index/index?from=web'
            } else{
                window.location.reload();
            }
        },
        error: function (data) {

        }
    });
})

var wxLoginSoleCodeGetTimer;

function createQRCode() {
    // 获取当前时间戳准备存入redis
    var soleCode = Date.parse(new Date());
    $.get(serverHttp + "/login/wxLoginSole", {soleCode: soleCode}, function (data) {
        if (data.code == 200) {
            var localurl = encodeURIComponent(window.location.href);
            var redirect_uri = serverHttp + '/login/wxLoginOAuth?redirectUrl='+localurl;
            redirect_uri = encodeURIComponent(redirect_uri);
            // 实例微信登录二维码JS对象
            var obj = new WxLogin({
                self_redirect: false,
                id: "wx-qrcode",
                appid: "wxac5d392b940d1f6f",
                scope: "snsapi_login",
                redirect_uri: redirect_uri,
                state: soleCode,
            })
            // 设置定时器每秒请求后台获取redis中时间戳做对比
            wxLoginSoleCodeGetTimer = window.setInterval("getWxLoginSoleCode('" + soleCode + "')", 1000);
        } else {
            alert('出错了，请重试！');
        }
    });

}

//定时请求微信登录数据
function getWxLoginSoleCode(soleCode) {
    $.get(serverHttp + "/login/getWxLoginSoleCode", {soleCode: soleCode}, function (data) {
        if (data.code == "success") {
            if (data.info == "stop") {
                //    二维码已过期，停驶定时器且提示二维码已过期
                window.clearInterval(wxLoginSoleCodeGetTimer);
                //    先删除微信二维码元素
                $("#wx-qrcode").empty()
                //    自定义元素覆盖微信二维码元素
                $("#wx-qrcode").append('<div style="text-align: center;padding-top: 120px;"><p>二维码已失效</p><button style="margin-top: 5px;" id="retrieve-qrcode" type="button" class="layui-btn layui-btn-normal">重新获取二维码</button></div>')
            }
        } else {
            //    后台异常或没有soleCode参数，停止定时器
            window.clearInterval(wxLoginSoleCodeGetTimer);
        }
    })
}

$(document).on("click", "#retrieve-qrcode", function () {
    // 先删除自己元素
    $("#wx-qrcode").empty();
    // 重新加上二维码
    createQRCode();
})

function toRegister() {
    $("#wxNav").hide()
    $("#passNav").hide()
    $("#codeNav").hide()
    $("#registerNav").show();
    $("#registerNav").siblings().removeClass();
    $("#registerNav").addClass("layui-this");
    $(".layui-layer-title").addClass("layui-this-center");
    $("#layui-layer-tabli").removeClass("layui-this");
    $(".layui-layer-tabli").hide()
    $($(".layui-layer-tabli")[3]).show()
    $($(".layui-layer-tabli")[3]).addClass("layui-this")
}

function toLogin() {
    $(".layui-layer-title").removeClass("layui-this-center");
    $("#registerNav").hide();
    $("#wxNav").show()
    $("#passNav").show()
    $("#codeNav").show()
    $("#codeNav").siblings().removeClass();
    $("#codeNav").addClass("layui-this");
    $("#layui-layer-tabli").removeClass("layui-this");
    $(".layui-layer-tabli").hide()
    $($(".layui-layer-tabli")[0]).show()
    $($(".layui-layer-tabli")[0]).addClass("layui-this")
}

// 阅读 分享加积分
function saveUserDorecWeb(oprType, objType, objId, url, source) {
    $.ajax({
        type: 'POST',
        url: serverHttp + "/user/saveUserDorecWeb",
        data: {
            oprType: oprType,
            objType: objType,
            objId: objId,
            url: url,
            source,
        },
        success: function (data) {
            if (data.code == 200 && data.data) {
                if (oprType == 1)
                    playMusic("阅读文章", 5)
                else if (oprType == 2)
                    playMusic("分享转发", 10)
            }
        },
        error: function (data) {

        }
    });
}

// 积分音效
function playMusic(type, count) {
    layer.open({
        type: 1,
        area: ['300px', '180px'],
        skin: 'layui-layer-sign',
        shift: 0,
        offset: ['40%', ' calc(50% - 150px)'],
        time: 2000,
        title: false,
        anim: 1,
        closeBtn: 0,
        shadeClose: true,
        content: `<p style="margin-top:60px;text-align:center;font-size: 25px;font-weight: bold;color: #555555">${type}</p>
              <p style="margin-top:20px;text-align:center;color:#FFAC00; font-size: 20px;">
              <img style="width: 25px" src="http://files.qkyxzx.com/html5/jb.png" /> +${count}</p>`,
        success: function () {
            $('#conMusicBtn').trigger('click')
        }
    });

}

function playMusiclogin(type, count) {
    layer.open({
        type: 1,
        area: ['300px', '180px'],
        skin: 'layui-layer-sign',
        offset: ['40%', ' calc(50% - 150px)'],
        shift: 0,
        time: 4000,
        title: false,
        anim: 1,
        closeBtn: 0,
        shadeClose: true,
        content: `<p style="margin-top:60px;text-align:center;font-size: 25px;font-weight: bold;color: #555555">${type}</p>
              <p style="margin-top:20px;text-align:center;color:#FFAC00; font-size: 20px;">
              <img style="width: 25px" src="http://files.qkyxzx.com/html5/jb.png" /> +${count}</p>`,
        success: function () {
            $('#conMusicBtn').trigger('click')
        }
    });

}

$('#search').click(function() {
    searchBtn();
});

$("#searchVal").keypress(function(event){
    if(event.which === 13) {
        searchBtn();
    }
})
function searchBtn(){
    var val = $('#searchVal').val();
    window.location.href = "/index/search?from=web&searchVal=" + val;
    sessionStorage.removeItem('searchTitleweb')
}

function isIdentityCard(idcode){
    // 函数参数必须是字符串，因为⼆代⾝份证号码是⼗⼋位，⽽在中，⼗⼋位的数值会超出计算范围，造成不精确的结果，导致最后两位和计算的值javascript不⼀致，从⽽该函数出现错误。
    // 详情查看的数值范围javascript
    // 加权因⼦

    var weight_factor =[7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2];
    // 校验码

    var check_code =['1','0','X','9','8','7','6','5','4','3','2'];
    var code = idcode +"";
    // 最后⼀位
    var last = idcode[17];//
    var seventeen = code.substring(0,17);
    // ISO 7064:1983.MOD 11-2
    //  判断最后⼀位校验码是否正确

    var arr = seventeen.split("");
    var len = arr.length;
    var num =0;
    for(var i =0; i < len; i++){
        num = num + arr[i]* weight_factor[i];
    }
    //  获取余数

    var resisue = num %11;
    var last_no = check_code[resisue];
    //  格式的正则

    //   正则思路

    /*
    第⼀位不可能是
    0
    第⼆位到第六位可以是
    0-9
    第七位到第⼗位是年份，所以七⼋位为
    或者
    19
    20
    ⼗⼀位和⼗⼆位是⽉份，这两位是
    之间的数值
    01-12
    ⼗三位和⼗四位是⽇期，是从
    之间的数值
    01-31
    ⼗五，⼗六，⼗七都是数字
    0-9
    ⼗⼋位可能是数字
    ，也可能是
    0-9
    X
        */
    var idcard_patter = /^[1-9][0-9]{5}([1][9][0-9]{2}|[2][0][0|1][0-9])([0][1-9]|[1][0|1|2])([0][1-9]|[1|2][0-9]|[3][0|1])[0-9]{3}([0-9]|[X])$/;
    //   判断格式是否正确

    var format = idcard_patter.test(idcode);
    //   返回验证结果，校验码和格式同时正确才算是合法的⾝份证号码

    return last === last_no && format ?true:false;
};
function isEmptyStr (str) {
    if ( str == "" ) return true;
    var regu = "^[ ]+$";
    var re = new RegExp(regu);
    return re.test(str);
}
