<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <!-- <meta name="viewport"
        content="width=device-width, initial-scale=1, maximum-scale=1"> -->
    <title>登录</title>
    <link rel="stylesheet"
          href="${pageContext.request.contextPath}/static/layui/css/layui.css">
    <link rel="stylesheet"
          href="${pageContext.request.contextPath}/static/css/adminLogin.css">
    <script src="${pageContext.request.contextPath}/static/js/jquery.min.js"></script>
    <script src="${pageContext.request.contextPath}/static/layui/layui.js"></script>
</head>
<script type="text/javascript">
    if (top.location != self.location) {
        alert('登录信息失效，请重新登录！');
        top.location = self.location;
    }
</script>
<body>
<div class="wrap">
    <img src="img/bg401.jpg" class="imgStyle">
    <div class="loginForm">
        <form>
            <div class="logoHead">
                <h1 style="margin-top: 15px"> 领淘产品报价系统</h1>
            </div>
            <div class="usernameWrapDiv">
                <div class="usernameLabel">
                    <label>用户名:</label>
                </div>
                <div class="usernameDiv">
                    <i class="layui-icon layui-icon-username adminIcon"></i>
                    <input id="loginUsername" autofocus="autofocus" autocomplete="off" class="layui-input adminInput"
                           type="text" name="username" placeholder="请输入用户名">
                </div>
            </div>
            <div class="usernameWrapDiv">
                <div class="usernameLabel">
                    <label>密码:</label>
                </div>
                <div class="passwordDiv">
                    <i class="layui-icon layui-icon-password adminIcon"></i>
                    <input id="loginPassword" class="layui-input adminInput" type="password" name="password"
                           placeholder="请输入密码">
                </div>
            </div>
            <div class="usernameWrapDiv" style="display:none">
                <div class="usernameLabel">
                    <label>验证码:</label>
                </div>
                <div class="cardDiv">
                    <input id="loginCard" class="layui-input cardInput" type="text" name="card" autocomplete="off"
                           placeholder="请输入验证码">
                </div>
                <div class="codeDiv">
                    <input id="loginCode" class="layui-input codeInput" type="button">
                </div>
            </div>
            <span><font color="red">${errorInfo}</font></span>
            <div class="usernameWrapDiv">
                <div class="submitLabel">
                    <label>没有账号？<a href="#" id="loginRegister">点击注册</a></label>
                </div>
                <div class="submitDiv">
                    <input id="loginBtn" type="button" class="submit layui-btn layui-btn-primary" value="登录"></input>
                </div>
            </div>
            <div style="text-align:center;margin-top: 20px;font-size: 16px;">您的ip是:<input
                    style="border: unset;background: unset;" id="ui_ip" type="text" readonly="readonly" name="ui_ip"
                    value=""/></div>
        </form>
    </div>
