<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">

    <title>webchat聊天</title>

    <link rel="stylesheet" href="/css/common/common.css">
    <link rel="stylesheet" href="/css/client/chat.h5.css">
    <link href="/ref/layui-v2.6.8/layui/css/layui.css" rel="stylesheet" type="text/css" />

    <script src="/ref/jquery/jquery-3.4.1.js" type="text/javascript"></script>
    <script src="/ref/layui-v2.6.8/layui/layui.js" type="text/javascript"></script>
    <script src="/ref/jquery/jquery.qqFace.js" type="text/javascript"></script>

    <script>
        if(!(/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent))) {
            window.location.href = "/chat";
        }
    </script>
</head>
<body>
<center>
    <!-- 聊天列表 -->
    <div class="chat-user-list-container chat-main-list-container" style="display: block;">
        <div class="chat-main-list-title">
            <button class="add-btn" id="add-btn">
                <svg t="1730112209518" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="10200" width="32" height="32"><path d="M533.333333 288a10.666667 10.666667 0 0 0-10.666666-10.666667h-42.666667a10.666667 10.666667 0 0 0-10.666667 10.666667v192h-192a10.666667 10.666667 0 0 0-10.666666 10.666667v42.666666a10.666667 10.666667 0 0 0 10.666666 10.666667h192v192a10.666667 10.666667 0 0 0 10.666667 10.666667h42.666667a10.666667 10.666667 0 0 0 10.666666-10.666667v-192h192a10.666667 10.666667 0 0 0 10.666667-10.666667v-42.666666a10.666667 10.666667 0 0 0-10.666667-10.666667h-192v-192z" fill="#2c2c2c" p-id="10201"></path></svg>
            </button>
        </div>
        <div class="chat-user-list" id="chat-group-banner" style="display: none; min-height: 50px; height: auto; margin-top: 20px; width: 95%">
            <div class="list-title" style="text-indent: -10px">置顶群聊</div>
            <div id="chat-group-list" style="padding: 10px; min-height: 50px; height: auto"></div>
            <div style="clear: both"></div>
        </div>
        <div class="list-title">聊天列表</div>
        <div class="chat-user-list" id="chat-user-list">

        </div>
        <div style="clear: both"></div>
    </div>

    <!-- 音视频通话邀请 -->
    <div class="video-chat-offer-card" style="display: none" id="video-chat-offer-card">
        <img src="https://coderutil.oss-cn-beijing.aliyuncs.com/bbs-image/file_011df09866634d90962c42ba31802f54.png" class="video-chat-offer-icon"> <span style="color: #0755e3" id="offerSenderName">-</span>发来了音视频通话邀请
        <div style="width: 100%; height: 30px; margin-top: 10px; text-align: right">
            <button id="rejectOffer">拒绝</button>
            <button id="acceptOffer">接通</button>
        </div>
    </div>
    <div id="h5-footer"></div>
</center>
</body>
<script src="/js/client/auth.js" type="text/javascript"></script>
<script src="/js/client/chat.js" type="text/javascript"></script>
<script>
    $("#h5-footer").load("/h5/footer");
