var remindLayer;
new Particleground.particle('#canvus', {
    color: '#70e1ff',
    maxR: '1.5',
    distance: '100'
});
$(document).ready(function () {
    if (window.top != window.self) {
        window.top.location.href = "/sso";
    }

    getImageCode();
});


$("#codeDiv").on("click", "#_cap", function () {
    getImageCode();
})

function getImageCode() {
    var url = '/sso/user/getImgCode';
    var xhr = new XMLHttpRequest();
    xhr.open("post", url, true);
    xhr.responseType = "blob";
    xhr.onload = function () {
        if (this.status === 200) {
            var blob = this.response;
            var img = document.createElement("img");
            img.style.height = '45px';
            img.style.cursor = 'pointer';
            img.id = '_cap';
            img.onload = function (e) {
                window.URL.revokeObjectURL(img.src);
            };
            img.src = window.URL.createObjectURL(blob);
            $("#codeDiv").html(img);
        }
    }
    xhr.send();
}

/******************
 * 点击登录按钮触发事件
 *******************/
$("#login").click(function () {
    login();
});
/******************
 * Enter触发登录事件
 *******************/
$(document).keyup(function (event) {
    if (event.keyCode == 13) {
        login();
    }
});

function login() {
    //验证用户名
    var userFlag = true;
    var username = $("#username").val();
    username = username.replace(/(^\s*)|(\s*$)/g, '');
    if (username.length < 1) {
        userFlag = false;
    }
    //验证密码
    var pwdFlag = true;
    var password = $("#password").val();
    password = password.replace(/(^\s*)|(\s*$)/g, '');
    if (password.length < 1) {
        pwdFlag = false;
    }
    //验证图形验证码
    var codeFlag = validImgCode();
    var loginFlag = false;
    if (userFlag) {
        if (pwdFlag) {
            if (codeFlag) {
                loginFlag = true;
            } else {
                $("#errorS").html("请输入正确的验证码");
                getImageCode();
            }
        } else {
            $("#errorS").html("密码为空");
            getImageCode();
        }
    } else {
        if (pwdFlag) {
            $("#errorS").html("用户名为空");
            getImageCode();
        } else {
            $("#errorS").html("请输入正确的用户名/密码");
            getImageCode();
        }
    }
    displayErrorDiv();
    //通过上面判断后，用户输入符合基本的规格
    if (loginFlag) {
        $("#errorS").html("");
        noneErrorDiv();

        //将所有表单数据发送后台校验
        var username = $("#username").val();
        var password = $("#password").val();
        var code = $("#_checkcode").val();
        //Xss攻击处理
        username = filterXSS(username);
        password = filterXSS(password);
        username = encrypt(username);
        $.ajax({
            type: "POST",
            url: "/sso/user/generateSM2Key",
            /*url: "/sso/user/generateRSAKey",*/
            dataType: "text",
            data: {
                username: username
            },
            success: function (data) {
                var info = $.parseJSON(data);
                if (info.code === 200) {
                    var pubkeyHex = info.body;//获取SM2加密公钥

                    var sm3Pwd = sm3Digest(password);//SM3加密
                    var sm2Pwd =sm2Encrypt(sm3Pwd + "|" + password, pubkeyHex, 0);//SM2公钥加密
                    /*var pubkeyHex = new RSAUtils.getKeyPair(info.body.exponent, "", info.body.modulus);//获取RSA加密公钥
                    var sm3Pwd = sm3Encrypt(password);//SM3加密
                    var fitPwd = sm3Pwd + "|" + password;//驗證組裝
                    var reversedPwd = fitPwd.split("").reverse().join("");//內容顛倒
                    var sm2Pwd = RSAUtils.encryptedString(pubkeyHex, reversedPwd);//RSA加密*/
                    $.ajax({
                        type: "POST",
                        url: "/sso/user/login",
                        dataType: "text",
                        data: {
                            username: username,
                            password: sm2Pwd,
                            checkcode: code
                        },
                        statusCode: {
                            203: function () {
                                location.href = "user/judgeLogin";
                            }
                        },
                        success: function (data) {
                            var info = $.parseJSON(data);
                            if (info.code !== 200) {
                                if (info.message === "用户密码已经过期" | info.message === "长期未登录，请修改密码" | info.message === '用户首次登录') {
                                    remindModifyPWD(info.message, username);
                                    getImageCode();
                                } else {
                                    if (info.message !== "登录成功") {
                                        $("#errorS").html(info.message);
                                        displayErrorDiv();
                                        getImageCode();
                                    }
                                }
                            }
                        }
                    });

                }
            }
        });
    }
}

//显示错误DIV
function displayErrorDiv() {
    $("#errorD").css("display", "block");
    $("#usernameDiv").css("margin-top", "0")
}

//隐藏错误DIV
function noneErrorDiv() {
    $("#errorD").css("display", "none");
    $("#usernameDiv").css("margin-top", "45px")
}


//验证用户名
function validUsername() {
    var username = $("#username").val();
    username = username.replace(/(^\s*)|(\s*$)/g, '');
    var userRepx = /^[a-zA-Z0-9]{3,16}$/;
    if (!userRepx.test(username)) {
        return false;
    }
    return true;
}

