var wsHost = document.domain;
// 如果你修改了application-dev.yml 中的端口号，这里的ws端口也要一块修改
var wsPort = 8101;

// 是否来自h5的请求
var fromH5 = location.href.indexOf("/h5") > 0;

var chatting = false;
var systemMessage = '';
var chatChannelApi = "/api/robot/chat/stream?biz=ROBOT_CHAT";
function chatChannel() {
    systemMessage = '';
    chatting = false;
    var eventSource = new EventSource(chatChannelApi);
    eventSource.onopen = function(e){
        console.log("Connection Opened");
    };
    eventSource.onmessage = function(e){
        chatting = true;
        var message = e.data;
        systemMessage += message;
        if (e.data == ' ') {
            systemMessage = systemMessage + ' ';
        }
        if (e.data == 'finished') {
            console.log("本轮对话结束！");
            chatting = false;
            saveRobotMessage(systemMessage);
            systemMessage = '';
        } else {
            $("#"+robotLastMessId).html(marked.parse(systemMessage));
            refreshChatMessContainerScrollBar2Bottom();
        }
    };
    eventSource.onerror = function(e){
        console.log("Error");
    };
}

/**
 * 保存机器人聊天记录
 * @param robotMessage
 */
function saveRobotMessage() {
    // 保存
    $.ajax({
        url:"/api/chat/mess/send",
        type: "post",
        dataType: "json",
        contentType: "application/json;charset=utf-8",
        data: JSON.stringify({
            receiverId: me.userId,
            senderId: selectCardUserId,
            type: 1,
            message: $("#"+robotLastMessId).html(),
        }),
        success:function (data) {
            // console.log(data);
        },error:function () {}
    })
}

var friendUsers = [];
loadFriendList('');

<!-- 创建群聊、加人加群 -->
$(function () {
    layui.use(['dropdown', 'util', 'layer', 'table'], function(){
        var dropdown = layui.dropdown;
        //用户
        dropdown.render({
            elem: '#add-btn'
            , data: [{
                title: '创建群聊'
                , id: 1
            }, {
                title: '加人/订阅'
                , id: 2
            }]
            , click: function (obj) {
                if(obj.id == 1) {
                    createGroup();
                } else if (obj.id == 2) {
                    searchUserOrGroup();
                }
            }
        });

        dropdown.render({
            elem: '#group-ctrl'
            , data: [{
                title: '查看群成员'
                , id: 1
            }]
            , click: function (obj) {
                if(obj.id == 1) {
                    viewGroupUsers();
                }
            }
        });
    })
})

function viewGroupUsers() {
    $.ajax({
        url:"/api/user/listGroupUsers/"+selectCardUserId,
        type:"get",
        success:function (data) {
            data = eval(data);
            if (data.success){
                var list = data.data;
                var groupUserContainer = '<div style=\"width: 200px; height: 300px; padding: 20px 40px; background-color: white; border: 1px solid #d6d6d6\">' +
                    '<div style="line-height: 20px;">群成员列表</div>' +
                    '<div>';
                $.each(list, function (index, user) {
                    groupUserContainer += "<div style='position: relative; width: 100%; height: 45px; text-align: left; line-height: 45px'>" +
                        " <img src='"+user.photo+"' style='position: relative; width: 30px; border-radius: 3px; margin: 0px 10px'><span style='font-size: 15px'>" + user.userName + "</span>" +
                        "</div>";
                })
                groupUserContainer += '</div>' +
                    '</div>';
                layer.open({
                    type: 1,
                    title: false,
                    closeBtn: 0,
                    shadeClose: true,
                    skin: 'yourclass',
                    content: groupUserContainer
                });
            }
        }
    })

}


