You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1854 lines
53 KiB

<template>
<view class="page chat-box" id="chatBox">
<nav-bar>{{ title }}</nav-bar>
<view class="chat-main-box" :style="{ height: chatMainHeight + 'px' }">
<view class="chat-message" @click="switchChatTabBox('none')">
<view v-if="showAutoQuestionTip" class="guess-question-box">
<!-- <view class="guess-title">猜你想问</view> -->
<view class="guess-list">
<view
class="guess-item"
v-for="(q, i) in commonQuestions"
:key="i"
@click="sendQuestionMessage(q)"
>
<text class="item-bullet">*</text>
<text class="item-text">{{ q }}</text>
</view>
</view>
</view>
<scroll-view
class="scroll-box"
scroll-y="true"
upper-threshold="200"
@scrolltoupper="onScrollToTop"
@scroll="onScroll"
:scroll-into-view="'chat-item-' + scrollMsgIdx"
:scroll-top="scrollTop"
>
<view v-if="chat" class="chat-wrap">
<view v-for="(msgInfo, idx) in chat.messages" :key="idx">
<chat-message-item
:ref="'message' + msgInfo.id"
v-if="idx >= showMinIdx"
:headImage="headImage(msgInfo)"
@call="onRtCall(msgInfo)"
:showName="showName(msgInfo)"
@resend="onResendMessage"
@recall="onRecallMessage"
@delete="onDeleteMessage"
@copy="onCopyMessage"
@longPressHead="onLongPressHead(msgInfo)"
@download="onDownloadFile"
@audioStateChange="onAudioStateChange"
:id="'chat-item-' + idx"
:msgInfo="msgInfo"
:groupMembers="groupMembers"
>
</chat-message-item>
</view>
</view>
</scroll-view>
<view
v-if="!isInBottom"
class="scroll-to-bottom"
@click="onClickToBottom"
>
{{ newMessageSize > 0 ? newMessageSize + "条新消息" : "⬇️" }}
</view>
</view>
<view
v-if="atUserIds.length > 0"
class="chat-at-bar"
@click="openAtBox()"
>
<view class="iconfont icon-at">&nbsp;</view>
<scroll-view
v-if="atUserIds.length > 0"
class="chat-at-scroll-box"
scroll-x="true"
scroll-left="120"
>
<view class="chat-at-items">
<view v-for="m in atUserItems" class="chat-at-item" :key="m.userId">
<head-image
:name="m.showNickName"
:url="m.headImage"
size="minier"
></head-image>
</view>
</view>
</scroll-view>
</view>
<view class="send-bar">
<!-- <view class="iconfont icon-voice-circle" @click="onRecorderInput()"></view> -->
<!-- <view class="iconfont icon-keyboard" @click="onKeyboardInput()"></view> -->
<!-- <chat-record v-if="showRecord" class="chat-record" @send="onSendRecord"></chat-record> -->
<view class="send-text">
<editor
id="editor"
class="send-text-area"
:placeholder="isReceipt ? '[回执消息]' : ''"
:read-only="isReadOnly"
@focus="onEditorFocus"
@blur="onEditorBlur"
@ready="onEditorReady"
@input="onTextInput"
>
</editor>
</view>
<view
v-if="chat && chat.type == 'GROUP'"
class="iconfont icon-at"
@click="openAtBox()"
></view>
<view
class="iconfont icon-icon_emoji"
@click="onShowEmoChatTab()"
></view>
<view
v-if="isEmpty"
class="iconfont icon-add"
@click="onShowToolsChatTab()"
>
</view>
<button
v-if="!isEmpty || atUserIds.length"
class="btn-send"
type="primary"
@click="sendTextMessage()"
size="mini"
>
发送
</button>
</view>
</view>
<view class="chat-tab-bar">
<scroll-view
v-if="chatTabBox == 'tools'"
class="chat-tools"
:style="{ height: keyboardHeight + 'px' }"
>
<view class="chat-tools-list">
<view class="chat-tools-item" v-if="isFileOpen">
<file-upload
ref="fileUpload"
:onBefore="onUploadFileBefore"
:onSuccess="onUploadFileSuccess"
:onError="onUploadFileFail"
>
<view class="tool-icon iconfont icon-folder"></view>
</file-upload>
<view class="tool-name">文件</view>
</view>
<view class="chat-tools-item">
<image-upload
:maxCount="9"
sourceType="album"
:onBefore="onUploadImageBefore"
:onSuccess="onUploadImageSuccess"
:onError="onUploadImageFail"
>
<view class="tool-icon iconfont icon-picture"></view>
</image-upload>
<view class="tool-name">相册</view>
</view>
<view class="chat-tools-item">
<image-upload
sourceType="camera"
:onBefore="onUploadImageBefore"
:onSuccess="onUploadImageSuccess"
:onError="onUploadImageFail"
>
<view class="tool-icon iconfont icon-camera"></view>
</image-upload>
<view class="tool-name">拍摄</view>
</view>
<!-- <view class="chat-tools-item" @click="onRecorderInput()">
<view class="tool-icon iconfont icon-microphone"></view>
<view class="tool-name">语音消息</view>
</view>
<view v-if="chat.type == 'GROUP' && memberSize<=500" class="chat-tools-item"
@click="switchReceipt()">
<view class="tool-icon iconfont icon-receipt" :class="isReceipt ? 'active' : ''"></view>
<view class="tool-name">回执消息</view>
</view> -->
<!-- #ifndef MP-WEIXIN -->
<!-- 音视频不支持小程序 -->
<!-- <view v-if="chat.type == 'PRIVATE'" class="chat-tools-item" @click="onPriviteVideo()">
<view class="tool-icon iconfont icon-video"></view>
<view class="tool-name">视频通话</view>
</view>
<view v-if="chat.type == 'PRIVATE'" class="chat-tools-item" @click="onPriviteVoice()">
<view class="tool-icon iconfont icon-call"></view>
<view class="tool-name">语音通话</view>
</view>
<view v-if="chat.type == 'GROUP'" class="chat-tools-item" @click="onGroupVideo()">
<view class="tool-icon iconfont icon-call"></view>
<view class="tool-name">语音通话</view>
</view> -->
<!-- #endif -->
</view>
</scroll-view>
<scroll-view
v-if="chatTabBox === 'emo'"
class="chat-emotion"
scroll-y="true"
:style="{ height: keyboardHeight + 'px' }"
>
<view class="emotion-item-list">
<image
class="emotion-item emoji-large"
:title="emoText"
:src="$emo.textToPath(emoText)"
v-for="(emoText, i) in $emo.emoTextList"
:key="i"
@click="selectEmoji(emoText)"
mode="aspectFit"
lazy-load="true"
></image>
</view>
</scroll-view>
</view>
<!-- @用户时选择成员 -->
<chat-at-box
ref="atBox"
:ownerId="group.ownerId"
:members="groupMembers"
@complete="onAtComplete"
></chat-at-box>
<!-- 群语音通话时选择成员 -->
<!-- #ifndef MP-WEIXIN -->
<group-member-selector
ref="selBox"
:members="groupMembers"
:maxSize="configStore.webrtc.maxChannel"
@complete="onInviteOk"
></group-member-selector>
<group-rtc-join ref="rtcJoin" :groupId="group.id"></group-rtc-join>
<!-- #endif -->
</view>
</template>
<script>
import UNI_APP from "@/.env.js";
export default {
data() {
return {
userInfo: {},
group: {},
groupMembers: [],
showAutoQuestionTip: true,
commonQuestions: [], // 空数组,接口获取
autoReplyList: [], // 存储完整回复列表
isReceipt: false,
scrollMsgIdx: 0,
chatTabBox: "none",
currentTargetId: null,
currentChatType: "PRIVATE",
_activeChatIdx: 0,
showRecord: false,
chatMainHeight: 800,
keyboardHeight: 290,
screenHeight: 1000,
windowHeight: 1000,
initHeight: 1000,
atUserIds: [],
showMinIdx: 0,
reqQueue: [],
isSending: false,
isShowKeyBoard: false,
editorCtx: null,
isEmpty: true,
isFocus: false,
isReadOnly: false,
playingAudio: null,
isInBottom: true,
newMessageSize: 0,
scrollTop: 0,
scrollViewHeight: 0,
maxTmpId: 0,
isFileOpen: false,
};
},
methods: {
loadCommonQuestions(userId) {
this.$http({
url: "/auto/reply/list",
method: "get",
})
.then((res) => {
let list = res || [];
this.autoReplyList = list;
this.commonQuestions = list.map((item) => item.replyTitle);
})
.catch(() => {});
},
sendQuestionMessage(replyTitle) {
let autoReply = this.autoReplyList.find(
(item) => item.replyTitle === replyTitle
);
if (!autoReply) return;
// 检查是否被封禁
if (this.isBanned) {
this.showBannedTip();
return;
}
// ========== 第一步:用户发送问题(replyTitle) ==========
let userMsgInfo = {
tmpId: this.generateId(),
type: this.$enums.MESSAGE_TYPE.TEXT,
content: autoReply.replyTitle,
receipt: this.isReceipt
};
this.fillTargetId(userMsgInfo, this.chat.targetId);
const chat = this.chat;
if (!chat) return;
let tmpUserMessage = this.buildTmpMessage(userMsgInfo);
this.chatStore.insertMessage(tmpUserMessage, chat);
this.moveChatToTop();
// 发送用户消息
this.sendMessageRequest(userMsgInfo)
.then((m) => {
tmpUserMessage = JSON.parse(JSON.stringify(tmpUserMessage));
tmpUserMessage.id = m.id;
tmpUserMessage.status = m.status;
this.chatStore.updateMessage(tmpUserMessage, chat);
// ========== 第二步:调用后端接口发送客服回复 ==========
this.triggerAutoReply(autoReply);
this.scrollToBottom();
this.isReceipt = false;
})
.catch(() => {
tmpUserMessage = JSON.parse(JSON.stringify(tmpUserMessage));
tmpUserMessage.status = this.$enums.MESSAGE_STATUS.FAILED;
this.chatStore.updateMessage(tmpUserMessage, chat);
});
},
// 触发客服自动回复
triggerAutoReply(autoReply) {
// 生成临时ID用于追踪
let tmpId = this.generateId();
// 构建客服回复消息
let replyMsgInfo = {
tmpId: tmpId, // 添加 tmpId
sendId: this.chat.targetId, // 客服ID作为发送者
recvId: this.mine.id, // 当前用户作为接收者
type: autoReply.replyType, // 回复类型
receipt: false
};
// 根据类型设置内容
if (autoReply.replyType === 0) {
// 文本回复
replyMsgInfo.content = autoReply.replyContent;
} else if (autoReply.replyType === 1) {
// 图片回复
replyMsgInfo.content = JSON.stringify({
originUrl: autoReply.replyContent,
thumbUrl: autoReply.replyContent,
});
}
// 可选:先在前端显示一条临时的"客服正在输入"消息
let typingMessage = {
id: this.generateId(),
tmpId: tmpId,
sendId: this.chat.targetId,
recvId: this.mine.id,
selfSend: false,
sendTime: new Date().getTime(),
type: this.$enums.MESSAGE_TYPE.TIP_TEXT,
content: "客服正在输入...",
status: this.$enums.MESSAGE_STATUS.SENDING
};
this.chatStore.insertMessage(typingMessage, this.chat);
// 调用发送消息接口
this.$http({
url: "/message/private/send",
method: "post",
data: replyMsgInfo
}).then(res => {
console.log("自动回复发送成功", res);
// 删除"正在输入"的临时消息
this.chatStore.deleteMessage(typingMessage, this.chat);
// 消息会通过 WebSocket 推送过来,前端会自动接收并显示
// 或者如果接口直接返回消息体,可以手动插入
if (res && res.id) {
let replyMessage = {
id: res.id,
tmpId: tmpId,
sendId: this.chat.targetId,
recvId: this.mine.id,
selfSend: false,
sendTime: new Date().getTime(),
type: autoReply.replyType,
content: replyMsgInfo.content,
status: this.$enums.MESSAGE_STATUS.SENDED
};
this.chatStore.insertMessage(replyMessage, this.chat);
this.scrollToBottom();
}
}).catch(err => {
console.error("自动回复发送失败", err);
// 删除"正在输入"的临时消息
this.chatStore.deleteMessage(typingMessage, this.chat);
// 可选:显示发送失败提示
uni.showToast({
title: "自动回复失败",
icon: "none"
});
});
},
// 新增方法:触发客服自动回复(调用后端接口)
// triggerAutoReply(autoReply) {
// // 构建客服回复消息,关键是要传入 sendId
// let replyMsgInfo = {
// sendId: this.chat.targetId, // 客服ID作为发送者
// recvId: this.mine.id, // 当前用户作为接收者
// type: autoReply.replyType, // 回复类型
// };
// console.log(replyMsgInfo)
// // 根据类型设置内容
// if (autoReply.replyType === 0) {
// // 文本回复
// replyMsgInfo.content = autoReply.replyContent;
// } else if (autoReply.replyType === 1) {
// // 图片回复
// replyMsgInfo.content = JSON.stringify({
// originUrl: autoReply.replyContent,
// thumbUrl: autoReply.replyContent,
// });
// }
// // 调用发送消息接口
// this.$http({
// url: "/message/private/send",
// method: "post",
// data: replyMsgInfo
// }).then(res => {
// console.log("自动回复发送成功", res);
// // 消息会通过 WebSocket 推送过来,前端会自动接收并显示
// }).catch(err => {
// console.error("自动回复发送失败", err);
// });
// },
onRecorderInput() {
this.showRecord = true;
this.switchChatTabBox("none");
},
onKeyboardInput() {
this.showRecord = false;
this.switchChatTabBox("none");
},
onSendRecord(data) {
// 检查是否被封禁
if (this.isBanned) {
this.showBannedTip();
return;
}
let msgInfo = {
tmpId: this.generateId(),
content: JSON.stringify(data),
type: this.$enums.MESSAGE_TYPE.AUDIO,
receipt: this.isReceipt,
};
// 填充对方id
this.fillTargetId(msgInfo, this.chat.targetId);
// 防止发送期间用户切换会话导致串扰
const chat = this.chat;
// const chat = this.chatStore.chats[this.activeChatIdx];
if (!chat) return;
// 消息回显
let tmpMessage = this.buildTmpMessage(msgInfo);
this.chatStore.insertMessage(tmpMessage, chat);
this.moveChatToTop();
this.sendMessageRequest(msgInfo)
.then((m) => {
// 更新消息
tmpMessage = JSON.parse(JSON.stringify(tmpMessage));
tmpMessage.id = m.id;
tmpMessage.status = m.status;
this.chatStore.updateMessage(tmpMessage, chat);
// 会话置顶
this.moveChatToTop();
// 滚动到底部
this.scrollToBottom();
this.isReceipt = false;
})
.catch(() => {
tmpMessage = JSON.parse(JSON.stringify(tmpMessage));
tmpMessage.status = this.$enums.MESSAGE_STATUS.FAILED;
this.chatStore.updateMessage(tmpMessage, chat);
});
},
onRtCall(msgInfo) {
if (msgInfo.type == this.$enums.MESSAGE_TYPE.ACT_RT_VOICE) {
this.onPriviteVoice();
} else if (msgInfo.type == this.$enums.MESSAGE_TYPE.ACT_RT_VIDEO) {
this.onPriviteVideo();
}
},
onPriviteVideo() {
const friendInfo = encodeURIComponent(JSON.stringify(this.friend));
uni.navigateTo({
url: `/pages/chat/chat-private-video?mode=video&friend=${friendInfo}&isHost=true`,
});
},
onPriviteVoice() {
const friendInfo = encodeURIComponent(JSON.stringify(this.friend));
uni.navigateTo({
url: `/pages/chat/chat-private-video?mode=voice&friend=${friendInfo}&isHost=true`,
});
},
onGroupVideo() {
// 邀请成员发起通话
let ids = [this.mine.id];
this.$refs.selBox.init(ids, ids, []);
this.$refs.selBox.open();
},
onInviteOk(ids) {
if (ids.length < 2) {
return;
}
let users = [];
ids.forEach((id) => {
let m = this.groupMembers.find((m) => m.userId == id);
// 只取部分字段,压缩url长度
users.push({
id: m.userId,
nickName: m.showNickName,
headImage: m.headImage,
isCamera: false,
isMicroPhone: true,
});
});
const groupId = this.group.id;
const inviterId = this.mine.id;
const userInfos = encodeURIComponent(JSON.stringify(users));
uni.navigateTo({
url: `/pages/chat/chat-group-video?groupId=${groupId}&isHost=true
&inviterId=${inviterId}&userInfos=${userInfos}`,
});
},
moveChatToTop() {
let chatIdx = this.chatStore.findChatIdx(this.chat);
this.chatStore.moveTop(chatIdx);
},
switchReceipt() {
this.isReceipt = !this.isReceipt;
},
openAtBox() {
this.$refs.atBox.init(this.atUserIds);
this.$refs.atBox.open();
},
onAtComplete(atUserIds) {
this.atUserIds = atUserIds;
},
onLongPressHead(msgInfo) {
if (
!msgInfo.selfSend &&
this.isGroup &&
this.atUserIds.indexOf(msgInfo.sendId) < 0
) {
this.atUserIds.push(msgInfo.sendId);
}
},
headImage(msgInfo) {
if (this.isGroup) {
let member = this.groupMembers.find((m) => m.userId == msgInfo.sendId);
return member ? member.headImage : "";
} else {
return msgInfo.selfSend
? this.mine.headImageThumb
: this.chat.headImage;
}
},
showName(msgInfo) {
if (this.isGroup) {
let member = this.groupMembers.find((m) => m.userId == msgInfo.sendId);
return member ? member.showNickName : "";
} else {
return msgInfo.selfSend ? this.mine.nickName : this.chat.showName;
}
},
sendTextMessage() {
this.editorCtx.getContents({
success: (e) => {
this.editorCtx.clear();
if (this.isBanned) {
this.showBannedTip();
return;
}
let sendText = "";
e.delta.ops.forEach((op) => {
if (op.insert.image) {
sendText += `#${op.attributes.alt};`;
} else {
sendText += op.insert;
}
});
sendText = sendText.trim();
if (!sendText && this.atUserIds.length == 0) {
return uni.showToast({
title: "不能发送空白信息",
icon: "none",
});
}
let receiptText = this.isReceipt ? "【回执消息】" : "";
let atText = this.createAtText();
let msgInfo = {
tmpId: this.generateId(),
content: receiptText + sendText + atText,
atUserIds: this.atUserIds,
receipt: this.isReceipt,
type: this.$enums.MESSAGE_TYPE.TEXT,
};
this.atUserIds = [];
this.isReceipt = false;
this.fillTargetId(msgInfo, this.chat.targetId);
const chat = this.chat;
if (!chat) return;
// 创建临时消息
let tmpMessage = this.buildTmpMessage(msgInfo);
// 保存临时消息的副本用于更新
const tmpMessageCopy = JSON.parse(JSON.stringify(tmpMessage));
// 插入消息到 store
this.chatStore.insertMessage(tmpMessageCopy, chat);
// 关键:使用 chat 引用来获取最新消息
const chatIndex = this.chatStore.chats.findIndex(
(c) => c.targetId === chat.targetId && c.type === chat.type
);
if (chatIndex !== -1) {
const targetChat = this.chatStore.chats[chatIndex];
const msgIndex = targetChat.messages.findIndex(
(m) => m.tmpId === msgInfo.tmpId
);
if (msgIndex !== -1) {
// 滚动到底部
this.$nextTick(() => {
this.scrollToBottom();
});
// 发送请求
this.sendMessageRequest(msgInfo)
.then((m) => {
// 更新消息 - 使用响应式更新
const updatedMessage = {
...targetChat.messages[msgIndex],
id: m.id,
status: m.status,
content: m.content,
};
// 使用 Vue.set 或直接替换数组项
this.$set(targetChat.messages, msgIndex, updatedMessage);
// 触发 chat 引用更新
this.$forceUpdate();
})
.catch(() => {
// 更新失败状态
const failedMessage = {
...targetChat.messages[msgIndex],
status: this.$enums.MESSAGE_STATUS.FAILED,
};
this.$set(targetChat.messages, msgIndex, failedMessage);
this.$forceUpdate();
uni.showToast({
title: "发送失败",
icon: "none",
});
});
}
}
},
});
},
createAtText() {
let atText = "";
this.atUserIds.forEach((id) => {
if (id == -1) {
atText += ` @全体成员`;
} else {
let member = this.groupMembers.find((m) => m.userId == id);
if (member) {
atText += ` @${member.showNickName}`;
}
}
});
return atText;
},
fillTargetId(msgInfo, targetId) {
if (this.isGroup) {
msgInfo.groupId = targetId;
} else {
msgInfo.recvId = targetId;
}
},
scrollToBottom() {
let size = this.messageSize;
if (size > 0) {
this.scrollToMsgIdx(size - 1);
}
},
scrollToMsgIdx(idx) {
// 如果scrollMsgIdx值没变化,滚动条不会移动
if (idx == this.scrollMsgIdx && idx > 0) {
this.$nextTick(() => {
// 先滚动到上一条
this.scrollMsgIdx = idx - 1;
// 再滚动目标位置
this.scrollToMsgIdx(idx);
});
return;
}
this.$nextTick(() => {
this.scrollMsgIdx = idx;
});
},
onShowEmoChatTab() {
this.showRecord = false;
this.switchChatTabBox("emo");
},
onShowToolsChatTab() {
this.showRecord = false;
this.switchChatTabBox("tools");
},
switchChatTabBox(chatTabBox) {
if (this.chatTabBox != chatTabBox) {
this.chatTabBox = chatTabBox;
if (chatTabBox != "tools" && this.$refs.fileUpload) {
this.$refs.fileUpload.hide();
}
setTimeout(() => this.reCalChatMainHeight(), 30);
}
},
selectEmoji(emoText) {
let path = this.$emo.textToPath(emoText);
// 先把键盘禁用了,否则会重新弹出键盘
this.isReadOnly = true;
this.isEmpty = false;
this.$nextTick(() => {
this.editorCtx.insertImage({
src: path,
alt: emoText,
extClass: "emoji-small",
nowrap: true,
complete: () => {
this.isReadOnly = false;
this.editorCtx.blur();
},
});
});
},
onUploadImageBefore(file) {
// 检查是否被封禁
if (this.isBanned) {
this.showBannedTip();
return;
}
let data = {
originUrl: file.path,
thumbUrl: file.path,
};
let msgInfo = {
tmpId: this.generateId(),
fileId: file.uid,
sendId: this.mine.id,
content: JSON.stringify(data),
sendTime: new Date().getTime(),
selfSend: true,
type: this.$enums.MESSAGE_TYPE.IMAGE,
readedCount: 0,
status: this.$enums.MESSAGE_STATUS.SENDING,
};
// 填充对方id
this.fillTargetId(msgInfo, this.chat.targetId);
// 插入消息
this.chatStore.insertMessage(msgInfo, this.chat);
// 会话置顶
this.moveChatToTop();
// 借助file对象保存
file.msgInfo = msgInfo;
file.chat = this.chat;
// 更新图片宽高
let chat = this.chat;
this.getImageSize(file).then((size) => {
msgInfo = JSON.parse(JSON.stringify(msgInfo));
data.width = size.width;
data.height = size.height;
msgInfo.content = JSON.stringify(data);
this.chatStore.updateMessage(msgInfo, chat);
this.scrollToBottom();
});
return true;
},
onUploadImageSuccess(file, res) {
let msgInfo = JSON.parse(JSON.stringify(file.msgInfo));
msgInfo.content = JSON.stringify(res.data);
msgInfo.receipt = this.isReceipt;
this.sendMessageRequest(msgInfo)
.then((m) => {
msgInfo.id = m.id;
msgInfo.status = m.status;
this.isReceipt = false;
this.chatStore.updateMessage(msgInfo, file.chat);
})
.catch(() => {
msgInfo.status = this.$enums.MESSAGE_STATUS.FAILED;
this.chatStore.updateMessage(msgInfo, file.chat);
});
},
onUploadImageFail(file, err) {
let msgInfo = JSON.parse(JSON.stringify(file.msgInfo));
msgInfo.status = this.$enums.MESSAGE_STATUS.FAILED;
this.chatStore.updateMessage(msgInfo, file.chat);
},
onUploadFileBefore(file) {
// 检查是否被封禁
if (this.isBanned) {
this.showBannedTip();
return;
}
let data = {
name: file.name,
size: file.size,
url: file.path,
};
let msgInfo = {
tmpId: this.generateId(),
sendId: this.mine.id,
content: JSON.stringify(data),
sendTime: new Date().getTime(),
selfSend: true,
type: this.$enums.MESSAGE_TYPE.FILE,
readedCount: 0,
status: this.$enums.MESSAGE_STATUS.SENDING,
};
// 填充对方id
this.fillTargetId(msgInfo, this.chat.targetId);
// 插入消息
this.chatStore.insertMessage(msgInfo, this.chat);
// 会话置顶
this.moveChatToTop();
// 借助file对象保存
file.msgInfo = msgInfo;
file.chat = this.chat;
return true;
},
onUploadFileSuccess(file, res) {
let data = {
name: file.name,
size: file.size,
url: res.data,
};
let msgInfo = JSON.parse(JSON.stringify(file.msgInfo));
msgInfo.content = JSON.stringify(data);
msgInfo.receipt = this.isReceipt;
this.sendMessageRequest(msgInfo)
.then((m) => {
msgInfo.id = m.id;
msgInfo.status = m.status;
this.isReceipt = false;
this.chatStore.updateMessage(msgInfo, file.chat);
})
.catch(() => {
msgInfo.status = this.$enums.MESSAGE_STATUS.FAILED;
this.chatStore.updateMessage(msgInfo, file.chat);
});
},
onUploadFileFail(file, res) {
let msgInfo = JSON.parse(JSON.stringify(file.msgInfo));
msgInfo.status = this.$enums.MESSAGE_STATUS.FAILED;
this.chatStore.updateMessage(msgInfo, file.chat);
},
onResendMessage(msgInfo) {
if (msgInfo.type != this.$enums.MESSAGE_TYPE.TEXT) {
uni.showToast({
title: "该消息不支持自动重新发送,建议手动重新发送",
icon: "none",
});
return;
}
// 防止发送期间用户切换会话导致串扰
const chat = this.chat;
// const chat = this.chatStore.chats[this.activeChatIdx];
if (!chat) return;
// 删除旧消息
this.chatStore.deleteMessage(msgInfo, chat);
// 重新发送
msgInfo.tmpId = this.generateId();
let tmpMessage = this.buildTmpMessage(msgInfo);
this.chatStore.insertMessage(tmpMessage, chat);
this.moveChatToTop();
this.sendMessageRequest(msgInfo)
.then((m) => {
// 更新消息
tmpMessage = JSON.parse(JSON.stringify(tmpMessage));
tmpMessage.id = m.id;
tmpMessage.status = m.status;
tmpMessage.content = m.content;
this.chatStore.updateMessage(tmpMessage, chat);
})
.catch(() => {
// 更新消息
tmpMessage = JSON.parse(JSON.stringify(tmpMessage));
tmpMessage.status = this.$enums.MESSAGE_STATUS.FAILED;
this.chatStore.updateMessage(tmpMessage, chat);
});
},
onDeleteMessage(msgInfo) {
uni.showModal({
title: "删除消息",
content: "确认删除消息?",
success: (res) => {
if (!res.cancel) {
this.chatStore.deleteMessage(msgInfo, this.chat);
uni.showToast({
title: "删除成功",
icon: "none",
});
}
},
});
},
onRecallMessage(msgInfo) {
uni.showModal({
title: "撤回消息",
content: "确认撤回消息?",
success: (res) => {
if (!res.cancel) {
let url = `/message/${this.chat.type.toLowerCase()}/recall/${
msgInfo.id
}`;
this.$http({
url: url,
method: "DELETE",
}).then((m) => {
m.selfSend = true;
this.chatStore.recallMessage(m, this.chat);
});
}
},
});
},
onCopyMessage(msgInfo) {
uni.setClipboardData({
data: msgInfo.content,
success: () => {
uni.showToast({ title: "复制成功" });
},
fail: () => {
uni.showToast({ title: "复制失败", icon: "none" });
},
});
},
onDownloadFile(msgInfo) {
let url = JSON.parse(msgInfo.content).url;
uni.downloadFile({
url: url,
success(res) {
if (res.statusCode === 200) {
var filePath = encodeURI(res.tempFilePath);
uni.openDocument({
filePath: filePath,
showMenu: true,
});
}
},
fail(e) {
uni.showToast({
title: "文件下载失败",
icon: "none",
});
},
});
},
onClickToBottom() {
/**
* 有些ios设备在点击回到底部后页面会卡住原因不详
* 解决方式: 延迟300ms再滚动
*/
setTimeout(() => {
this.scrollToBottom();
/**
* 有些设备滚到底部时会莫名触发滚动到顶部的事件
* 解决方式: 延迟100ms保证能准确设置底部标志
*/
setTimeout(() => {
this.isInBottom = true;
this.newMessageSize = 0;
}, 100);
}, 300);
},
onScroll(e) {
// 记录当前滚动条高度
this.scrollViewHeight = e.detail.scrollHeight;
},
onScrollToTop() {
if (this.showMinIdx > 0) {
// 防止滚动条定格在顶部,不能一直往上滚
if (uni.getSystemInfoSync().platform == "ios") {
// ios采用scroll-top定位,否则可能会出现白屏
this.holdingScrollBar(this.scrollViewHeight);
} else {
// 安卓采用scroll-into-view定位
this.scrollToMsgIdx(this.showMinIdx);
}
// 多展示20条信息
this.showMinIdx = this.showMinIdx > 20 ? this.showMinIdx - 20 : 0;
}
// 清除底部标识
this.isInBottom = false;
},
onScrollToBottom(e) {
// 设置底部标识
this.isInBottom = true;
this.newMessageSize = 0;
},
holdingScrollBar(scrollViewHeight) {
// 内容高度
const query = uni.createSelectorQuery().in(this);
setTimeout(() => {
query.select(".chat-wrap").boundingClientRect();
query.exec((data) => {
this.scrollTop = data[0].height - scrollViewHeight;
if (this.scrollTop < 10) {
// 未渲染完成,重试一次
this.holdingScrollBar();
} else {
// 让页面再滚动一下,解决部分ios手机出现白屏问题
const delays = [100, 300, 1000];
delays.forEach((delay) =>
setTimeout(() => (this.scrollTop += 5), delay)
);
}
});
}, 10);
},
onShowMore() {
if (this.isGroup) {
uni.navigateTo({
url: "/pages/group/group-info?id=" + this.group.id,
});
} else {
uni.navigateTo({
url: "/pages/common/user-info?id=" + this.userInfo.id,
});
}
},
onTextInput(e) {
this.isEmpty = e.detail.html == "<p><br></p>";
},
onEditorReady() {
this.$nextTick(() => {
const query = uni.createSelectorQuery().in(this);
query
.select("#editor")
.context((res) => {
this.editorCtx = res.context;
})
.exec();
});
},
onEditorFocus(e) {
this.isFocus = true;
this.scrollToBottom();
this.switchChatTabBox("none");
},
onEditorBlur(e) {
this.isFocus = false;
},
onAudioStateChange(state, msgInfo) {
const playingAudio = this.$refs["message" + msgInfo.id][0];
if (state == "PLAYING" && playingAudio != this.playingAudio) {
// 停止之前的录音
this.playingAudio && this.playingAudio.stopPlayAudio();
// 记录当前正在播放的消息
this.playingAudio = playingAudio;
}
},
loadReaded(fid) {
this.$http({
url: `/message/private/maxReadedId?friendId=${fid}`,
method: "get",
}).then((id) => {
this.chatStore.readedMessage({
friendId: fid,
maxId: id,
});
});
},
readedMessage() {
if (this.unreadCount > 0) {
let url = "";
if (this.isGroup) {
url = `/message/group/readed?groupId=${this.chat.targetId}`;
} else {
url = `/message/private/readed?friendId=${this.chat.targetId}`;
}
this.$http({
url: url,
method: "PUT",
}).then(() => {});
}
this.chatStore.resetUnreadCount(this.chat);
},
loadGroup(groupId) {
this.$http({
url: `/group/find/${groupId}`,
method: "GET",
}).then((group) => {
this.group = group;
this.chatStore.updateChatFromGroup(group);
this.groupStore.updateGroup(group);
});
this.$http({
url: `/group/members/${groupId}`,
method: "GET",
}).then((groupMembers) => {
this.groupMembers = groupMembers;
});
},
updateFriendInfo() {
if (this.isFriend) {
// store的数据不能直接修改,深拷贝一份store的数据
let friend = JSON.parse(JSON.stringify(this.friend));
friend.headImage = this.userInfo.headImageThumb;
friend.nickName = this.userInfo.nickName;
friend.showNickName = friend.remarkNickName
? friend.remarkNickName
: friend.nickName;
// 更新好友列表中的昵称和头像
this.friendStore.updateFriend(friend);
// 更新会话中的头像和昵称
this.chatStore.updateChatFromFriend(friend);
} else {
this.chatStore.updateChatFromUser(this.userInfo);
}
},
loadFriend(friendId) {
// 获取好友用户信息
this.$http({
url: `/user/find/${friendId}`,
method: "GET",
}).then((userInfo) => {
this.userInfo = userInfo;
this.updateFriendInfo();
});
},
rpxTopx(rpx) {
// rpx转换成px
let info = uni.getSystemInfoSync();
let px = (info.windowWidth * rpx) / 750;
return Math.floor(rpx);
},
sendMessageRequest(msgInfo) {
return new Promise((resolve, reject) => {
// 请求入队列,防止请求"后发先至",导致消息错序
this.reqQueue.push({ msgInfo, resolve, reject });
this.processReqQueue();
});
},
processReqQueue() {
if (this.reqQueue.length && !this.isSending) {
this.isSending = true;
const reqData = this.reqQueue.shift();
console.log(reqData.msgInfo);
this.$http({
url: this.messageAction,
method: "post",
data: reqData.msgInfo,
})
.then((res) => {
reqData.resolve(res);
})
.catch((e) => {
reqData.reject(e);
})
.finally(() => {
this.isSending = false;
// 发送下一条请求
this.processReqQueue();
});
}
},
reCalChatMainHeight() {
let sysInfo = uni.getSystemInfoSync();
let h = this.windowHeight;
// 减去标题栏高度
h -= 50;
// 减去键盘高度
if (this.isShowKeyBoard || this.chatTabBox != "none") {
h -= this.keyboardHeight;
this.scrollToBottom();
}
// APP需要减去状态栏高度
// #ifdef APP-PLUS
h -= sysInfo.statusBarHeight;
// #endif
this.chatMainHeight = h;
// #ifndef APP
// ios浏览器键盘把页面顶起后,页面长度不会变化,这里把页面拉到顶部适配一下
if (uni.getSystemInfoSync().platform == "ios") {
// 不同手机需要的延时时间不一致,采用分段延时的方式处理
const delays = [50, 100, 500];
delays.forEach((delay) => {
setTimeout(() => {
uni.pageScrollTo({
scrollTop: 0,
duration: 10,
});
}, delay);
});
}
// #endif
},
listenKeyBoard() {
// #ifdef H5
if (navigator.platform == "Win32") {
// 电脑端不需要弹出键盘
console.log("navigator.platform:", navigator.platform);
return;
}
if (uni.getSystemInfoSync().platform == "ios") {
// 监听键盘高度,ios13以上开始支持
if (window.visualViewport) {
window.visualViewport.addEventListener("resize", this.resizeListener);
} else {
// ios h5实现键盘监听
window.addEventListener("focusin", this.focusInListener);
window.addEventListener("focusout", this.focusOutListener);
}
} else {
// 安卓h5实现键盘监听
window.addEventListener("resize", this.resizeListener);
}
// #endif
// #ifndef H5
// app实现键盘监听
uni.onKeyboardHeightChange(this.keyBoardListener);
// #endif
},
unListenKeyboard() {
// #ifdef H5
window.removeEventListener("focusin", this.focusInListener);
window.removeEventListener("focusout", this.focusOutListener);
window.removeEventListener("resize", this.resizeListener);
if (window.visualViewport) {
window.visualViewport.removeEventListener(
"resize",
this.resizeListener
);
}
// #endif
// #ifndef H5
uni.offKeyboardHeightChange(this.keyBoardListener);
// #endif
},
keyBoardListener(res) {
this.isShowKeyBoard = res.height > 0;
if (this.isShowKeyBoard) {
this.keyboardHeight = res.height; // 获取并保存键盘高度
// #ifdef APP-PLUS
// ios app的键盘高度不准,需要减去屏幕和窗口差
let sysInfo = uni.getSystemInfoSync();
if (sysInfo.platform == "ios") {
this.keyboardHeight -= this.screenHeight - this.windowHeight;
}
// #endif
}
setTimeout(() => this.reCalChatMainHeight(), 30);
},
resizeListener() {
let keyboardHeight = this.initHeight - window.innerHeight;
// 兼容部分ios浏览器
if (window.visualViewport && uni.getSystemInfoSync().platform == "ios") {
keyboardHeight = this.initHeight - window.visualViewport.height;
}
let isShowKeyBoard = keyboardHeight > 150;
if (isShowKeyBoard) {
this.keyboardHeight = keyboardHeight;
}
if (this.isShowKeyBoard != isShowKeyBoard) {
this.isShowKeyBoard = isShowKeyBoard;
setTimeout(() => this.reCalChatMainHeight(), 30);
}
},
focusInListener() {
this.isShowKeyBoard = true;
setTimeout(() => this.reCalChatMainHeight(), 30);
},
focusOutListener() {
this.isShowKeyBoard = false;
setTimeout(() => this.reCalChatMainHeight(), 30);
},
showBannedTip() {
let msgInfo = {
tmpId: this.generateId(),
sendId: this.mine.id,
sendTime: new Date().getTime(),
type: this.$enums.MESSAGE_TYPE.TIP_TEXT,
};
if (this.isPrivate) {
msgInfo.recvId = this.mine.id;
msgInfo.content = "该用户已被管理员封禁,原因:" + this.userInfo.reason;
} else {
msgInfo.groupId = this.group.id;
msgInfo.content = "本群聊已被管理员封禁,原因:" + this.group.reason;
}
this.chatStore.insertMessage(msgInfo, this.chat);
},
buildTmpMessage(msgInfo) {
let message = JSON.parse(JSON.stringify(msgInfo));
message.sendId = this.mine.id;
message.sendTime = new Date().getTime();
message.status = this.$enums.MESSAGE_STATUS.SENDING;
message.selfSend = true;
if (this.isGroup) {
message.readedCount = 0;
}
return message;
},
getImageSize(file) {
return new Promise((resolve) => {
uni.getImageInfo({
src: file.path,
success: (res) => {
resolve(res);
},
fail: (err) => {
console.error("获取图片信息失败", err);
},
});
});
},
generateId() {
const id =
String(new Date().getTime()) + String(Math.floor(Math.random() * 1000));
// 必须保证id是递增
if (this.maxTmpId > id) {
return this.generateId();
}
this.maxTmpId = id;
return id;
},
//获取后台设置
async getSetting() {
this.$http({
url: "/getSetting",
method: "post",
}).then((res) => {
if(res.isFileOpen === 1){
this.isFileOpen = true;
}
});
},
},
computed: {
title() {
if (!this.chat) return "";
let title = this.chat.showName;
if (this.isGroup) {
let size = this.groupMembers.filter((m) => !m.quit).length;
title += `(${size})`;
}
return title;
},
chat() {
if (!this.currentTargetId) return null;
return (
this.chatStore.chats.find(
(c) =>
c.targetId === this.currentTargetId &&
c.type === this.currentChatType
) || null
);
},
activeChatIdx: {
get() {
return this._activeChatIdx || 0;
},
set(val) {
this._activeChatIdx = val;
},
},
mine() {
return this.userStore.userInfo;
},
friend() {
return this.friendStore.findFriend(this.userInfo.id);
},
messageAction() {
if (!this.chat) return "";
return `/message/${this.chat.type.toLowerCase()}/send`;
},
messageSize() {
if (!this.chat || !this.chat.messages) {
return 0;
}
return this.chat.messages.length;
},
unreadCount() {
if (!this.chat || !this.chat.unreadCount) {
return 0;
}
return this.chat.unreadCount;
},
isBanned() {
return (
(this.isPrivate && this.userInfo.isBanned) ||
(this.isGroup && this.group.isBanned)
);
},
atUserItems() {
let atUsers = [];
this.atUserIds.forEach((id) => {
if (id == -1) {
atUsers.push({
id: -1,
showNickName: "全体成员",
});
return;
}
let member = this.groupMembers.find((m) => m.userId == id);
if (member) {
atUsers.push(member);
}
});
return atUsers;
},
memberSize() {
return this.groupMembers.filter((m) => !m.quit).length;
},
isGroup() {
return this.chat && this.chat.type == "GROUP";
},
isPrivate() {
return this.chat && this.chat.type == "PRIVATE";
},
loading() {
return this.chatStore.loading;
},
},
watch: {
chat: {
handler(newChat, oldChat) {
if (newChat && newChat.messages && newChat.messages.length > 0) {
// 当消息数量变化时,如果正在底部则滚动
if (this.isInBottom) {
this.$nextTick(() => {
this.scrollToBottom();
});
}
}
},
deep: true,
immediate: true,
},
"chat.messages.length": function (newLength, oldLength) {
if (newLength > oldLength && this.isInBottom) {
this.$nextTick(() => {
this.scrollToBottom();
});
}
},
messageSize: function (newSize, oldSize) {
if (newSize > oldSize && oldSize > 0) {
let lastMessage = this.chat.messages[newSize - 1];
if (this.$msgType.isNormal(lastMessage.type)) {
if (this.isInBottom || lastMessage.selfSend) {
this.scrollToBottom();
} else {
this.newMessageSize++;
}
}
}
},
unreadCount: {
handler(newCount, oldCount) {
if (newCount > 0) {
// 消息已读
this.readedMessage();
}
},
},
loading: {
handler(newLoading, oldLoading) {
// 断线重连后,需要更新一下已读状态
if (!newLoading && this.isPrivate) {
this.loadReaded(this.chat.targetId);
}
},
},
},
async onLoad(options) {
try {
uni.showLoading({ title: "加载中...", mask: true });
let targetId = null;
let type = "PRIVATE";
if (options.targetId) {
targetId = Number(options.targetId);
type = options.type || "PRIVATE";
} else {
if (this.friendStore.friends.length === 0)
await this.friendStore.loadFriend();
const first = this.friendStore.friends[0];
if (!first) return uni.showToast({ title: "暂无好友", icon: "none" });
targetId = first.id;
}
await this.chatStore.loadChat();
await new Promise((r) => setTimeout(r, 300));
let chat = this.chatStore.chats.find(
(c) => c.type === type && c.targetId === targetId
);
if (!chat) {
const friend =
this.friendStore.findFriend(targetId) || this.friendStore.friends[0];
chat = {
targetId,
type,
showName: friend?.nickName || "客服",
headImage: friend?.headImage || "",
isDnd: false,
lastContent: "",
lastSendTime: Date.now(),
unreadCount: 0,
messages: [],
};
this.chatStore.chats.unshift(chat);
}
this.currentTargetId = targetId;
this.currentChatType = type;
await this.$nextTick();
if (!this.chat) {
console.error("Chat 初始化失败");
uni.hideLoading();
return;
}
this.readedMessage();
this.loadFriend(targetId);
this.loadReaded(targetId);
// 加载常见问题
this.loadCommonQuestions(targetId);
this.listenKeyBoard();
this.windowHeight = uni.getSystemInfoSync().windowHeight;
this.screenHeight = uni.getSystemInfoSync().screenHeight;
this.reCalChatMainHeight();
//获取配置信息
await this.getSetting();
this.$nextTick(() => this.scrollToBottom());
} catch (err) {
console.error("错误:", err);
} finally {
uni.hideLoading();
}
},
onUnload() {
this.unListenKeyboard();
},
};
</script>
<style lang="scss">
.chat-box {
$icon-color: rgba(0, 0, 0, 0.88);
position: relative;
background-color: #fafafa;
.header {
display: flex;
justify-content: center;
align-items: center;
height: 60rpx;
padding: 5px;
background-color: #fafafa;
line-height: 50px;
font-size: $im-font-size-large;
box-shadow: $im-box-shadow-lighter;
z-index: 1;
.btn-side {
position: absolute;
line-height: 60rpx;
cursor: pointer;
&.right {
right: 30rpx;
}
}
}
.chat-main-box {
// #ifndef APP-PLUS
top: $im-nav-bar-height;
// #endif
// #ifdef APP-PLUS
top: calc($im-nav-bar-height + var(--status-bar-height));
// #endif
position: fixed;
width: 100%;
display: flex;
flex-direction: column;
z-index: 2;
.chat-message {
flex: 1;
padding: 0;
overflow: hidden;
position: relative;
background-color: white;
.scroll-box {
height: 100%;
padding-top: 200rpx;
box-sizing: border-box;
}
.guess-question-box {
position: absolute;
top: 0;
left: 0;
right: 0;
z-index: 10;
background-color: #f6f6f6;
padding: 20rpx 30rpx;
border-radius: 12rpx;
margin: 10rpx 20rpx;
box-sizing: border-box;
.guess-title {
font-size: 32rpx;
color: #333333;
font-weight: 500;
margin-bottom: 20rpx;
}
.guess-list {
display: flex;
flex-direction: column;
gap: 16rpx;
}
.guess-item {
display: flex;
align-items: center;
gap: 10rpx;
font-size: 30rpx;
color: #009e5f;
cursor: pointer;
.item-bullet {
line-height: 1;
}
.item-text {
line-height: 1.4;
}
&:active {
opacity: 0.7;
}
}
}
.scroll-to-bottom {
position: absolute;
right: 30rpx;
bottom: 30rpx;
font-size: $im-font-size;
color: $im-color-primary;
font-weight: 600;
background: white;
padding: 10rpx 30rpx;
border-radius: 25rpx;
box-shadow: $im-box-shadow-dark;
}
}
.chat-at-bar {
display: flex;
align-items: center;
padding: 0 10rpx;
.icon-at {
font-size: $im-font-size-larger;
color: $im-color-primary;
font-weight: bold;
}
.chat-at-scroll-box {
flex: 1;
width: 80%;
.chat-at-items {
display: flex;
align-items: center;
height: 70rpx;
.chat-at-item {
padding: 0 3rpx;
}
}
}
}
.send-bar {
display: flex;
align-items: center;
padding: 10rpx;
border-top: $im-border solid 1px;
background-color: $im-bg;
min-height: 80rpx;
padding-bottom: 14rpx;
.iconfont {
font-size: 60rpx;
margin: 0 10rpx;
color: $icon-color;
}
.chat-record {
flex: 1;
}
.send-text {
flex: 1;
overflow: auto;
padding: 14rpx 20rpx;
background-color: #fff;
border-radius: 8rpx;
font-size: $im-font-size;
box-sizing: border-box;
margin: 0 10rpx;
position: relative;
.send-text-area {
width: 100%;
height: 100%;
min-height: 40rpx;
max-height: 200rpx;
font-size: 30rpx;
}
}
.btn-send {
margin: 5rpx;
}
}
}
.chat-tab-bar {
width: 100%;
position: fixed;
bottom: 0;
background-color: $im-bg;
.chat-tools {
padding: 40rpx;
box-sizing: border-box;
.chat-tools-list {
display: flex;
flex-wrap: wrap;
align-content: center;
.chat-tools-item {
width: 25%;
padding: 16rpx;
box-sizing: border-box;
display: flex;
flex-direction: column;
align-items: center;
.tool-icon {
padding: 26rpx;
font-size: 54rpx;
border-radius: 20%;
background-color: white;
color: $icon-color;
&:active {
background-color: $im-bg-active;
}
}
.tool-name {
height: 60rpx;
line-height: 60rpx;
font-size: 28rpx;
}
}
}
}
.chat-emotion {
padding: 40rpx;
box-sizing: border-box;
.emotion-item-list {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
align-content: center;
.emotion-item {
text-align: center;
cursor: pointer;
padding: 5px;
}
}
}
}
}
</style>