</script>
<script>
    var me;
    var userId;
    var webSocket;
    // 心跳检测的间隔时间（毫秒）
    const heartbeatInterval = 30000;
    // 重连尝试的时间间隔（毫秒）
    var reconnectInterval = 5000;
    // 最大重连尝试间隔时间
    var maxReconnectInterval = 300000; // 5分钟
    var heartbeatTimer;
    var reconnectTimer;
    var selectCardUserId;
    var selectCardUser = null;
    var robotLastMessId = "";
    var videoChatting = false;
    loadCurrUserInfo();
    function loadCurrUserInfo() {
        $.ajax({
            url:"/api/user/getCurrentUserInfo",
            type:"get",
            success:function (data) {
                data = eval(data);
                if (data.success){
                    $("#login-user").show();
                    $("#login-menu").hide();
                    data = data.data;
                    me = data;
                    userId = data.userId;
                    $("#curr-user-photo").attr("src", data.photo+"?x-oss-process=image/resize,m_fill,w_40,h_40");
                    if (data.roleCode == 2) {
                        $("#admin-icon").show();
                    }
                    initWebSocket();
                } else {
                    location.href="/auth";
                }
            },error:function () {
                location.href="/auth";
            }
        })
    }

    function initWebSocket() {
        if ("WebSocket" in window) {
            webSocket = new WebSocket("ws://"+wsHost+":"+wsPort+"/ws/chat/" + userId);
            webSocket.onopen = function () {
                console.log("已经连通了websocket");
            };
            // 发送心跳函数
            function sendHeartbeat() {
                if (webSocket.readyState === WebSocket.OPEN) {
                    webSocket.send('heartbeat');
                }
            }
            // 重连函数
            function reconnect() {
                reconnectTimer = setTimeout(function () {
                    webSocket = null;
                    initWebSocket();
                    reconnectInterval = Math.min(maxReconnectInterval, reconnectInterval * 2);
                }, reconnectInterval);
            }
            // 连接打开时
            webSocket.onopen = function () {
                console.log('WebSocket connection established');
                // 连接成功后启动心跳检测
                heartbeatTimer = setInterval(sendHeartbeat, heartbeatInterval);
                reconnectInterval = 5000; // 重置重连间隔时间
            };
            //接收后台服务端的消息
            webSocket.onmessage = function (evt) {
                if (evt.data == "ok") {
                    // 跳过心跳检测
                    console.log("心跳检测成功！");
                    return;
                }
                var mess = JSON.parse(evt.data);

                if (mess.videoOffer) {
                    // 来自用户音视频请求
                    showVideoOfferNotify(mess.senderId, mess.receiverId, mess.senderName);
                    return;
                } else if (mess.rejectVideoOffer) {
                    hideVideoOfferNotify();
                    return;
                }
                showReceiverMsg(mess);
                setTimeout('loadChat(false)', 1000);
            };
            //连接关闭的回调事件
            webSocket.onclose = function () {
                console.log("连接已关闭...");
                clearInterval(heartbeatTimer);
                clearTimeout(reconnectTimer);
                reconnect(); // 调用重连函数
            };
        } else {
            // 浏览器不支持 WebSocket
            alert("您的浏览器不支持 WebSocket!");
        }
    }

    function sendChatWebSocket(message) {
        webSocket.send(message);
    }

    // 获取URL请求参数
    function getUserParamByName(key) {
        var url = window.location.search;
        var reg = new RegExp("(^|&)" + key + "=([^&]*)(&|$)");
        var result = url.substr(1).match(reg);
        return result ? decodeURIComponent(result[2]) : "";
    }

    function showReceiverMsg(chat) {
        var message;
        var groupMessage = chat.groupMessage;
        var sender = groupMessage ? chat.proxySender : chat.sender;
        var isMe = sender.userId == me.userId;
        if (selectCardUserId != chat.sender.userId) {
            // 不是当前点开的窗口，不显示消息
            return;
        }
        if (isMe) {
            // 当前用户
            message ="                <p class=\"chat-mess-time\">"+formatMsgTime(chat.time)+"</p>\n" +
                "                <div class=\"chat-mess-container chat-mess-me\">\n" +
                "                    <div class=\"chat-mess-avatar\">\n" +
                "                        <a href='/coder?userid="+sender.userId+"' target='_blank'><img src=\""+sender.photo+"?x-oss-process=image/resize,m_fill,w_50,h_50\"></a>\n" +
                "                    </div>\n" +
                "          <div class=\"chat-mess-triangle-right\"></div>\n" +
                "                    <div class=\"chat-mess-box\">"+messContentEnCode(chat.message)+"</div>\n" +
                "                </div>\n";
        } else {
            message =" <p class=\"chat-mess-time\">"+formatMsgTime(chat.time)+"</p>\n" +
                "                <div class=\"chat-mess-container chat-mess-user\">\n" +
                "                    <div class=\"chat-mess-avatar\">\n" +
                "                        <a href='/coder?userid="+sender.userId+"' target='_blank'><img src=\""+sender.photo+"?x-oss-process=image/resize,m_fill,w_50,h_50\"></a>\n" +
                "                    </div>\n";
            var topTip = 10;
            var topMessage = 0;
            if (groupMessage) {
                topTip = 20;
                topMessage = 15;
                message += "<span style='color: #9e9e9e;font-size: 10px;position: absolute;top: 0px;left: 65px'>"+sender.userName+"</span>";
            }
            message += "                    <div class=\"chat-mess-triangle-left\" style='top: "+topTip+"px'></div>\n" +
                "                    <div class=\"chat-mess-box\" style='top: "+topMessage+"px'>"+messContentEnCode(chat.message)+"</div>\n" +
                "                </div>\n";
        }
        $("#chat-message-container").append(message);
        // 刷新消息区滚动条
        refreshChatMessContainerScrollBar2Bottom();
    }

    // 获取好友id
    var chatId = getUserParamByName("chatid");
    var chatUserListUrl;
    if (chatId != '') {
        chatUserListUrl = "/api/chat/mess/users?selectUser=" + chatId;
    } else {
        chatUserListUrl = "/api/chat/mess/users";
    }
    loadChat(true);
    function loadChat(selectFirstUser) {
        $("#chat-user-list").empty();
        $.ajax({
            url: chatUserListUrl,
            type:"get",
            success:function (data) {
                data = eval(data);
                if (data.success){
                    if (data.data.length == 0) {
                        $("#chat-user-list").append("<p style='line-height: 300px; color: gray'>暂无聊天记录</p>");
                        return;
                    }
                    $.each(data.data, function (index, chatUser) {
                        var user = chatUser.user;
                        var unReadTag = chatUser.unReadMess ?
                            "<button class='unReadMessTag' id='unreadTag-"+user.userId+"'></button>" : "";
                        var chatUserCard = "<div class=\"chat-user-card\" id='card-"+user.userId+"'>\n" +
                            "<a onclick=\"deleteChatCard('"+user.userId+"')\" class='deleteChatCardIcon'><?xml version=\"1.0\" encoding=\"UTF-8\"?><svg width=\"15\" height=\"15\" viewBox=\"0 0 48 48\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M8 8L40 40\" stroke=\"#424242\" stroke-width=\"4\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/><path d=\"M8 40L40 8\" stroke=\"#424242\" stroke-width=\"4\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/></svg></a>"+
                            "<a onclick=\"selectChatUser('"+user.userId+"', '"+user.userName+"', '无签名', true)\">";
                        var groupIcon = "";
                        if (user.roleCode == 4) {
                            // 群管理
                            groupIcon = "<span class='group-icon'>群</span>";
                            chatUserCard += "<button class=\"chat-user-card-photo line2ppp\" style='border: 0; color: white; font-size: 10px; background-color: "+colors[user.id%5]+"'>"+user.userName+"</button>";
                        } else if (user.roleCode == 5) {
                            // 群管理
                            groupIcon = "<span class='robot-icon'>机器人</span>";
                            chatUserCard += "<button class=\"chat-user-card-photo line2ppp\" style='border: 0; color: white; font-size: 10px; background-color: "+colors[user.id%5]+"'>"+user.userName+"</button>";
                        } else {
                            chatUserCard += "<img src=\""+user.photo+"\" class=\"chat-user-card-photo\">\n";
                        }
                        chatUserCard += "<p class=\"chat-user-card-username\">"+groupIcon+user.userName+unReadTag+"</p>\n" +
                            "                    <p class=\"chat-user-card-last-msg line1ppp\">"+codeContentEnCode(chatUser.lastMessage)+"</p>\n" +
                            "                    <span class=\"chat-user-card-last-time\">"+formatMsgTime(chatUser.time)+"</span>\n" +
                            "</a></div>";
                        $("#chat-user-list").append(chatUserCard);
                    })
                    $(".chat-user-card").css("background-color", "transparent");
                    $("#card-"+selectCardUserId).css("background-color", "white");
                }
                $(".chat-user-card").hover(function(){
                    $(this).children(".deleteChatCardIcon").show();
                },function(){
                    $(this).children(".deleteChatCardIcon").hide();
                });
            }
        })
    }
    function selectChatUser(userId, userName, signature, focusUser) {
        selectCardUserId = userId;
        location.href = "/h5/chat?chatid="+userId;
    }

    function refreshSelectUserInfo(selectUserId) {
        selectCardUser = null;
        $.ajax({
            url: "/api/user/getUserInfo?userId=" + selectUserId,
            type:"get",
            success:function (data) {
                data = eval(data);
                if (data.success){
                    selectCardUser = data.data;
                    if (selectCardUser.roleCode == 5) {
                        chatChannel();
                    }
                }
            }
        })
    }

    function deleteChatCard(cardUserId) {
        $("#card-"+cardUserId).remove();
        if (cardUserId == selectCardUserId) {
            $("#chat-user-header").hide();
        }
    }