function createGroup() {
    var selectedUserIdArr = [];
    var friendList = "";
    for (var i = 0; i < friendUsers.length; i++) {
        var user = friendUsers[i];
        if (user.roleCode > 3) {
            continue;
        }
        friendList += "<div style='position: relative; width: 80%; height: 45px; text-align: left; line-height: 45px; padding-left: 10%'>" +
                      " <label><input type='checkbox' id='"+user.userId+"' name='checkbox-user' data-photo='"+user.photo+"' value='"+user.userId+"'> <img src='"+user.photo+"' style='position: relative; width: 30px; border-radius: 3px; margin: 0px 10px'><span style='font-size: 15px'>" + user.userName + "</span></label>" +
                      "</div>";
    }
    var selectUserTop = fromH5 ? "50px" : "0px";
    var createGroupContainer = '<div style=\"width: 650px; overflow: hidden; height: 450px; background-color: white; border: 1px solid #d6d6d6\">' +
        '<div style="position: absolute; overflow-y: scroll;  left: 0px; top: 0px; width: 49%; height: 100%; background-color: #f7f7f7; border-right: 1px solid #d6d6d6">' +
        '   <div style="position: relative;  text-indent: 20px; line-height: 50px; font-size: 14px; text-align: left; height: 50px; color: #757373">至少选择2个用户创建群聊</div>' + friendList +
        '</div>' +
        '<div style="position: absolute; right: 0px; top: 0px; width: 49%; height: 100%">' +
        '   <div style="position: relative; line-height: 50px; font-size: 16px; text-align: left; height: 50px; color: black">创建群聊' +
        '       <input placeholder="设置群聊名称"  id="createGroupName" style="position: relative; margin-right: 20px; margin-top: 10px; float: right; padding: 0px 10px; border: 1px solid #b5b5b5; border-radius: 3px; width: 150px; line-height: 28px;">' +
        '  </div>' +
        '   <div style="position: relative; height: 300px; top: '+selectUserTop+'" id="selected-user-container"></div>' +
        '   <div style="position: absolute; left: 0px; width: 100%; height: 65px; bottom: 0px; text-align: center;">' +
        '       <button id = "cancelCreateGroup" style="position: relative; padding: 7px 25px; border-radius: 3px; border: none; background-color: #eaeaea; color: black;">取消</button>' +
        '       <button id = "createGroup" style="position: relative; padding: 7px 25px; border-radius: 3px; border: none; background-color: #16b516; color: white;">创建</button>' +
        '  </div>' +
        '</div>' +
        '</div>';
    layer.open({
        type: 1,
        title: false,
        closeBtn: 0,
        shadeClose: true,
        skin: 'yourclass',
        content: createGroupContainer
    });
    // 获取所有的checkbox元素
    var checkboxes = document.querySelectorAll('input[type="checkbox"]');
    // 为每个checkbox添加事件监听器
    var marginStyle = fromH5 ? " margin: 10px 10px 10px 0px" : " margin: 20px 20px 20px 0px";
    checkboxes.forEach(function(checkbox) {
        checkbox.addEventListener('change', function() {
            if (this.checked) {
                var selectedId = this.id;
                var selectedPhoto = this.getAttribute("data-photo");
                var selectedUserCard =
                    "<div id='selected-user-"+selectedId+"'>" +
                    "<img src='"+selectedPhoto+"' style='width: 50px; height: 50px; border-radius: 5px; float: left; "+marginStyle+"'>" +
                    "</div>";
                $("#selected-user-container").append(selectedUserCard);
                selectedUserIdArr.push(selectedId);
            } else {
                var cancelId = this.id;
                $("#selected-user-"+cancelId).remove();
                let indexToRemove = selectedUserIdArr.findIndex(item => item === cancelId);
                if (indexToRemove > -1) {
                    selectedUserIdArr.splice(indexToRemove, 1);
                }
            }
        });
    });

    /**
     * 取消创建群聊
     */
    $("#cancelCreateGroup").on('click', function () {
        layer.closeAll();
    })

    /**
     * 创建群聊
     */
    $("#createGroup").on('click', function () {
        if (selectedUserIdArr.length < 2) {
            layer.msg("创建群组至少选择两个好友");
            return;
        }
        var createGroupName = $("#createGroupName").val();
        if (createGroupName == '' || createGroupName.trim() == '') {
            layer.msg("未设置群聊名称");
            return;
        }
        if (createGroupName.length > 20) {
            layer.msg("群聊名称不能超过20个字");
            return;
        }
        $.ajax({
            url:"/api/user/createChatGroup",
            type: "post",
            dataType: "json",
            contentType: "application/json;charset=utf-8",
            data: JSON.stringify({
                userIds: selectedUserIdArr,
                groupName: createGroupName
            }),
            success:function (data) {
                data = eval(data);
                if (data.success){
                    layer.closeAll();
                    layer.msg("创建成功");
                    // 重新拉取群聊列表
                    loadGroupList();
                } else {
                    layer.msg(data.msg);
                }
            },error:function () {
                layer.msg("网络异常");
            }
        })
    })
}

