<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <base th:href="${#request.getContextPath() + '/'}">
    <meta charset="UTF-8">
    <title>聊天测试</title>
    <style>
        .websocket-line {padding: 5px 0;}
        .websocket-input {width: 234px; height: 23px; border: 1px solid silver; padding: 0 5px;}
        .websocket-container {width: 295px;}
        .websocket-history-box {height: 400px; border: 1px solid silver; overflow: auto;}
        .websocket-box {padding: 5px 0; text-align: right;}
        .message {display: inline-block; max-width: 195px; font-size: 13px; margin: 10px; padding: 5px; border-radius: 5px;word-wrap: break-word; word-break: normal;}
        .receive-msg-box {}
        .receive-msg {background-color: #04b304; color: #FFFFFF;}
        .send-msg-box {text-align: right;}
        .send-msg {text-align: left; background-color: #c5c5c5; color: #000000; margin: 10px 10px 10px 0;}
        .send-status {width: 20px; height: 20px; border-radius: 10px; background-color: red; display: inline-block;text-align: center; color: #FFF; vertical-align: middle;}
    </style>
</head>

<body>
    <div class="websocket-container">
        <div class="websocket-line">
            <select id="scheme" style="width: 70px; height: 26px; font-size: 18px;">
                <option value="ws://" selected>ws://</option>
                <option value="wss://">wss://</option>
            </select>
            <span id="webSocketUrl" th:text="${webSocketUrl}"></span>
            <input id="currentUserId" class="websocket-input" type="hidden" th:value="${currentUserId}"/>
        </div>
        <div class="websocket-line">
            接收用户ID <input id="toUserId" class="websocket-input" type="text" style="width: 196px;" placeholder="输入接收用户ID"/>
        </div>
        <div class="websocket-line">
            <input id="clientName" class="websocket-input" type="text" placeholder="请输入客户端名称"/>
            <button id="loginBtn" onclick="login()">登录</button>
            <button id="closeBtn" style="display: none;" onclick="closeWebSocket()">关闭</button>
        </div>
        <div class="websocket-line" style="font-size: 12px;">
            状态：<span id="loginStatus">未登录</span>
        </div>
        <div id="websocketHistoryBox" class="websocket-history-box">
            <!--
            <div class="receive-msg-box">
                <div class="message receive-msg">收到</div>
            </div>
            <div class="send-msg-box">
                <span class="send-status" title="用户不存在">!</span> <div class="message send-msg">发送</div>
            </div>
            -->
        </div>
        <div id="sendBox" class="websocket-box" style="display: none;">
            <input type="text" id="message" class="websocket-input" placeholder="请输入发送内容"/>
            <button id="login" onclick="send()">发送</button>
        </div>
    </div>

    <script type="text/javascript" src="assets/js/jquery-3.5.1.min.js"></script>
    <script type="text/javascript" src="assets/js/restajax.js"></script>
    <script type="text/javascript">
        var websocket;

        function register(sessionId) {
            var registBody = {
                id: new Date().getTime(),
                type: 1000,
                from: $('#currentUserId').val(),
                to: $('#currentUserId').val(),
                body: {
                    sessionId: sessionId
                }
            }
            websocket.send(JSON.stringify(registBody));
        }

        function initWebSocket(sessionId) {
            if ('WebSocket' in window) {
                websocket = new WebSocket($('#scheme').val() + $('#webSocketUrl').html());
                console.log("WebSocket连接成功")
            } else {
                alert('浏览器不支持WebSocket');
                return;
            }
            //连接发生错误的回调方法
            websocket.onerror = function () {
                console.log('error')
            };
            //连接成功建立的回调方法
            websocket.onopen = function (event) {
                console.log('open', event);
                // 打开连接，注册WebSocket
                register(sessionId);
            }
            //接收到消息的回调方法
            websocket.onmessage = function (event) {
                var data = JSON.parse(event.data);
                if(data.type === 1000) {
                    // 注册
                    var body = JSON.parse(data.body);
                    if(body.code === 200) {
                        $('#loginStatus').html('已连接');
                    } else {
                        $('#loginStatus').html(body.msg);
                    }
                } else if(data.type === 2001) {
                    // 文本消息
                    var body = data.body;
                    $('#websocketHistoryBox').append('<div class="receive-msg-box"><div class="message receive-msg">'+ body +'</div></div>');
                    autoScrollBottom();
                } else if(data.type === 9001) {
                    // 发送状态
                    var body = JSON.parse(data.body);
                    if(body.code != 200) {
                        $('#'+ data.id).before('<span class="send-status" title="'+ body.msg +'">!</span> ')
                    }
                } else if(data.type === 9101) {
                    // 接收状态
                    var body = JSON.parse(data.body);
                    if(body.code != 200) {
                        $('#'+ data.id).before('<span class="send-status" title="'+ body.msg +'">!</span> ')
                    }
                }
            }
            //连接关闭的回调方法
            websocket.onclose = function () {
                console.log('close')
            }
            //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
            window.onbeforeunload = function () {
                websocket.close();
            }
        }

        function login() {
            if(!$('#toUserId').val()) {
                alert('请输入接收用户ID');
                return;
            }
            if(!$('#clientName').val()) {
                alert('请输入客户端名称')
                return;
            }
            restAjax.get(restAjax.path('api/websocket/client/login/{clientName}', [$('#clientName').val()]), {}, null, function(code, data) {
                var sessionId = data.data
                $('#loginBtn').hide();
                $('#closeBtn').show();
                $('#clientName').attr('disabled', 'disabled');
                $('#toUserId').attr('disabled', 'disabled');
                $('#sendBox').show();
                initWebSocket(sessionId);
            }, function(code, data) {
                alert(data.msg);
            })
        }

        function send() {
            if(!websocket) {
                alert('请开启WebSocket');
                return;
            }
            if(!$('#message').val()) {
                alert('请输入内容');
                return;
            }
            var sendId = new Date().getTime();
            var sendBody = {
                id: sendId,
                type: 2001,
                from: $('#currentUserId').val(),
                to: $('#toUserId').val(),
                body: $('#message').val()
            }
            websocket.send(JSON.stringify(sendBody));
            $('#websocketHistoryBox').append('<div class="send-msg-box"><div id="'+ sendId +'" class="message send-msg">'+ $('#message').val() +'</div></div>');
            $('#message').val('');
            autoScrollBottom();
            //
        }

        function closeWebSocket() {
            websocket.close();
            $('#loginBtn').show();
            $('#closeBtn').hide();
            $('#clientName').removeAttr('disabled');
            $('#toUserId').removeAttr('disabled');
            $('#sendBox').hide();
        }

        function autoScrollBottom() {
            var websocketHistoryBox = document.getElementById('websocketHistoryBox');
            websocketHistoryBox.scrollTop = websocketHistoryBox.scrollHeight;
        }
    </script>

</body>

</html>