</div>
<script>
    layui.use(['layer'], function () {
        var layer = layui.layer;

        // 监听回车登录事件
        $('body').keydown(function () {
            if (event.keyCode == '13') {
                login();
            }
        });
    })

    $(function () {
        // 页面初始化生成验证码
        window.onload = createCode('#loginCode');
        // 验证码切换
        $('#loginCode').click(function () {
            createCode('#loginCode');
        });
        // 登陆事件
        $('#loginBtn').click(function () {
            login();
        });
        // 注册事件
        $('#loginRegister').click(function () {
            register();
            getRoleList();
        });

        getIp();
    });

    function getIp() {
        $.ajax({
            url: "${pageContext.request.contextPath}/SysUser/getIp",
            type: "get",
            success: function (obj) {
                $("#ui_ip").attr("value", obj.data.ip);
            }
        });
    }

    // 生成验证码
    function createCode(codeID) {
        var code = "";
        // 验证码长度
        var codeLength = 4;
        // 验证码dom元素
        var checkCode = $(codeID);
        // 验证码随机数
        var random = [1, 2, 3, 4, 5, 6, 7, 8, 9, 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R',
            'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
        for (var i = 0; i < codeLength; i++) {
            // 随机数索引
            var index = Math.floor(Math.random() * 33);
            code += random[index];
        }
        // 将生成的随机验证码赋值
        checkCode.val(code);
    }

    // 不在授权IP中登录次数
    var ipErrorCount = 0;
    // 密码错误次数
    var passwordErrorCount = 0;

    // 校验验证码、用户名、密码
    function validateCode(inputID, codeID) {
        var inputCode = $(inputID).val().toUpperCase();
        var cardCode = $(codeID).val();
        var loginUsername = $('#loginUsername').val();
        var loginPassword = $('#loginPassword').val();
        if ($.trim(loginUsername) == '' || $.trim(loginUsername).length <= 0) {
            layer.msg("用户名不能为空", function () {
            });
            return false;
        }
        if ($.trim(loginPassword) == '' || $.trim(loginPassword).length <= 0) {
            layer.msg("密码不能为空");
            return false;
        }
        // 密码错误3次以上要输入验证码
        if (passwordErrorCount > 2) {
            if (inputCode.length <= 0) {
                layer.msg("请输入验证码");
                return false;
            }

            if (inputCode != cardCode) {
                layer.msg("验证码不正确！", function () {
                });
                return false;
            }
        }
        return true;
    }

    function login() {
        // window.location.href="./views/main.jsp";
        if (!validateCode('#loginCard', '#loginCode')) {
            //阻断提示
        } else {
            var loginUsername = $('#loginUsername').val();
            var loginPassword = $('#loginPassword').val();
            var params = {};
            params.loginUsername = loginUsername;
            params.loginPassword = loginPassword;
            // var loginLoadIndex = layer.load(2);
            $.ajax({
                type: 'post',
                //url:window.location.protocol+'//'+window.location.host+'/security-web/login.do',
                //data:JSON.stringify(params),
                //contentType:'application/json',

                url: "${pageContext.request.contextPath}/SysUser/login",
                data: {
                    "username": loginUsername,
                    "password": loginPassword
                },
                success: function (data) {
                    window.location.href = "./views/main.jsp";
                    // layer.close(loginLoadIndex);
                    // var jsonData = JSON.parse(data);
                    /*  if (data){
                         window.location.href = './main.jsp';
                     }else{
                          $('#loginBtn').val("登录");
                     } */
                },
                error: function (data) {
                    if (data.responseText == '300') {
                        layer.msg("用户未激活,请联系管理员!", function () {
                        });
                    } else if (data.responseText == '404') {
                        ipErrorCount++;
                        // 连续失败三次以上，刷新验证码
                        if (ipErrorCount > 2) {
                            // 刷新验证码
                            createCode('#loginCode')
                        }
                        layer.msg('登录异常,请联系开发人员!', {offset: ['550px', '800px']}, function () {
                        });
                    } else {
                        passwordErrorCount++;
                        if (passwordErrorCount > 2) {
                            $(".usernameWrapDiv").show()
                        }
                        layer.msg("账号密码有误！", function () {
                        });
                    }
                }
            });
        }
    }

    function getRoleList() {
        // 每次点击注册都清空角色列表
        $('#roleSelect').empty();
        // 下拉框第一列添加空的option
        $('#roleSelect').append(new Option("", ""));
        //一访问页面就调用,查询可以被注册的角色名称、id
        $.ajax({
            url: '${pageContext.request.contextPath}/SysUser/getRoleName',
            dataType: 'json',
            data: {
                isRegist: "1"
            }, //查询状态为允许被注册的角色
            type: 'post',
            success: function (data) {
                $.each(data, function (index, item) {
                    $('#roleSelect').append(new Option(item, index));//往下拉菜单里添加元素
                });
            }
        });
    }

    // 注册流程
    function register() {
        layer.open({
            type: '1',
            content: $('.registerPage'),
            title: '注册',
            area: ['430px', '500px'],
            skin: "layui-layer-molv",
            btn: ['注册', '重置', '取消'],
            closeBtn: '1',
            btn1: function (index, layero) {
                //注册回调
                //layer.close(index);
                var registerRealname = $('#registerRealname').val();
                var registerUsername = $('#registerUsername').val();
                var registerPassword = $('#registerPassword').val();
                var registerWellPassword = $('#registerWellPassword').val();
                var selectValue = $('#roleSelect option:selected').val();
                if ($.trim(registerUsername) == '' || $.trim(registerUsername).length <= 0) {
                    layer.msg("注册用户名不能为空！", function () {
                    });
                    return false;
                } else if ($.trim(registerPassword) == '' || $.trim(registerPassword).length <= 0) {
                    layer.msg("密码不能为空！");
                    return false;
                } else if ($.trim(registerRealname) == '' || $.trim(registerRealname).length <= 0) {
                    layer.msg("姓名不能为空！");
                    return false;
                } else if ($.trim(selectValue) == '' || $.trim(selectValue).length <= 0) {
                    layer.msg("店铺不能为空！");
                    return false;
                }
                if (registerPassword != registerWellPassword && registerPassword != '') {
                    layer.msg("俩次输入密码不一致", function () {
                    });
                    return false;
                }
                /*  var params = {};
                 params.registerUsername = registerUsername;
                 params.registerPassword = registerPassword;
                 params.registerWellPassword = registerWellPassword;
                 params.selectValue = selectValue;
                 var registerLoadIndex = layer.load(2); */
                $.ajax({
                    type: 'post',
                    //url:window.location.protocol+'//'+window.location.host+'/security-web/register.do',
                    url: "${pageContext.request.contextPath}/SysUser/register",
                    dataType: 'json',
                    //data:JSON.stringify(params),
                    //contentType:'application/json',
                    data: {
                        "realname": registerRealname,
                        "username": registerUsername,
                        "password": registerPassword,
                        "role": selectValue,
                    },
                    success: function (data) {
                        if (data.code == 200) {
                            layer.msg('录入成功！', {icon: 6, offset: "auto", time: 1000});//提示框
                            setTimeout(function () {
                                layer.close(index);//关闭弹出层
                            }, 1100);
                        } else {
                            layer.tips(data.msg, '#registerUsername', {tips: [2, '#009688'], time: 2000});
                        }
                    }
                });
            },
            btn2: function (index, layero) {
                //重置回调
                var registerUsername = $('#registerUsername').val("");
                var registerPassword = $('#registerPassword').val("");
                var registerWellPassword = $('#registerWellPassword').val("");
                // 防止注册页面关闭
                return false;
            },
            btn3: function (index, layero) {
                //取消回调
            }
        })
    }
</script>
</body>
<div class="registerPage">
    <div class="registerDiv">
        <form class="layui-form">
            <div class="usernameWrapDiv">
                <div class="usernameLabel">
                    <label>用户名:</label>
                </div>
                <div class="usernameDiv">
                    <i class="layui-icon layui-icon-username adminIcon"></i>
                    <input id="registerUsername" lay-verify="required" autocomplete="off" autofocus="autofocus"
                           class="layui-input adminInput" type="text" name="username" placeholder="输入用户名">
                </div>
            </div>
            <div class="usernameWrapDiv">
                <div class="usernameLabel">
                    <label>密码:</label>
                </div>
                <div class="passwordDiv">
                    <i class="layui-icon layui-icon-password adminIcon"></i>
                    <input id="registerPassword" class="layui-input adminInput" type="password" name="password"
                           placeholder="输入密码">
                </div>
            </div>
            <div class="usernameWrapDiv">
                <div class="usernameLabel">
                    <label>确认密码:</label>
                </div>
                <div class="passwordDiv">
                    <i class="layui-icon layui-icon-password adminIcon"></i>
                    <input id="registerWellPassword" class="layui-input adminInput" type="password" name="password"
                           placeholder="输入密码">
                </div>
            </div>
            <div class="usernameWrapDiv">
                <div class="usernameLabel">
                    <label>真实姓名:</label>
                </div>
                <div class="usernameDiv">
                    <i class="layui-icon layui-icon-username adminIcon"></i>
                    <input id="registerRealname" lay-verify="required" autocomplete="off" autofocus="autofocus"
                           class="layui-input adminInput" type="text" name="realname" placeholder="输入姓名">
                </div>
            </div>
            <div class="usernameWrapDiv">
                <div class="usernameLabel">
                    <label>所属店铺:</label>
                </div>
                <div class="usernameDiv">
                    <i class="layui-icon layui-icon-service adminIcon"></i>
                    <select name="role" id="roleSelect" class="layui-select" lay-search lay-verify="required"></select>
                </div>
            </div>
        </form>
    </div>
</div>
</html>