function searchUserOrGroup() {
    var padding = fromH5 != null && fromH5 ? "padding: 10px 10px;" : "padding: 10px 50px;";
    var width = fromH5 != null && fromH5 ? "350px" : "500px";
    var searchUser = "<div style='width: "+width+"; height: 300px; background-color: white; border-radius: 5px; "+padding+"'>" +
        "<p style='text-align: left; line-height: 50px; font-weight: 700; font-size: 16px; color: #424242'>搜索好友/机器人/公众号 " +
        "<span style='font-size: 13px; font-weight: 400; float: right; color: gray'>手机号检索</span></p>" +
        "<input id='search-mobile' style='height: 45px; margin-top: 20px; border: 1px solid #c1d5f3; border-radius: 3px; width: 100%; text-indent: 10px;' placeholder='输入要检索的账号, 回车搜索'>" +
        "<div style='width: 100%; margin-top: 20px; font-size: 14px; font-weight: 400' id='search-result'>" +
        '检索结果: '+
        "</div>" +
        "</div>";
    layer.open({
        type: 1,
        title: false,
        closeBtn: 0,
        shadeClose: true,
        skin: 'yourclass',
        content: searchUser
    });
    // 监听搜索的回车事件
    $("#search-mobile").keydown(function(event) {
        if (event.keyCode == 13) {
            var searchMobile = $("#search-mobile").val();
            if (searchMobile == '' || searchMobile.toString().trim() == '') {
                layer.msg("输入空内容");
                return;
            }
            $("#search-result").empty();
            $.ajax({
                url:"/api/user/search/"+searchMobile,
                type:"get",
                success:function (data) {
                    data = eval(data);
                    if (data.success){
                        var user = data.data;
                        if(user == null) {
                            $("#search-result").append("未查询到账号(<span style='color: orangered'>"+searchMobile+"</span>)用户！")
                        } else {
                            var applyText = "申请加好友";
                            if (user.roleCode == 5) {
                                applyText = "添加机器人";
                            } else if (user.roleCode == 6) {
                                applyText = "订阅公众号";
                            }
                            $("#search-result").append("<div class=\"search-user-card\">\n" +
                                "        <img src=\""+user.photo+"?x-oss-process=image/resize,m_fill,w_60,h_60\" class=\"search-user-photo\">\n" +
                                "        <p class=\"search-username\">"+user.userName+"</p>\n" +
                                "        <p class=\"search-mobile\">"+user.mobile+"</p>\n" +
                                "        <button class=\"applyAddUser\" onclick='applyAddUserFriend(\""+user.userId+"\", \""+user.roleCode+"\")'>"+applyText+"</button>\n" +
                                "    </div>")
                        }
                    } else {
                        layer.msg("服务异常");
                    }
                },error:function () {
                    layer.msg("网络异常");
                }
            })
        }
    })
}

function applyAddUserFriend(friendId, friendRoleCode) {
    $.ajax({
        url:"/api/friend/applyAdd/"+friendId,
        type:"post",
        success:function (data) {
            data = eval(data);
            if (data.success){
                var toast = "申请已发出";
                if (friendRoleCode == 5) {
                    toast = "机器人已添加";
                } else if (friendRoleCode == 6) {
                    toast = "公众号订阅成功";
                }
                layer.msg(toast);
            } else {
                layer.msg(data.msg);
            }
        },error:function () {
            layer.msg("网络异常");
        }
    })
}

countNewMessage();
function countNewMessage() {
    $.ajax({
        url:"/api/friend/countUnHandleApply",
        type:"get",
        success:function (data) {
            data = eval(data);
            if (data.success){
                if (data.data > 0) {
                    $(".new-message-icon").show();
                }
            }
        }
    })
}


function loadUnHandleApplyList() {
    $(".apply-unhandle-list").empty();
    $.ajax({
        url:"/api/friend/listUnHandleApplyUsers",
        type:"get",
        success:function (data) {
            data = eval(data);
            if (data.success){
                var list = data.data;
                if (list.length == 0) {
                    $(".apply-unhandle-list").append("<p style='line-height: 400px; color: #666'>暂无申请</p>");
                    return;
                }
                $.each(list, function (index, apply) {
                    var applyItem = "<div class='apply-item' id='apply-item-"+apply.applyId+"'>" +
                        "<img class='applyUserPhoto' src=\""+apply.applyUser.photo+"\">" +
                        "<span class='applyUserName'>"+apply.applyUser.userName+"</span>" +
                        "<a onclick='applyPass(\""+apply.applyId+"\")' class='apply-pass'>同意</a>" +
                        "<a onclick='applyRefuse(\""+apply.applyId+"\")' class='apply-refuse'>拒绝</a>" +
                        "</div>";
                    $(".apply-unhandle-list").append(applyItem);
                })
            }
        }
    })
}

