m2pool_web_frontend/mining-pool/src/views/customerService/index.vue

1044 lines
26 KiB
Vue
Raw Normal View History

2025-04-22 06:26:41 +00:00
<template>
<div class="cs-chat-container">
<!-- 聊天窗口主体 -->
<div class="cs-chat-wrapper">
<!-- 左侧联系人列表 -->
<div class="cs-contact-list">
<div class="cs-header"><i class="el-icon-s-custom"></i> 联系列表</div>
<div class="cs-search">
<el-input
prefix-icon="el-icon-search"
v-model="searchText"
placeholder="搜索最近联系人"
clearable
></el-input>
</div>
<!-- 联系人列表 -->
<div class="cs-contacts">
<div
v-for="(contact, index) in filteredContacts"
:key="index"
class="cs-contact-item"
:class="{ active: currentContactId === contact.roomId }"
@click="selectContact(contact.roomId)"
>
<div class="cs-avatar">
<el-avatar :size="40" :src="getDefaultAvatar(contact.name)">
{{ contact.name ? contact.name.charAt(0) : "?" }}
</el-avatar>
<span v-if="contact.unread" class="unread-badge">{{
contact.unread
}}</span>
</div>
<div class="cs-contact-info">
<div class="cs-contact-name">
{{ contact.name }}
<span class="cs-contact-time">{{
formatLastTime(contact.lastTime)
}}</span>
</div>
<div class="cs-contact-msg">
<span v-if="contact.important" class="important-tag"
>[重要]</span
>
{{ contact.lastMessage }}
</div>
</div>
</div>
</div>
</div>
<!-- 右侧聊天区域 -->
<div class="cs-chat-area">
<!-- 顶部信息栏 -->
<div class="cs-chat-header">
<div class="cs-chat-title">
{{ currentContact ? currentContact.name : "请选择联系人" }}
<el-tag
v-if="currentContact && currentContact.important"
size="small"
type="danger"
@click="
toggleImportant(
currentContact.roomId,
!currentContact.important
)
"
>
重要
</el-tag>
<el-tag
v-else-if="currentContact"
size="small"
type="info"
@click="
toggleImportant(
currentContact.roomId,
!currentContact.important
)
"
>
标记为重要
</el-tag>
</div>
<div class="cs-header-actions">
<i class="el-icon-time" title="历史记录" @click="loadHistory"></i>
<i
class="el-icon-refresh"
title="刷新"
@click="refreshMessages"
></i>
<i class="el-icon-more" title="更多选项"></i>
</div>
</div>
<!-- 聊天内容区域 -->
<div class="cs-chat-messages" ref="messageContainer">
<div v-if="!currentContact" class="cs-empty-chat">
<i class="el-icon-chat-dot-round"></i>
<p>您尚未选择联系人</p>
</div>
<template v-else>
<div v-if="messagesLoading" class="cs-loading">
<i class="el-icon-loading"></i>
<p>加载消息中...</p>
</div>
<div v-else-if="currentMessages.length === 0" class="cs-empty-chat">
<i class="el-icon-chat-line-round"></i>
<p>暂无消息记录</p>
</div>
<div v-else class="cs-message-list">
<div
v-for="(message, idx) in currentMessages"
:key="idx"
class="cs-message"
:class="{ 'cs-message-self': message.isSelf }"
>
<div class="cs-message-time" v-if="showMessageTime(idx)">
{{ formatTime(message.time) }}
</div>
<div class="cs-message-content">
<div class="cs-avatar">
<el-avatar :size="36" :src="message.isSelf ? getDefaultAvatar('我') : getDefaultAvatar(message.sender)">
{{ message.sender ? message.sender.charAt(0) : '?' }}
</el-avatar>
</div>
<div class="cs-bubble">
<div class="cs-sender">{{ message.sender }}</div>
<div v-if="!message.isImage" class="cs-text">
{{ message.content }}
</div>
<div v-else class="cs-image">
<img
:src="message.content"
@click="previewImage(message.content)"
/>
</div>
</div>
</div>
</div>
</div>
</template>
</div>
<!-- 输入区域 -->
<div class="cs-chat-input">
<div class="cs-toolbar">
<i
class="el-icon-picture-outline"
title="发送图片"
@click="openImageUpload"
></i>
<input
type="file"
ref="imageInput"
accept="image/*"
style="display: none"
@change="handleImageUpload"
/>
<i class="el-icon-folder-opened" title="发送文件"></i>
<i class="el-icon-s-opportunity" title="发送表情"></i>
<i class="el-icon-scissors" title="截图"></i>
</div>
<div class="cs-input-area">
<el-input
type="textarea"
v-model="inputMessage"
:rows="3"
:disabled="!currentContact"
placeholder="请输入消息按Enter键发送按Ctrl+Enter键换行"
@keydown.enter.exact.prevent="sendMessage"
></el-input>
</div>
<div class="cs-send-area">
<span class="cs-counter">{{ inputMessage.length }}/500</span>
<el-button
type="primary"
:disabled="!currentContact || !inputMessage.trim() || sending"
@click="sendMessage"
>
<i v-if="sending" class="el-icon-loading"></i>
<span v-else>发送</span>
</el-button>
</div>
</div>
</div>
</div>
<!-- 图片预览 -->
<el-dialog
:visible.sync="previewVisible"
append-to-body
class="image-preview-dialog"
>
<img :src="previewImageUrl" class="preview-image" alt="预览图片" />
</el-dialog>
</div>
</template>
<script>
import {
getRoomList,
getHistory,
getHistory7,
getReadMessage,
getUpdateRoom,
getFileUpdate,
} from "../../api/customerService";
export default {
name: "CustomerServiceChat",
data() {
return {
searchText: "",
inputMessage: "",
currentContactId: null,
previewVisible: false,
previewImageUrl: "",
contacts: [],
messages: {},
messagesLoading: false,
sending: false,
loadingRooms: true,
};
},
computed: {
filteredContacts() {
if (!this.searchText) {
return this.contacts;
}
return this.contacts.filter((contact) =>
contact.name.toLowerCase().includes(this.searchText.toLowerCase())
);
},
currentContact() {
return this.contacts.find(
(contact) => contact.roomId === this.currentContactId
);
},
currentMessages() {
return this.messages[this.currentContactId] || [];
},
},
methods: {
// 获取聊天室列表
async fetchRoomList() {
try {
this.loadingRooms = true;
const response = await getRoomList();
if (response && response.code === 200 && response.data) {
this.contacts = response.data.map(room => ({
roomId: room.roomId,
name: room.roomName || '未命名聊天室',
avatar: this.getDefaultAvatar(room.roomName || '未命名聊天室'), // 使用默认头像
lastMessage: room.lastMessage || '暂无消息',
lastTime: room.lastTime || new Date(),
unread: room.unreadCount || 0,
important: room.important || false
}));
} else {
this.$message.error('获取聊天室列表失败');
}
} catch (error) {
console.error('获取聊天室列表异常:', error);
this.$message.error('获取聊天室列表异常');
} finally {
this.loadingRooms = false;
}
},
// 选择联系人
async selectContact(roomId) {
if (this.currentContactId === roomId) return;
this.currentContactId = roomId;
// 如果没有该联系人的消息,则加载
if (!this.messages[roomId]) {
await this.loadMessages(roomId);
}
// 标记消息为已读
if (this.currentContact && this.currentContact.unread > 0) {
try {
await getReadMessage({ roomId });
// 更新未读数
const contact = this.contacts.find((c) => c.roomId === roomId);
if (contact) {
contact.unread = 0;
}
} catch (error) {
console.error("标记消息已读失败:", error);
}
}
this.$nextTick(() => {
this.scrollToBottom();
});
},
// 加载聊天消息
async loadMessages(roomId) {
if (!roomId) return;
try {
this.messagesLoading = true;
// 获取最近7天的消息
const response = await getHistory7();
if (response && response.code === 200 && response.data) {
// 过滤出当前聊天室的消息
const roomMessages = response.data
.filter(msg => msg.roomId === roomId)
.map(msg => ({
sender: msg.senderName || '未知发送者',
avatar: msg.isSelf ? this.getDefaultAvatar('我') : this.getDefaultAvatar(msg.senderName || '未知发送者'), // 使用默认头像
content: msg.content,
time: new Date(msg.createTime),
isSelf: msg.isSelf,
isImage: msg.type === 'image'
}));
// 更新消息列表
this.$set(this.messages, roomId, roomMessages);
} else {
this.$message.warning('获取聊天记录失败');
this.$set(this.messages, roomId, []);
}
} catch (error) {
console.error('加载消息异常:', error);
this.$message.error('加载消息异常');
this.$set(this.messages, roomId, []);
} finally {
this.messagesLoading = false;
}
},
// 加载历史消息(7天前)
async loadHistory() {
if (!this.currentContactId) return;
try {
this.messagesLoading = true;
const response = await getHistory();
if (response && response.code === 200 && response.data) {
// 过滤出当前聊天室的历史消息
const historyMessages = response.data
.filter((msg) => msg.roomId === this.currentContactId)
.map((msg) => ({
sender: msg.senderName || "未知发送者",
avatar: msg.avatar,
content: msg.content,
time: new Date(msg.createTime),
isSelf: msg.isSelf,
isImage: msg.type === "image",
}));
// 合并消息
const currentMessages = this.messages[this.currentContactId] || [];
// 将历史消息放在前面
this.$set(this.messages, this.currentContactId, [
...historyMessages,
...currentMessages,
]);
this.$message.success("已加载历史消息");
} else {
this.$message.warning("没有更多历史消息");
}
} catch (error) {
console.error("加载历史消息异常:", error);
this.$message.error("加载历史消息异常");
} finally {
this.messagesLoading = false;
}
},
// 刷新当前聊天消息
async refreshMessages() {
if (!this.currentContactId) return;
await this.loadMessages(this.currentContactId);
},
// 发送消息
async sendMessage() {
if (!this.inputMessage.trim() || !this.currentContact || this.sending) return;
const messageContent = this.inputMessage.trim();
this.inputMessage = '';
this.sending = true;
try {
// 这里应该有一个发送消息的API假设是通过websocket或API发送
// 因为示例代码中没有提供发送消息的API这里模拟发送
// 先显示本地消息
if (!this.messages[this.currentContactId]) {
this.$set(this.messages, this.currentContactId, []);
}
this.messages[this.currentContactId].push({
sender: '我',
avatar: this.getDefaultAvatar('我'), // 使用默认头像
content: messageContent,
time: new Date(),
isSelf: true,
isImage: false
});
// 更新最后一条消息
const currentContact = this.contacts.find(c => c.roomId === this.currentContactId);
if (currentContact) {
currentContact.lastMessage = messageContent;
currentContact.lastTime = new Date();
}
// 滚动到底部
this.$nextTick(() => {
this.scrollToBottom();
});
// 模拟发送延迟
await this.simulateMessageSending();
} catch (error) {
console.error('发送消息失败:', error);
this.$message.error('发送消息失败,请重试');
} finally {
this.sending = false;
}
},
// 模拟消息发送请求
simulateMessageSending() {
return new Promise(resolve => {
setTimeout(() => {
// 模拟服务器响应
this.messages[this.currentContactId].push({
sender: this.currentContact.name,
avatar: this.getDefaultAvatar(this.currentContact.name), // 使用默认头像
content: '已收到您的消息,我们会尽快回复。',
time: new Date(),
isSelf: false,
isImage: false
});
// 更新最后一条消息
const currentContact = this.contacts.find(c => c.roomId === this.currentContactId);
if (currentContact) {
currentContact.lastMessage = '已收到您的消息,我们会尽快回复。';
}
this.$nextTick(() => {
this.scrollToBottom();
});
resolve();
}, 1000);
});
},
// 打开图片上传控件
openImageUpload() {
if (!this.currentContact) return;
this.$refs.imageInput.click();
},
// 处理图片上传
async handleImageUpload(event) {
const file = event.target.files[0];
if (!file) return;
// 检查文件类型
if (!file.type.startsWith('image/')) {
this.$message.warning('只能上传图片文件!');
return;
}
// 检查文件大小 (5MB限制)
const maxSize = 5 * 1024 * 1024;
if (file.size > maxSize) {
this.$message.warning('图片大小不能超过5MB!');
return;
}
this.sending = true;
try {
// 创建FormData对象
const formData = new FormData();
formData.append('file', file);
// 调用文件上传API
const response = await getFileUpdate(formData);
if (response && response.code === 200 && response.data) {
const imageUrl = response.data.url; // 假设API返回图片URL
// 添加图片消息
if (!this.messages[this.currentContactId]) {
this.$set(this.messages, this.currentContactId, []);
}
this.messages[this.currentContactId].push({
sender: '我',
avatar: this.getDefaultAvatar('我'), // 使用默认头像
content: imageUrl,
time: new Date(),
isSelf: true,
isImage: true
});
// 更新最后一条消息
const currentContact = this.contacts.find(c => c.roomId === this.currentContactId);
if (currentContact) {
currentContact.lastMessage = '[图片]';
currentContact.lastTime = new Date();
}
// 滚动到底部
this.$nextTick(() => {
this.scrollToBottom();
});
// 模拟接收回复
setTimeout(() => {
this.messages[this.currentContactId].push({
sender: this.currentContact.name,
avatar: this.getDefaultAvatar(this.currentContact.name), // 使用默认头像
content: '已收到您的图片,我们会尽快查看。',
time: new Date(),
isSelf: false,
isImage: false
});
// 更新最后一条消息
if (currentContact) {
currentContact.lastMessage = '已收到您的图片,我们会尽快查看。';
}
this.$nextTick(() => {
this.scrollToBottom();
});
}, 1000);
} else {
this.$message.error('图片上传失败');
}
} catch (error) {
console.error('上传图片异常:', error);
this.$message.error('上传图片异常');
} finally {
this.sending = false;
// 重置文件输入
this.$refs.imageInput.value = '';
}
},
// 预览图片
previewImage(imageUrl) {
this.previewImageUrl = imageUrl;
this.previewVisible = true;
},
// 标记聊天为重要/非重要
async toggleImportant(roomId, important) {
if (!roomId) return;
try {
const response = await getUpdateRoom({ roomId, important });
if (response && response.code === 200) {
// 更新本地数据
const contact = this.contacts.find((c) => c.roomId === roomId);
if (contact) {
contact.important = important;
}
this.$message.success(important ? "已标记为重要" : "已取消重要标记");
} else {
this.$message.error("标记操作失败");
}
} catch (error) {
console.error("标记聊天状态异常:", error);
this.$message.error("操作失败,请重试");
}
},
// 滚动到底部
scrollToBottom() {
if (this.$refs.messageContainer) {
this.$refs.messageContainer.scrollTop =
this.$refs.messageContainer.scrollHeight;
}
},
// 判断是否显示时间
showMessageTime(index) {
// 显示时间的逻辑第一条消息或距离上一条消息超过5分钟
if (index === 0) return true;
const currentMsg = this.currentMessages[index];
const prevMsg = this.currentMessages[index - 1];
if (!currentMsg.time || !prevMsg.time) return false;
const currentTime = new Date(currentMsg.time).getTime();
const prevTime = new Date(prevMsg.time).getTime();
const diffMinutes = (currentTime - prevTime) / (1000 * 60);
return diffMinutes > 5;
},
// 格式化消息时间
formatTime(date) {
if (!date) return "";
if (!(date instanceof Date)) {
date = new Date(date);
}
const today = new Date();
const yesterday = new Date(today);
yesterday.setDate(yesterday.getDate() - 1);
const isToday = today.toDateString() === date.toDateString();
const isYesterday = yesterday.toDateString() === date.toDateString();
if (isToday) {
return `今天 ${date.toLocaleTimeString([], {
hour: "2-digit",
minute: "2-digit",
})}`;
} else if (isYesterday) {
return `昨天 ${date.toLocaleTimeString([], {
hour: "2-digit",
minute: "2-digit",
})}`;
} else {
return `${date.getFullYear()}/${
date.getMonth() + 1
}/${date.getDate()} ${date.toLocaleTimeString([], {
hour: "2-digit",
minute: "2-digit",
})}`;
}
},
// 格式化最后消息时间
formatLastTime(date) {
if (!date) return "";
if (!(date instanceof Date)) {
date = new Date(date);
}
const today = new Date();
const yesterday = new Date(today);
yesterday.setDate(yesterday.getDate() - 1);
const isToday = today.toDateString() === date.toDateString();
const isYesterday = yesterday.toDateString() === date.toDateString();
if (isToday) {
return date.toLocaleTimeString([], {
hour: "2-digit",
minute: "2-digit",
});
} else if (isYesterday) {
return "昨天";
} else {
return `${date.getMonth() + 1}/${date.getDate()}`;
}
},
// 获取默认头像
getDefaultAvatar(name) {
if (!name) return "";
// 根据名称生成颜色
const colors = [
"#4CAF50",
"#9C27B0",
"#FF5722",
"#2196F3",
"#FFC107",
"#607D8B",
"#E91E63",
];
const index = Math.abs(name.charCodeAt(0)) % colors.length;
const color = colors[index];
// 获取名称首字母
const initial = name.charAt(0).toUpperCase();
// 生成占位头像URL
return `https://via.placeholder.com/40/${color.substring(
1
)}/FFFFFF?text=${initial}`;
},
},
async mounted() {
// 获取聊天室列表
await this.fetchRoomList();
// 默认选择第一个联系人
if (this.contacts.length > 0) {
this.selectContact(this.contacts[0].roomId);
}
// 定时刷新聊天室列表例如每30秒刷新一次
this.roomListInterval = setInterval(() => {
this.fetchRoomList();
// 如果有选中联系人,刷新消息
if (this.currentContactId) {
this.loadMessages(this.currentContactId);
}
}, 30000);
},
beforeDestroy() {
// 清除定时器
if (this.roomListInterval) {
clearInterval(this.roomListInterval);
}
},
};
</script>
<style scoped>
.cs-chat-container {
width: 70%;
height: 600px;
margin: 0 auto;
background-color: #f5f6f7;
border-radius: 10px;
box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
overflow: hidden;
margin-top: 50px;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen,
Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
}
.cs-chat-wrapper {
display: flex;
height: 100%;
}
/* 联系人列表样式 */
.cs-contact-list {
width: 260px;
border-right: 1px solid #e0e0e0;
background-color: #fff;
display: flex;
flex-direction: column;
height: 100%;
}
.cs-header {
padding: 15px;
font-weight: bold;
border-bottom: 1px solid #e0e0e0;
color: #333;
font-size: 16px;
background-color: #f8f8f8;
}
.cs-search {
padding: 10px;
border-bottom: 1px solid #e0e0e0;
}
.cs-contacts {
flex: 1;
overflow-y: auto;
}
.cs-contact-item {
display: flex;
padding: 10px;
cursor: pointer;
border-bottom: 1px solid #f0f0f0;
transition: background-color 0.2s;
}
.cs-contact-item:hover {
background-color: #f5f5f5;
}
.cs-contact-item.active {
background-color: #e6f7ff;
}
.cs-avatar {
position: relative;
margin-right: 10px;
}
.unread-badge {
position: absolute;
top: -5px;
right: -5px;
background-color: #f56c6c;
color: white;
font-size: 12px;
min-width: 16px;
height: 16px;
text-align: center;
line-height: 16px;
border-radius: 8px;
padding: 0 4px;
}
.cs-contact-info {
flex: 1;
min-width: 0;
}
.cs-contact-name {
font-weight: 500;
font-size: 14px;
color: #333;
display: flex;
justify-content: space-between;
margin-bottom: 4px;
}
.cs-contact-time {
font-size: 12px;
color: #999;
font-weight: normal;
}
.cs-contact-msg {
font-size: 12px;
color: #666;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.important-tag {
color: #f56c6c;
font-size: 12px;
margin-right: 4px;
}
/* 聊天区域样式 */
.cs-chat-area {
flex: 1;
display: flex;
flex-direction: column;
background-color: #f5f5f5;
}
.cs-chat-header {
padding: 15px;
border-bottom: 1px solid #e0e0e0;
display: flex;
justify-content: space-between;
align-items: center;
background-color: #fff;
}
.cs-chat-title {
font-weight: bold;
font-size: 16px;
color: #333;
display: flex;
align-items: center;
gap: 10px;
}
.cs-header-actions i {
font-size: 18px;
margin-left: 15px;
color: #666;
cursor: pointer;
}
.cs-header-actions i:hover {
color: #409eff;
}
.cs-chat-messages {
flex: 1;
padding: 15px;
overflow-y: auto;
background-color: #f5f5f5;
}
.cs-loading,
.cs-empty-chat {
height: 100%;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
color: #909399;
}
.cs-loading i,
.cs-empty-chat i {
font-size: 60px;
margin-bottom: 20px;
color: #dcdfe6;
}
.cs-message-list {
display: flex;
flex-direction: column;
}
.cs-message {
margin-bottom: 15px;
}
.cs-message-time {
text-align: center;
margin: 10px 0;
font-size: 12px;
color: #909399;
}
.cs-message-content {
display: flex;
align-items: flex-start;
}
.cs-message-self .cs-message-content {
flex-direction: row-reverse;
}
.cs-message-self .cs-avatar {
margin-right: 0;
margin-left: 10px;
}
.cs-bubble {
max-width: 70%;
padding: 8px 12px;
border-radius: 4px;
background-color: #fff;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
position: relative;
}
.cs-message-self .cs-bubble {
background-color: #d8f4fe;
}
.cs-sender {
font-size: 12px;
color: #909399;
margin-bottom: 4px;
}
.cs-text {
font-size: 14px;
line-height: 1.5;
word-break: break-word;
}
.cs-image img {
max-width: 200px;
max-height: 200px;
border-radius: 4px;
cursor: pointer;
}
/* 输入区域样式 */
.cs-chat-input {
padding: 10px;
background-color: #fff;
border-top: 1px solid #e0e0e0;
}
.cs-toolbar {
padding: 5px 0;
margin-bottom: 5px;
}
.cs-toolbar i {
font-size: 18px;
margin-right: 15px;
color: #606266;
cursor: pointer;
}
.cs-toolbar i:hover {
color: #409eff;
}
.cs-input-area {
margin-bottom: 10px;
}
.cs-send-area {
display: flex;
justify-content: flex-end;
align-items: center;
}
.cs-counter {
margin-right: 10px;
font-size: 12px;
color: #909399;
}
.shop-type {
font-size: 12px;
color: #909399;
font-weight: normal;
margin-left: 5px;
}
/* 图片预览 */
.image-preview-dialog {
display: flex;
justify-content: center;
align-items: center;
}
.preview-image {
max-width: 100%;
max-height: 80vh;
}
/* 响应式调整 */
@media (max-width: 768px) {
.cs-contact-list {
width: 200px;
}
.cs-image img {
max-width: 150px;
max-height: 150px;
}
}
</style>