</script>

<!-- 视频通话 -->
<script>

    function acceptVideoChat(userId, targetUserId) {
        if (videoChatting) {
            // 音视频中
            return;
        }
        videoChatting = true;
        // 视频通话呼叫
        layer.open({
            type: 2,
            title: '视频通话',
            shadeClose: true,
            resize: false,
            shade: 0.6,
            maxmin: false, //开启最大化最小化按钮
            area: ['450px', '700px'],
            content: '/client/video-chat?userId='+userId+'&targetUserId='+targetUserId
        });
    }

    /**
     * 显示音视频邀请通知
     *
     * @param senderId
     * @param receiverId
     */
    function showVideoOfferNotify(senderId, receiverId, senderName) {
        if (videoChatting) {
            // 音视频中不提醒，目前提醒的话会有BUG，可能导致死循环，内存溢出问题
            return;
        }
        $("#offerSenderName").text(senderName);
        $("#video-chat-offer-card").show();

        $("#acceptOffer").on("click", function () {
            $("#video-chat-offer-card").hide();
            acceptVideoChat(receiverId, senderId);
        })

        $("#rejectOffer").on("click", function () {
            $("#video-chat-offer-card").hide();
            var data = "{\"receiverId\":\""+senderId+"\", \"senderId\":\""+receiverId+"\", \"rejectVideoOffer\": true}";
            webSocket.send(data);
        })
    }

    function hideVideoOfferNotify() {
        videoChatting = false;
        layer.closeAll();
        layer.msg("对方拒绝了你的通话邀请！");
    }

    $("#mess-video-menu").on("click", function () {
        if (selectCardUser.roleCode != 1 && selectCardUser.roleCode != 2) {
            layer.msg("不支持音视频");
            return;
        }
        videoChatting = false;
        acceptVideoChat(me.userId, selectCardUserId);
    })
</script>
</html>