// 👥 群聊信息页面逻辑 const app = getApp(); const groupChatManager = require('../../../utils/group-chat-manager.js'); const apiClient = require('../../../utils/api-client.js'); Page({ data: { // 系统信息 statusBarHeight: 44, navBarHeight: 88, // 群信息 groupId: '', groupInfo: {}, memberCount: 0, displayMembers: [], // 用户权限 currentUserId: '', userRole: 'member', isOwner: false, isOwnerOrAdmin: false, canInviteMembers: false, // 群设置 groupSettings: { muteNotifications: false, pinned: false, saveToContacts: true }, // 弹窗状态 showQRCodeModal: false, showEditNameModal: false, showEditDescModal: false, // 编辑状态 editGroupName: '', editGroupDescription: '', // 二维码 qrCodeSize: 400, // 加载状态 loading: false, loadingText: '加载中...' }, onLoad(options) { // 获取系统信息 this.getSystemInfo(); // 获取群ID if (options.groupId) { this.setData({ groupId: options.groupId }); // 加载群信息 this.loadGroupInfo(); } else { wx.showToast({ title: '群聊ID不能为空', icon: 'none' }); setTimeout(() => { wx.navigateBack(); }, 1500); } }, onShow() { // 刷新群信息 if (this.data.groupId) { this.loadGroupInfo(); } }, // 获取系统信息 getSystemInfo() { const systemInfo = wx.getSystemInfoSync(); this.setData({ statusBarHeight: systemInfo.statusBarHeight || 44, navBarHeight: 88, currentUserId: wx.getStorageSync('userId') }); }, // 加载群信息 async loadGroupInfo() { try { this.setData({ loading: true, loadingText: '加载群信息中...' }); // 获取群基本信息 const groupResponse = await apiClient.request({ url: `/api/v1/groups/${this.data.groupId}`, method: 'GET' }); if (!groupResponse.success) { throw new Error(groupResponse.error || '获取群信息失败'); } const groupInfo = groupResponse.data; // 获取群成员列表 const membersResult = await groupChatManager.getGroupMembers(this.data.groupId, false); if (!membersResult.success) { throw new Error(membersResult.error || '获取群成员失败'); } const members = membersResult.data; // 获取当前用户角色 const currentUser = members.find(member => member.userId === this.data.currentUserId); const userRole = currentUser ? currentUser.role : 'member'; // 计算权限 const isOwner = userRole === 'owner'; const isOwnerOrAdmin = userRole === 'owner' || userRole === 'admin'; const canInviteMembers = isOwnerOrAdmin || groupInfo.settings?.allowMemberInvite; // 处理显示的成员(最多显示8个) const displayMembers = members.slice(0, 8); // 处理公告时间 let announcementTimeText = ''; if (groupInfo.announcementTime) { const date = new Date(groupInfo.announcementTime); announcementTimeText = this.formatDateTime(date); } this.setData({ groupInfo: groupInfo, memberCount: members.length, displayMembers: displayMembers, userRole: userRole, isOwner: isOwner, isOwnerOrAdmin: isOwnerOrAdmin, canInviteMembers: canInviteMembers, announcementTimeText: announcementTimeText, loading: false }); // 加载群设置 this.loadGroupSettings(); } catch (error) { this.setData({ loading: false }); console.error('❌ 加载群信息失败:', error); wx.showToast({ title: error.message || '加载群信息失败', icon: 'none' }); } }, // 加载群设置 async loadGroupSettings() { try { // 从本地存储获取群设置 const settings = wx.getStorageSync(`groupSettings_${this.data.groupId}`) || {}; this.setData({ groupSettings: { muteNotifications: settings.muteNotifications || false, pinned: settings.pinned || false, saveToContacts: settings.saveToContacts !== false } }); } catch (error) { console.error('❌ 加载群设置失败:', error); } }, // 👥 ===== 群信息编辑 ===== // 编辑群头像 editGroupAvatar() { if (!this.data.isOwnerOrAdmin) { wx.showToast({ title: '没有修改权限', icon: 'none' }); return; } wx.chooseImage({ count: 1, sizeType: ['compressed'], sourceType: ['album', 'camera'], success: (res) => { const tempFilePath = res.tempFilePaths[0]; this.updateGroupAvatar(tempFilePath); }, fail: (error) => { console.error('❌ 选择头像失败:', error); wx.showToast({ title: '选择头像失败', icon: 'none' }); } }); }, // 更新群头像 async updateGroupAvatar(avatarPath) { try { this.setData({ loading: true, loadingText: '更新头像中...' }); // 上传头像 const uploadResult = await this.uploadImage(avatarPath); if (!uploadResult.success) { throw new Error('头像上传失败'); } // 更新群信息 const result = await groupChatManager.updateGroupInfo(this.data.groupId, { avatar: uploadResult.url }); this.setData({ loading: false }); if (result.success) { // 更新本地数据 this.setData({ 'groupInfo.avatar': uploadResult.url }); wx.showToast({ title: '头像更新成功', icon: 'success' }); } else { throw new Error(result.error || '头像更新失败'); } } catch (error) { this.setData({ loading: false }); console.error('❌ 更新群头像失败:', error); wx.showToast({ title: error.message || '头像更新失败', icon: 'none' }); } }, // 编辑群名称 editGroupName() { if (!this.data.isOwnerOrAdmin) { wx.showToast({ title: '没有修改权限', icon: 'none' }); return; } this.setData({ editGroupName: this.data.groupInfo.name || '', showEditNameModal: true }); }, // 群名称输入 onEditGroupNameInput(e) { this.setData({ editGroupName: e.detail.value }); }, // 确认修改群名称 async confirmEditGroupName() { const newName = this.data.editGroupName.trim(); if (!newName) { wx.showToast({ title: '群名称不能为空', icon: 'none' }); return; } if (newName === this.data.groupInfo.name) { this.closeEditNameModal(); return; } try { this.setData({ loading: true, loadingText: '更新群名称中...' }); const result = await groupChatManager.updateGroupInfo(this.data.groupId, { name: newName }); this.setData({ loading: false }); if (result.success) { // 更新本地数据 this.setData({ 'groupInfo.name': newName }); this.closeEditNameModal(); wx.showToast({ title: '群名称更新成功', icon: 'success' }); } else { throw new Error(result.error || '群名称更新失败'); } } catch (error) { this.setData({ loading: false }); console.error('❌ 更新群名称失败:', error); wx.showToast({ title: error.message || '群名称更新失败', icon: 'none' }); } }, // 关闭编辑群名称弹窗 closeEditNameModal() { this.setData({ showEditNameModal: false, editGroupName: '' }); }, // 编辑群描述 editGroupDescription() { if (!this.data.isOwnerOrAdmin) { wx.showToast({ title: '没有修改权限', icon: 'none' }); return; } this.setData({ editGroupDescription: this.data.groupInfo.description || '', showEditDescModal: true }); }, // 群描述输入 onEditGroupDescInput(e) { this.setData({ editGroupDescription: e.detail.value }); }, // 确认修改群描述 async confirmEditGroupDescription() { const newDescription = this.data.editGroupDescription.trim(); if (newDescription === this.data.groupInfo.description) { this.closeEditDescModal(); return; } try { this.setData({ loading: true, loadingText: '更新群描述中...' }); const result = await groupChatManager.updateGroupInfo(this.data.groupId, { description: newDescription }); this.setData({ loading: false }); if (result.success) { // 更新本地数据 this.setData({ 'groupInfo.description': newDescription }); this.closeEditDescModal(); wx.showToast({ title: '群描述更新成功', icon: 'success' }); } else { throw new Error(result.error || '群描述更新失败'); } } catch (error) { this.setData({ loading: false }); console.error('❌ 更新群描述失败:', error); wx.showToast({ title: error.message || '群描述更新失败', icon: 'none' }); } }, // 关闭编辑群描述弹窗 closeEditDescModal() { this.setData({ showEditDescModal: false, editGroupDescription: '' }); }, // 编辑群公告 editGroupAnnouncement() { if (!this.data.isOwnerOrAdmin) { wx.showToast({ title: '没有发布权限', icon: 'none' }); return; } // 跳转到群公告编辑页面 wx.navigateTo({ url: `/subpackages/group/group-announcement/group-announcement?groupId=${this.data.groupId}&mode=edit` }); }, // 🔧 ===== 工具方法 ===== // 格式化日期时间 formatDateTime(date) { const now = new Date(); const diff = now.getTime() - date.getTime(); if (diff < 60000) { // 1分钟内 return '刚刚'; } else if (diff < 3600000) { // 1小时内 return `${Math.floor(diff / 60000)}分钟前`; } else if (diff < 86400000) { // 1天内 return `${Math.floor(diff / 3600000)}小时前`; } else if (diff < 604800000) { // 1周内 return `${Math.floor(diff / 86400000)}天前`; } else { return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`; } }, // 上传图片 async uploadImage(filePath) { return new Promise((resolve, reject) => { wx.uploadFile({ url: `${app.globalData.apiBaseUrl}/api/v1/upload/image`, filePath: filePath, name: 'file', header: { 'Authorization': `Bearer ${wx.getStorageSync('token')}` }, success: (res) => { try { const data = JSON.parse(res.data); if (data.success) { resolve({ success: true, url: data.data.url }); } else { reject(new Error(data.error || '上传失败')); } } catch (error) { reject(new Error('上传响应解析失败')); } }, fail: (error) => { reject(error); } }); }); }, // 👤 ===== 成员管理 ===== // 邀请成员 inviteMembers() { if (!this.data.canInviteMembers) { wx.showToast({ title: '没有邀请权限', icon: 'none' }); return; } // 跳转到邀请成员页面 wx.navigateTo({ url: `/subpackages/group/create-group-chat/create-group-chat?groupId=${this.data.groupId}` }); }, // 查看所有成员 viewAllMembers() { // 跳转到群成员列表页面 wx.navigateTo({ url: `/subpackages/group/group-members/group-members?groupId=${this.data.groupId}` }); }, // 查看成员资料 viewMemberProfile(e) { const userId = e.currentTarget.dataset.userId; if (userId === this.data.currentUserId) { // 查看自己的资料 wx.navigateTo({ url: '/subpackages/profile/profile/profile' }); } else { // 查看其他成员资料 wx.navigateTo({ url: `/subpackages/social/user-detail/user-detail?customId=${userId}` }); } }, // 📋 ===== 群功能 ===== // 搜索聊天记录 searchChatHistory() { wx.showToast({ title: '搜索功能开发中', icon: 'none' }); // TODO: 集成 NIM SDK 的消息搜索功能 // wx.navigateTo({ // url: `/subpackages/search/global-search/global-search?conversationId=${this.data.groupId}&conversationName=${encodeURIComponent(this.data.groupInfo.name || '群聊')}` // }); }, // 查看群文件 viewGroupFiles() { wx.showToast({ title: '群文件功能开发中', icon: 'none' }); }, // 查看群相册 viewGroupPhotos() { wx.showToast({ title: '群相册功能开发中', icon: 'none' }); }, // 显示群二维码 showGroupQRCode() { this.setData({ showQRCodeModal: true }); // 生成二维码 this.generateGroupQRCode(); }, // 生成群二维码 generateGroupQRCode() { try { // 构建二维码数据 const qrData = JSON.stringify({ type: 'group', groupId: this.data.groupId, groupName: this.data.groupInfo.name }); // 这里应该使用二维码生成库,暂时用canvas模拟 const ctx = wx.createCanvasContext('groupQRCode', this); // 绘制二维码背景 ctx.setFillStyle('#FFFFFF'); ctx.fillRect(0, 0, this.data.qrCodeSize, this.data.qrCodeSize); // 绘制二维码内容(这里简化处理) ctx.setFillStyle('#000000'); ctx.setTextAlign('center'); ctx.setFontSize(16); ctx.fillText('群聊二维码', this.data.qrCodeSize / 2, this.data.qrCodeSize / 2); ctx.fillText(this.data.groupInfo.name, this.data.qrCodeSize / 2, this.data.qrCodeSize / 2 + 30); ctx.draw(); } catch (error) { console.error('❌ 生成二维码失败:', error); } }, // 关闭二维码弹窗 closeQRCodeModal() { this.setData({ showQRCodeModal: false }); }, // 保存二维码到相册 saveQRCodeToAlbum() { wx.canvasToTempFilePath({ canvasId: 'groupQRCode', success: (res) => { wx.saveImageToPhotosAlbum({ filePath: res.tempFilePath, success: () => { wx.showToast({ title: '保存成功', icon: 'success' }); }, fail: (error) => { console.error('❌ 保存失败:', error); wx.showToast({ title: '保存失败', icon: 'none' }); } }); }, fail: (error) => { console.error('❌ 生成图片失败:', error); wx.showToast({ title: '生成图片失败', icon: 'none' }); } }, this); }, // 分享二维码 shareQRCode() { wx.canvasToTempFilePath({ canvasId: 'groupQRCode', success: (res) => { wx.showShareImageMenu({ path: res.tempFilePath, success: () => { }, fail: (error) => { console.error('❌ 分享失败:', error); wx.showToast({ title: '分享失败', icon: 'none' }); } }); }, fail: (error) => { console.error('❌ 生成图片失败:', error); wx.showToast({ title: '生成图片失败', icon: 'none' }); } }, this); }, // ⚙️ ===== 群设置 ===== // 消息免打扰设置变化 onMuteNotificationsChange(e) { const checked = e.detail.value; this.setData({ 'groupSettings.muteNotifications': checked }); this.saveGroupSettings(); }, // 置顶聊天设置变化 onPinnedChange(e) { const checked = e.detail.value; this.setData({ 'groupSettings.pinned': checked }); this.saveGroupSettings(); }, // 保存到通讯录设置变化 onSaveToContactsChange(e) { const checked = e.detail.value; this.setData({ 'groupSettings.saveToContacts': checked }); this.saveGroupSettings(); }, // 保存群设置 saveGroupSettings() { try { wx.setStorageSync(`groupSettings_${this.data.groupId}`, this.data.groupSettings); } catch (error) { console.error('❌ 保存群设置失败:', error); } }, // 打开群设置 openGroupSettings() { // 跳转到群设置页面 wx.navigateTo({ url: `/subpackages/group/group-info/group-info?groupId=${this.data.groupId}` }); }, // 📱 ===== 操作功能 ===== // 发消息 sendMessage() { // 跳转到群聊页面 wx.navigateTo({ url: `/pages/message/chat/chat?chatType=1&targetId=${this.data.groupId}&chatName=${encodeURIComponent(this.data.groupInfo.name || '群聊')}` }); }, // 显示退出群聊选项 showLeaveGroupOptions() { if (this.data.isOwner) { // 群主显示解散群聊选项 wx.showModal({ title: '解散群聊', content: '解散后,所有成员将被移出群聊,且聊天记录将被清空。确定要解散群聊吗?', confirmText: '解散', confirmColor: '#FF3B30', success: (res) => { if (res.confirm) { this.dissolveGroup(); } } }); } else { // 普通成员显示退出群聊选项 wx.showModal({ title: '退出群聊', content: '退出后,将不再接收此群聊消息。确定要退出群聊吗?', confirmText: '退出', confirmColor: '#FF3B30', success: (res) => { if (res.confirm) { this.leaveGroup(); } } }); } }, // 解散群聊 async dissolveGroup() { try { this.setData({ loading: true, loadingText: '解散群聊中...' }); const result = await groupChatManager.dissolveGroup(this.data.groupId); this.setData({ loading: false }); if (result.success) { wx.showToast({ title: '群聊已解散', icon: 'success' }); // 返回消息列表 setTimeout(() => { wx.navigateBack({ delta: 2 }); }, 1500); } else { throw new Error(result.error || '解散群聊失败'); } } catch (error) { this.setData({ loading: false }); console.error('❌ 解散群聊失败:', error); wx.showToast({ title: error.message || '解散群聊失败', icon: 'none' }); } }, // 退出群聊 async leaveGroup() { try { this.setData({ loading: true, loadingText: '退出群聊中...' }); const result = await groupChatManager.leaveGroup(this.data.groupId); this.setData({ loading: false }); if (result.success) { wx.showToast({ title: '已退出群聊', icon: 'success' }); // 返回消息列表 setTimeout(() => { wx.navigateBack({ delta: 2 }); }, 1500); } else { throw new Error(result.error || '退出群聊失败'); } } catch (error) { this.setData({ loading: false }); console.error('❌ 退出群聊失败:', error); wx.showToast({ title: error.message || '退出群聊失败', icon: 'none' }); } }, // 显示更多菜单 showMoreMenu() { const itemList = []; if (this.data.isOwnerOrAdmin) { itemList.push('群管理'); } itemList.push('举报群聊'); wx.showActionSheet({ itemList: itemList, success: (res) => { switch (res.tapIndex) { case 0: if (this.data.isOwnerOrAdmin) { this.openGroupManagement(); } else { this.reportGroup(); } break; case 1: this.reportGroup(); break; default: } } }); }, // 打开群管理 openGroupManagement() { // 跳转到群管理页面 wx.navigateTo({ url: `/subpackages/group/group-info/group-info?groupId=${this.data.groupId}&tab=management` }); }, // 举报群聊 reportGroup() { wx.showToast({ title: '举报功能开发中', icon: 'none' }); }, // 阻止事件冒泡 stopPropagation() { // 阻止点击事件冒泡 }, // 🧭 ===== 页面导航 ===== // 返回上一页 goBack() { wx.navigateBack(); }, // 设置tabBar选中状态 onShow() { if (typeof this.getTabBar === 'function' && this.getTabBar()) { this.getTabBar().setData({ selected: 0 }); } } });