//验证用户密码
function validPassword(password) {
    password = password.replace(/(^\s*)|(\s*$)/g, '');
    var pwdRepx = /^(?=.*[a-zA-Z])(?=.*\d)(?=.*[@#_!$%^&*()?<>/|~,\\\-+\.]).{8,16}$/;
    if (!pwdRepx.test(password)) {
        return false;
    }
    return true;
}

//验证图形验证码
function validImgCode() {
    var imgCode = $("#_checkcode").val();
    imgCode = imgCode.replace(/(^\s*)|(\s*$)/g, '');
    var imgCodeRepx = /^[0-9a-zA-Z]{4}$/;
    if (!imgCodeRepx.test(imgCode)) {
        return false;
    }
    return true;
}

$("#_checkcode").click(function () {
    var v = $(this).val();
    if (v == "验证码不正确") {
        $(this).val("");
    }
});


// 字符转义数据反编码函数
function htmlDecode(str) {
    return str.replace(/\&quot;/g, "\"").replace(/\&lt;/g, "<").replace(
        /\&gt;/g, ">").replace(/\&nbsp;/g, " ").replace(/\&amp;/g, "&");
}

// html字符转义过滤函数
function htmlEncode(str) {
    return str.replace(/&/g, "&amp;").replace(/\"/g, "&quot;").replace(/</g,
        "&lt;").replace(/>/g, "&gt;").replace(/ /g, "&nbsp;");
}

//提示用户修改密码
function remindModifyPWD(msg, username) {
    if (remindLayer === undefined | remindLayer === null) {
        remindLayer = layer.open({
            type: '1',
            title: msg,
            resize: false,
            shadeClose: true,
            scrollbar: false,
            area: "350px",
            closeBtn: 0,
            content: "<form class='form-horizontal pdr15 pdt15 pdl15'><div class='form-group'><label for='newPwd' class='col-sm-3 control-label'>新密码</label><div class='col-sm-9'><input type='password' class='form-control' id='newPwd' ></div></div><div class='form-group'><label for='comfirPwd' class='col-sm-3 control-label'>确认密码</label><div class='col-sm-9'><input type='password' class='form-control' id='comfirPwd' ></div></div></form>",
            btn: ['确定', '取消'],
            yes: function (index, layero) {
                var newPwd = $("#newPwd").val();
                newPwd = newPwd.replace(/(^\s*)|(\s*$)/g, '');
                var comfirPwd = $("#comfirPwd").val();
                comfirPwd = comfirPwd.replace(/(^\s*)|(\s*$)/g, '');
                if (validPassword(newPwd)) {
                    if (validPassword(comfirPwd)) {
                        if (newPwd === comfirPwd) {
                            //执行更新用户密码的操作
                            $.ajax({
                                type: "POST",
                                url: "/sso/user/generateSM2Key",
                                dataType: "text",
                                data: {
                                    username: username
                                },
                                success: function (data) {
                                    var info = $.parseJSON(data);
                                    if (info.code === 200) {
                                        var pubkeyHex = info.body;//获取SM2加密公钥
                                        var sm3Pwd = sm3Digest(comfirPwd);//SM3加密
                                        var sm2Pwd =sm2Encrypt(sm3Pwd + "|" + comfirPwd, pubkeyHex, 0);//SM2公钥加密
                                        modifPwd(username, sm2Pwd);
                                    }
                                }
                            });
                        } else {
                            layer.msg('密码不一致', {icon: 2, time: 2000});
                        }
                    } else {
                        layer.msg('确认密码不正确', {icon: 2, time: 2000});
                    }
                } else {
                    layer.msg('新密码不正确', {icon: 2, time: 2000});
                }
            }, btn2: function (index, layero) {
                layer.close(index);
            },
            end: function (index) {
                remindLayer = undefined;
                layer.close(index);
            }
        })
    }
}

//执行修改密码
function modifPwd(username, newPwd) {
    //Xss攻击处理
    username = filterXSS(username);
    newPwd = filterXSS(newPwd);
    $.ajax({
        type: "POST",
        url: "/sso/user/modifyPwd",
        dataType: "json",
        data: {
            username: username,
            password: newPwd
        },
        success: function (data) {
            if (data.code === 500) {
                layer.msg(data.message, {icon: 2, time: 2000});
            } else {
                getImageCode();
                layer.msg('修改密码成功，重新登录', {icon: 6, time: 2000});
                layer.close(remindLayer);
            }
        }
    })
}

/**
 * 加密（需要先加载lib/aes/aes.min.js文件）
 * @param word
 * @returns {*}
 */
function encrypt(word) {
    var key = CryptoJS.enc.Utf8.parse("njcnpqsqpncjnggg");
    var srcs = CryptoJS.enc.Utf8.parse(word);
    var encrypted = CryptoJS.AES.encrypt(srcs, key, {mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7});
    return encrypted.toString();
}

/**
 * 解密
 * @param word
 * @returns {*}
 */
function decrypt(word) {
    var key = CryptoJS.enc.Utf8.parse("njcnpqsqpncjnggg");
    var decrypt = CryptoJS.AES.decrypt(word, key, {mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7});
    return CryptoJS.enc.Utf8.stringify(decrypt).toString();
}