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 = '
' +
'
群成员列表
' +
'
';
$.each(list, function (index, user) {
groupUserContainer += "
" +
"
" + user.userName + " " +
"
";
})
groupUserContainer += '
' +
'
';
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 += "";
}
var selectUserTop = fromH5 ? "50px" : "0px";
var createGroupContainer = '' +
'
' +
'
至少选择2个用户创建群聊
' + friendList +
'
' +
'
' +
'
创建群聊' +
' ' +
'
' +
'
' +
'
' +
' 取消 ' +
' 创建 ' +
'
' +
'
' +
'
';
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 =
"" +
"
" +
"
";
$("#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 = "" +
"
搜索好友/机器人/公众号 " +
"手机号检索
" +
"
" +
"
" +
'检索结果: '+
"
" +
"
";
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("未查询到账号("+searchMobile+" )用户!")
} else {
var applyText = "申请加好友";
if (user.roleCode == 5) {
applyText = "添加机器人";
} else if (user.roleCode == 6) {
applyText = "订阅公众号";
}
$("#search-result").append("\n" +
"
\n" +
"
"+user.userName+"
\n" +
"
"+user.mobile+"
\n" +
"
"+applyText+" \n" +
"
")
}
} 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("暂无申请
");
return;
}
$.each(list, function (index, apply) {
var applyItem = "" +
"
" +
"
"+apply.applyUser.userName+" " +
"
同意 " +
"
拒绝 " +
"
";
$(".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("还没有任何好友
");
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 = "" +
"
" +
"
"+user.userName+" " +
"
";
$(".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 = ""+group.groupName +" ";
$("#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(/\n/g,'');
str = str.replace(/\[em(\d+)\]/g, ' ');
return str;
}
function codeContentEnCode(str) {
if (str == null || str == '') {return str;}
str = str.replaceAll(/\r\n/g," ")
str = str.replaceAll(/\n/g," ");
str = str.replaceAll(/\'/g,"'");
str = str.replaceAll(/\"/g,""");
str = str.replace(/&/g,"&");
str = str.replace(//g,">");
return str;
}
function messContentEnCode(str) {
if (str == null || str == '') {return str;}
str = str.replaceAll(/\r\n/g," ")
str = str.replaceAll(/\n/g," ");
str = str.replace(/&/g,"&");
str = str.replace(//g,">");
str = str.replaceAll("<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); // 处理上传错误
});
}