<!doctype html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <meta name="_csrf" th:content="${_csrf.token}">
    <meta name="_csrf_header" th:content="${_csrf.headerName}">
    <link th:href="@{/webjars/bootstrap/4.3.1/css/bootstrap.min.css}" rel="stylesheet">
    <title th:text="#{login}"></title>
    <script>
        <!-- 解决登录页面嵌套问题 -->
        if (window != top) {
            top.location.href = location.href;
        }
    </script>
    <style>
        body, html {
            margin: 0;
            padding: 0;
            width: 100%;
            height: 100%;
            background-color: #F1F3F4;
        }

        form {
            background-color: white;
            padding: 20px 6px 20px 6px;
        }

        body {
            /*background-color: #F1F3F4;*/
            background-image: url("/img/bg_login.jpg");
            background-position: 50% 50%;
            background-size: cover;
        }

        .h-10 {
            height: 10% !important;
        }

        .h-90 {
            height: 90% !important;
        }

        .h-5 {
            height: 5% !important;
        }

        .h-95 {
            height: 95% !important;
        }

        .error {
            color: red;
        }
    </style>
</head>
<body>
<div class="container-fluid h-100">
    <nav class="row h-5">
        <div class="offset-md-11 col-md-1">
            <select id="localeSelect">
                <option value="zh_CN">中文</option>
                <option value="en_US">English</option>
            </select>
        </div>
    </nav>
    <div class="row align-items-center h-95">
        <form id="loginForm" th:action="@{login}" method="post" class="offset-xl-4 col-xl-4 offset-lg-4 col-lg-4 offset-md-3 col-md-6 col-sm-10">
            <h1 class="text-center" th:text="#{signIn}"></h1>
            <div th:if="${(param.errMsg != null)}">
                <div class="text-center error" th:text="${param.errMsg}"></div>
            </div>
            <div class="form-group">
                <label for="username"></label>
                <input type="text" class="form-control" id="username" name="username" th:placeholder="#{usernameOrMobileOrEmail}">
            </div>
            <div class="form-group">
                <label for="password"></label>
                <input type="password" class="form-control" id="password" name="password" th:placeholder="#{password}">
            </div>
            <div class="form-group">
                <div class="row">
                    <div class="col-md-6 col-sm-6">
                        <label for="veriCode"></label>
                        <input type="text" class="form-control" id="veriCode" name="veriCode"
                               th:placeholder="#{veriCode}">
                    </div>
                    <div class="col-md-6 col-sm-6">
                        <!--<canvas class="codeimg" id="codeimg">
                            你的浏览器不支持canvas。
                        </canvas>-->
                        <img id="randCodeImage" th:src="@{/api/oauthUsers/getVeriCode}" style="width:100px;height:30px;float:right;margin:25px 20px 0 0;"/>
                        <div style="clear: both"></div>
                    </div>
                </div>
            </div>
            <div class="form-check" style="padding-bottom: 10px;">
                <label class="form-check-label">
                    <input class="form-check-input" type="checkbox" name="rememberPassword"><span th:text="#{rememberPassword}"></span>
                </label>
            </div>
            <button type="submit" name="submit" class="btn btn-raised btn-primary col-12" th:text="#{login}"></button>
        </form>
        <!--<div class="col-lg-4 col-md-3 col-sm-2">
            <select class="form-control" id="exampleFormControlSelect1" style="width: 60px">
                <option>中文</option>
                <option>English</option>
            </select>
        </div>-->
    </div>

</div>
<!-- jQuery 3 -->
<script th:src="@{/webjars/jquery/3.4.1/jquery.min.js}"></script>
<script th:src="@{/webjars/popper.js/1.15.0/umd/popper.min.js}"></script>
<script th:src="@{/webjars/bootstrap/4.3.1/js/bootstrap.min.js}"></script>
<script th:src="@{/webjars/jquery-validation/1.18.0/dist/jquery.validate.min.js}"></script>
<script th:if="${session.locale == 'zh_CN'}" th:src="@{/webjars/jquery-validation/1.18.0/src/localization/messages_zh.js}"></script>
<script th:src="@{/webjars/jquery-cookie/1.4.1-1/jquery.cookie.js}"></script>
<script>
    function setTokenInHeader() {
        let token = $("meta[name='_csrf']").attr("content");
        let header = $("meta[name='_csrf_header']").attr("content");
        $(document).ajaxSend(function (e, xhr, options) {
            xhr.setRequestHeader(header, token);
        });
    }

    function reloadCodeImage() {
        var date = new Date();
        var img = document.getElementById("randCodeImage");
        img.src = "/api/oauthUsers/getVeriCode?a=" + date.getTime();
    }

    $('#randCodeImage').click(function () {
        reloadCodeImage();
    });


    $().ready(function () {
        setTokenInHeader();

        jQuery.validator.addMethod("password", function (value, element, param) {
            let rex = /^(?![A-Z]+$)(?![a-z]+$)(?!\d+$)(?![\W_]+$)\S{6,16}$/;
            return this.optional(element) || (rex.test(value));
        }, "必须包含数字、字母或特殊字符");

        jQuery.validator.addMethod("mobileOrEmail", function (value, element, param) {
            let mobile = /^1[3-9]+\d{9}$/;
            let email = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
            return this.optional(element) || (email.test(value) || mobile.test(value));
        }, "[[#{pleaseInputValidMobileOrEmail}]]");

        function validForm() {
            return $("#loginForm").validate({
                debug: false,
                onsubmit: true,// 是否在提交是验证
                onfocusout: false,// 是否在获取焦点时验证
                onkeyup: false,// 是否在敲击键盘时验证
                rules: {
                    username: {
                        required: true,
                        minlength: 5,
                        mobileOrEmail: true
                    },
                    password: {
                        required: true,
                        rangelength: [6, 20]
                    },
                    veriCode: {
                        required: true,
                        minlength: 4,
                        remote: {
                            url: '/api/oauthUsers/checkVeriCode',
                            type: 'post',
                            async: false,//必须加非异步，否则即使校验失败也会有提交的风险
                            dataType: 'json',
                            /*data: {
                                username: function(){
                                    return $('#username').val()
                                }
                            },*/
                        }
                    }
                },
                messages: {
                    veriCode: {
                        remote: "[[#{invalidVeriCode}]]"
                    }
                },
                errorPlacement: function (error, element) {
                    error.appendTo(element.parent());
                },
                errorElement: "span",
                //单条校验失败，后会调用此方法，在此方法中，编写错误消息如何显示 及  校验失败回调方法
                showErrors: function (errorMap, errorList) {
                    let reload = false;
                    for (let obj in errorMap) {
                        reload = true;
                    }
                    if (reload) {
                        reloadCodeImage();
                    }
                    // 此处注意，一定要调用默认方法，这样保证提示消息的默认效果
                    this.defaultShowErrors();
                }
            });
        }

        $(validForm());

        $('#localeSelect').change(function () {
            $.cookie("locale", $(this).val());
            window.location.href="login?locale=" + $(this).val();
        });
        if ($.cookie("locale")) {
            $('#localeSelect').val($.cookie("locale"));
        }
    });
</script>
</body>
</html>