function loadFriendList(userName) {
    friendUsers = [];
    $(".friend-list").empty();
    $.ajax({
        url:"/api/friend/listFriendUsers?userName="+userName,
        type:"get",
        success:function (data) {
            data = eval(data);
            if (data.success){
                var list = data.data;
                if (list.length == 0) {
                    $(".friend-list").append("<p style='line-height: 400px; color: #666'>还没有任何好友</p>");
                    return;
                }
                $.each(list, function (index, apply) {
                    var user = apply.applyUser;
                    friendUsers.push(user);
                    var url = fromH5 ? "/h5/chat?chatid="+user.userId : "/chat?chatid="+user.userId;
                    var applyItem = "<a href='"+url+"'><div class='apply-item' id='apply-item-"+apply.applyId+"'>" +
                        "<img class='applyUserPhoto' src=\""+user.photo+"\">" +
                        "<span class='friendUserName'>"+user.userName+"</span>" +
                        "</div></a>";
                    $(".friend-list").append(applyItem);
                })
            }
        }
    })
}

var colors = ["#F84E4E", "#4263EB", "#1FB759", "#017D6F", "#FA6509"];

loadGroupList();
function loadGroupList() {
    $("#chat-group-list").empty()
    $("#chat-group-banner").hide();
    $.ajax({
        url:"/api/user/listGroups",
        type:"get",
        success:function (data) {
            data = eval(data);
            if (data.success){
                var list = data.data;
                if (list.length == 0) {
                    return;
                }
                var i = 0;
                $("#chat-group-banner").show();
                $.each(list, function (index, group) {
                    var bgColor = colors[group.id % 5];
                    var groupItem = "<a onclick=\"selectChatUser('"+group.groupId+"', '"+group.groupName+"', '群组', true)\"><button class='group-card line2ppp' style='background-color: "+bgColor+"'>"+group.groupName +"</button></a>";
                    $("#chat-group-list").append(groupItem);
                })
            }
        }
    })
}

function applyPass(id) {
    $.ajax({
        url:"/api/friend/applyPass/"+id,
        type:"post",
        success:function (data) {
            data = eval(data);
            if (data.success){
                layer.msg("通过");
                $(".new-message-icon").hide();
                $("#apply-item-"+id).fadeOut(500);
            } else {
                layer.msg("服务异常");
            }
        }
    })
}

function applyRefuse(id) {
    $.ajax({
        url:"/api/friend/applyRefuse/"+id,
        type:"post",
        success:function (data) {
            data = eval(data);
            if (data.success){
                layer.msg("已拒绝");
                $(".new-message-icon").hide();
                $("#apply-item-"+id).fadeOut(500);
            } else {
                layer.msg("服务异常");
            }
        }
    })
}

var hideChatMainListContainer = function () {
    $(".chat-main-list-container").hide();
}
var initCharMenuIconStatus = function () {
    $(".chat-menu-icon").removeClass("selected-icon");
}

$(".message-icon").on('click', function () {
    hideChatMainListContainer();
    initCharMenuIconStatus();
    $(".apply-list-container").show();
    $(".message-icon").addClass("selected-icon");

    loadUnHandleApplyList();
})

$(".friend-list-icon").on('click', function () {
    hideChatMainListContainer();
    initCharMenuIconStatus();
    $(".friend-list-container").show();
    $(".friend-list-icon").addClass("selected-icon");

    loadFriendList('');
})

$(".chat-icon").on('click', function () {
    hideChatMainListContainer();
    initCharMenuIconStatus();
    $(".chat-user-list-container").show();
    $(".chat-icon").addClass("selected-icon");

    loadFriendList('');
})

$("#search-username").keydown(function(event) {
    if (event.keyCode == 13) {
        loadFriendList($("#search-username").val());
    }
})

function formatMsgTime(timespan){
    var dateTime = new Date(timespan);
    var year = dateTime.getFullYear();
    var month = dateTime.getMonth() + 1;
    var day = dateTime.getDate();
    var hour = dateTime.getHours();
    var minute = dateTime.getMinutes();
    var nowDate = new Date();
    var now_new = new Date().getTime()
    var milliseconds = 0;
    var timeSpanStr;
    milliseconds = now_new - timespan;
    if (milliseconds <= 1000 * 60 * 1) {
        timeSpanStr = '刚刚';
    }
    else if (1000 * 60 * 1 < milliseconds && milliseconds <= 1000 * 60 * 60) {
        timeSpanStr = Math.round((milliseconds / (1000 * 60))) + '分钟前';
    }
    else if (1000 * 60 * 60 * 1 < milliseconds && milliseconds <= 1000 * 60 * 60 * 24) {
        timeSpanStr = Math.round(milliseconds / (1000 * 60 * 60)) + '小时前';
    }
    else if (1000 * 60 * 60 * 24 < milliseconds && milliseconds <= 1000 * 60 * 60 * 24 * 15) {
        timeSpanStr = Math.round(milliseconds / (1000 * 60 * 60 * 24)) + '天前';
    }
    else if (milliseconds > 1000 * 60 * 60 * 24 * 15 && year == nowDate.getFullYear()) {
        timeSpanStr = day + ' / ' + month + '月';
    } else {
        timeSpanStr = year + ' / ' + month + ' / ' + day;
    }
    return timeSpanStr;
};


//查看结果
function replace_em(str){
    str = str.replace(/\</g,'<');
    str = str.replace(/\>/g,'>');
    str = str.replace(/\n/g,'');
    str = str.replace(/\[em(\d+)\]/g, '<img src="/ref/jquery/face/$1.gif" border="0" />');
    return str;
}

function codeContentEnCode(str) {
    if (str == null || str == '') {return str;}
    str = str.replaceAll(/\r\n/g,"<br>")
    str = str.replaceAll(/\n/g,"<br>");
    str = str.replaceAll(/\'/g,"&#39;");
    str = str.replaceAll(/\"/g,"&quot;");
    str = str.replace(/&/g,"&amp;");
    str = str.replace(/</g,"&lt;");
    str = str.replace(/>/g,"&gt;");
    return str;
}

function messContentEnCode(str) {
    if (str == null || str == '') {return str;}
    str = str.replaceAll(/\r\n/g,"<br>")
    str = str.replaceAll(/\n/g,"<br>");
    str = str.replace(/&/g,"&amp;");
    str = str.replace(/</g,"&lt;");
    str = str.replace(/>/g,"&gt;");
    str = str.replaceAll("&lt;br&gt;","<br>")
    str = replace_em(str);
    return str;
}

// 获取上传按钮和文件输入框元素
const uploadButton = document.getElementById('mess-file-menu');
const fileInput = document.getElementById('fileInput');
// 为上传按钮添加点击事件监听器
uploadButton.addEventListener('click', function() {
    // 触发文件输入框的点击事件，以打开文件选择对话框
    fileInput.click();
});

// 为文件输入框添加变化事件监听器，以便在文件选择后上传
fileInput.addEventListener('change', function() {
    // 检查是否选择了文件
    if (this.files.length > 0) {
        const file = this.files[0]; // 获取选择的文件
        uploadFile(file); // 调用上传文件的函数
    }
});

// 上传文件的函数
function uploadFile(file) {
    const formData = new FormData();
    formData.append('file', file); // 将文件添加到FormData对象中
    fetch('/api/file/chat/upload', { // 发送POST请求到服务器的/upload端点
        method: 'POST',
        body: formData,
    })
        .then(response => response.json()) // 处理响应文本
        .then(data => {
            if (data.success) {
                var file = data.data;
                // 使用JSON.stringify将对象转换为JSON字符串，并确保转义
                var content = JSON.stringify({type: file.type, name: file.name, url: file.url});
                var data = JSON.stringify({
                    "receiverId": selectCardUserId,
                    "senderId": me.userId,
                    "message": content,
                    "type": 2
                });
                $("#chat-message-container").append(buildFileMess(JSON.parse(content), me.photo, "right"));
                refreshChatMessContainerScrollBar2Bottom();
                sendChatWebSocket(data);
                $.ajax({
                    url:"/api/chat/mess/send",
                    type: "post",
                    dataType: "json",
                    contentType: "application/json;charset=utf-8",
                    data: data,
                    success:function (data) {
                        data = eval(data);
                        if (!data.success){
                            layer.msg(data.msg);
                        } else {
                            if (selectCardUser.roleCode != 5) {
                                loadChat(false);
                            }
                        }
                    },error:function () {}
                })
            } else {
                layer.msg(data.msg);
            }
        })
        .catch(error => {
            console.error('上传失败:', error); // 处理上传错误
        });
}
