chat.vue 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967
  1. <template>
  2. <view class="chat-page">
  3. <!-- 更多选项弹窗 -->
  4. <view v-if="showMoreOptionsModal" class="modal-mask" @click="closeMoreOptions">
  5. <view class="modal-content" @click.stop>
  6. <view class="modal-header">
  7. <text class="modal-title">{{ targetUserName }}</text>
  8. <text class="modal-subtitle">好友操作</text>
  9. </view>
  10. <view class="modal-body">
  11. <!-- <view class="modal-item" @click="goToUserProfile">
  12. <text class="item-icon">👤</text>
  13. <text class="item-text">查看资料</text>
  14. </view> -->
  15. <view class="modal-item" @click="blockFriend" :class="{ danger: true }">
  16. <text class="item-icon">🚫</text>
  17. <text class="item-text">拉黑好友</text>
  18. </view>
  19. <!-- <view class="modal-item" @click="reportUser" :class="{ danger: true }">
  20. <text class="item-icon">🚨</text>
  21. <text class="item-text">举报用户</text>
  22. </view> -->
  23. </view>
  24. <view class="modal-footer">
  25. <button class="modal-close-btn" @click="closeMoreOptions">取消</button>
  26. </view>
  27. </view>
  28. </view>
  29. <!-- 拉黑确认弹窗 -->
  30. <view v-if="showBlockConfirmModal" class="modal-mask" @click="closeBlockConfirm">
  31. <view class="confirm-modal" @click.stop>
  32. <view class="confirm-title">确认拉黑</view>
  33. <view class="confirm-content">
  34. <text>拉黑后将无法接收该用户的消息,是否确定?</text>
  35. </view>
  36. <view class="confirm-buttons">
  37. <button class="confirm-btn cancel" @click="closeBlockConfirm">取消</button>
  38. <button class="confirm-btn confirm" @click="confirmBlockFriend">确认</button>
  39. </view>
  40. </view>
  41. </view>
  42. <!-- 顶部导航 -->
  43. <view class="chat-header">
  44. <view class="header-left" @click="goBack">
  45. <text class="icon-back">←</text>
  46. </view>
  47. <view class="header-center">
  48. <text class="chat-title">{{ targetUserName }}</text>
  49. <text class="online-status" :class="{ online: isTargetOnline }">
  50. {{ isTargetOnline ? '在线' : '离线' }}
  51. </text>
  52. </view>
  53. <view class="header-right" @click="showMoreOptions">
  54. <text class="icon-more">⋯</text>
  55. </view>
  56. </view>
  57. <!-- 消息列表 -->
  58. <scroll-view
  59. class="message-list"
  60. scroll-y
  61. :scroll-into-view="scrollToView"
  62. @scrolltoupper="loadMoreMessages">
  63. <!-- 加载更多提示 -->
  64. <view v-if="loading" class="loading-tip">加载中...</view>
  65. <view v-else-if="noMore" class="loading-tip">没有更多消息了</view>
  66. <!-- 时间分组和消息项 -->
  67. <view v-for="(msg, index) in messages" :key="msg.messageId">
  68. <!-- 时间分隔线 (每5分钟显示一次) -->
  69. <view v-if="shouldShowTime(msg, index)" class="time-divider">
  70. <text class="time-text">{{ formatMessageTime(msg.sendTime) }}</text>
  71. </view>
  72. <!-- 消息项 -->
  73. <view
  74. :id="'msg-' + index"
  75. class="message-item"
  76. :class="{ 'message-self': msg.fromUserId === userId }"
  77. @longpress="showMessageMenu(msg, index)">
  78. <!-- 头像 -->
  79. <image
  80. class="avatar"
  81. :src="msg.fromUserId === userId ? userAvatar : targetUserAvatar"
  82. mode="aspectFill" />
  83. <!-- 消息内容 -->
  84. <view class="message-content-wrapper">
  85. <!-- 用户名(对方消息时显示) -->
  86. <text v-if="msg.fromUserId !== userId" class="message-name">
  87. {{ msg.fromUserName }}
  88. </text>
  89. <!-- 消息气泡 -->
  90. <view
  91. class="message-bubble"
  92. :class="{ 'bubble-self': msg.fromUserId === userId, 'bubble-failed': msg.sendStatus === 4 }"
  93. @click="handleMessageClick(msg)">
  94. <!-- 文本消息 -->
  95. <text v-if="msg.messageType === 1" class="message-text">
  96. {{ msg.content }}
  97. </text>
  98. <!-- 图片消息 -->
  99. <image
  100. v-else-if="msg.messageType === 2"
  101. class="message-image"
  102. :src="msg.mediaUrl"
  103. mode="widthFix"
  104. lazy-load
  105. @click.stop="previewImage(msg.mediaUrl)" />
  106. <!-- 语音消息 -->
  107. <view v-else-if="msg.messageType === 3" class="message-voice" @click.stop="playVoice(msg)">
  108. <text>🔊</text>
  109. <text>{{ msg.duration }}"</text>
  110. </view>
  111. <!-- 视频消息 -->
  112. <video
  113. v-else-if="msg.messageType === 4"
  114. class="message-video"
  115. :src="msg.mediaUrl"
  116. controls />
  117. <!-- 撤回消息 -->
  118. <text v-if="msg.isRecalled" class="message-recalled">
  119. 消息已撤回
  120. </text>
  121. </view>
  122. <!-- 消息状态(自己的消息) -->
  123. <view v-if="msg.fromUserId === userId" class="message-status">
  124. <text v-if="msg.sendStatus === 1" class="sending">发送中...</text>
  125. <text v-else-if="msg.sendStatus === 2">已送达</text>
  126. <text v-else-if="msg.sendStatus === 3" class="read">已读</text>
  127. <view v-else-if="msg.sendStatus === 4" class="failed-group">
  128. <text class="failed">发送失败</text>
  129. <text class="retry-btn" @click.stop="retryMessage(msg)">重试</text>
  130. </view>
  131. </view>
  132. </view>
  133. </view>
  134. </view>
  135. </scroll-view>
  136. <!-- 新增:消息发送限制提示 -->
  137. <view class="message-limit-tip">
  138. <!-- 同时判断isVip和hasMessageLimit,增强可靠性 -->
  139. <text v-if="isVip || !hasMessageLimit" class="vip-tip">✨ VIP特权:无发送次数限制</text>
  140. <text v-else class="limit-tip">
  141. 今日剩余可发送消息:{{ Math.max(remainingCount, 0) }} 条<text class="vip-link" @click="goToVipPage">(非VIP每日限5条)</text>
  142. </text>
  143. </view>
  144. <!-- 输入框 -->
  145. <view class="input-bar">
  146. <!-- 语音按钮 -->
  147. <view class="input-icon" @click="switchInputType">
  148. <text>{{ inputType === 'text' ? '🎤' : '⌨️' }}</text>
  149. </view>
  150. <!-- 文本输入 -->
  151. <input
  152. v-if="inputType === 'text'"
  153. class="input-field"
  154. v-model="inputText"
  155. placeholder="说点什么..."
  156. confirm-type="send"
  157. @confirm="sendTextMessage"
  158. @input="onInputChange" />
  159. <!-- 语音按钮 -->
  160. <button
  161. v-else
  162. class="voice-button"
  163. @touchstart="startVoiceRecord"
  164. @touchend="stopVoiceRecord">
  165. 按住说话
  166. </button>
  167. <!-- 表情按钮 -->
  168. <view class="input-icon" @click="showEmojiPanel = !showEmojiPanel">
  169. <text>😊</text>
  170. </view>
  171. <!-- 更多按钮 -->
  172. <view class="input-icon" @click="showMorePanel = !showMorePanel">
  173. <text>➕</text>
  174. </view>
  175. </view>
  176. <!-- 表情面板 -->
  177. <view v-if="showEmojiPanel" class="emoji-panel">
  178. <text
  179. v-for="emoji in emojis"
  180. :key="emoji"
  181. class="emoji-item"
  182. @click="insertEmoji(emoji)">
  183. {{ emoji }}
  184. </text>
  185. </view>
  186. <!-- 更多功能面板 -->
  187. <view v-if="showMorePanel" class="more-panel">
  188. <view class="more-item" @click="chooseImage">
  189. <view class="more-icon">🖼️</view>
  190. <text class="more-text">图片</text>
  191. </view>
  192. <view class="more-item" @click="chooseVideo">
  193. <view class="more-icon">📹</view>
  194. <text class="more-text">视频</text>
  195. </view>
  196. <view class="more-item" @click="chooseFile">
  197. <view class="more-icon">📁</view>
  198. <text class="more-text">文件</text>
  199. </view>
  200. </view>
  201. <!-- 消息操作菜单 -->
  202. <view v-if="showMessageAction" class="message-action-mask" @click="hideMessageMenu">
  203. <view class="message-action-menu" @click.stop>
  204. <view class="menu-item" @click="copyMessage" v-if="selectedMessage && selectedMessage.messageType === 1">
  205. <text class="menu-icon">📋</text>
  206. <text>复制</text>
  207. </view>
  208. <view class="menu-item" @click="recallMessage" v-if="selectedMessage && selectedMessage.fromUserId === userId && canRecall(selectedMessage)">
  209. <text class="menu-icon">↩️</text>
  210. <text>撤回</text>
  211. </view>
  212. <view class="menu-item" @click="deleteMessage">
  213. <text class="menu-icon">🗑️</text>
  214. <text>删除</text>
  215. </view>
  216. <view class="menu-item cancel" @click="hideMessageMenu">
  217. <text>取消</text>
  218. </view>
  219. </view>
  220. </view>
  221. </view>
  222. </template>
  223. <script>
  224. import timManager from '@/utils/tim-manager.js';
  225. import TIM from 'tim-wx-sdk';
  226. export default {
  227. data() {
  228. return {
  229. isBlockedByTarget: false,
  230. userId: null,
  231. userAvatar: '',
  232. targetUserId: null,
  233. targetUserName: '',
  234. targetUserAvatar: '',
  235. messages: [],
  236. inputText: '',
  237. inputType: 'text',
  238. conversationID: '',
  239. scrollToView: '',
  240. showEmojiPanel: false,
  241. showMorePanel: false,
  242. isLogin: false,
  243. // 消息操作菜单
  244. showMessageAction: false,
  245. selectedMessage: null,
  246. selectedMessageIndex: -1,
  247. menuTop: 0,
  248. // 加载更多
  249. loading: false,
  250. noMore: false,
  251. nextReqMessageID: '',
  252. isTargetOnline: false,
  253. emojis: ['😀', '😃', '😄', '😁', '😆', '😅', '😂', '🤣', '😊', '😇', '🙂', '🙃', '😉', '😌', '😍', '🥰', '😘', '😗', '😙', '😚', '😋', '😛', '😝', '😜', '🤪', '🤨', '🧐', '🤓', '😎', '🤩', '🥳'],
  254. showMoreOptionsModal: false, // 控制更多选项弹窗显示
  255. showBlockConfirmModal: false, // 控制拉黑确认弹窗显示
  256. isVip: false, // 是否VIP用户
  257. remainingCount: 5, // 剩余可发送消息数(非VIP默认5)
  258. hasMessageLimit: true // 是否有发送限制(VIP为false)
  259. };
  260. },
  261. async onLoad(options) {
  262. console.log('=== 聊天页面加载 ===');
  263. // 严格验证登录状态
  264. const token = uni.getStorageSync('token');
  265. const userInfo = uni.getStorageSync('userInfo');
  266. const storedUserId = uni.getStorageSync('userId');
  267. console.log('登录状态检查:');
  268. console.log('- token:', token ? '存在' : '不存在');
  269. console.log('- userInfo:', userInfo);
  270. console.log('- storedUserId:', storedUserId);
  271. if (!token || !userInfo) {
  272. console.error('❌ 未登录或登录信息不完整');
  273. uni.showModal({
  274. title: '需要登录',
  275. content: '请先登录后再进行聊天',
  276. showCancel: false,
  277. success: () => {
  278. uni.reLaunch({
  279. url: '/pages/page3/page3'
  280. });
  281. }
  282. });
  283. return;
  284. }
  285. // 优先使用 storage 中的 userId,确保一致性
  286. let rawUserId = storedUserId || userInfo.userId || userInfo.id || userInfo.user_id;
  287. // 转换为数字类型(确保与消息列表页面一致)
  288. if (typeof rawUserId === 'string') {
  289. rawUserId = parseInt(rawUserId);
  290. }
  291. if (!rawUserId || isNaN(rawUserId)) {
  292. console.error('❌ 无法获取有效的用户ID');
  293. uni.showModal({
  294. title: '用户信息错误',
  295. content: '无法获取用户ID,请重新登录',
  296. showCancel: false,
  297. success: () => {
  298. uni.removeStorageSync('token');
  299. uni.removeStorageSync('userInfo');
  300. uni.removeStorageSync('userId');
  301. uni.reLaunch({
  302. url: '/pages/page3/page3'
  303. });
  304. }
  305. });
  306. return;
  307. }
  308. // 保存用户ID(TIM需要字符串格式)
  309. this.userId = String(rawUserId);
  310. this.userAvatar = userInfo.avatar || userInfo.avatarUrl || '/static/default-avatar.svg';
  311. // 获取对方用户信息(确保是字符串格式)
  312. this.targetUserId = String(options.targetUserId);
  313. this.targetUserName = decodeURIComponent(options.targetUserName || '用户');
  314. this.targetUserAvatar = decodeURIComponent(options.targetUserAvatar || '/static/default-avatar.svg');
  315. // 生成会话 ID
  316. this.conversationID = `C2C${this.targetUserId}`;
  317. console.log('✅ 聊天页面初始化成功:');
  318. console.log(' - 当前用户ID:', rawUserId, '(TIM格式:', this.userId, ')');
  319. console.log(' - 对方用户ID:', this.targetUserId);
  320. console.log(' - 会话ID:', this.conversationID);
  321. // 初始化 TIM
  322. await this.initTIM();
  323. // 获取用户消息发送限制(VIP状态+剩余次数)
  324. await this.getUserMessageLimit();
  325. // 等待 SDK Ready 后再加载消息
  326. await this.waitForSDKReady();
  327. // 先检查拉黑状态
  328. this.isBlockedByTarget = await this.checkIsBlockedByTarget();
  329. if (this.isBlockedByTarget) {
  330. uni.showToast({
  331. title: '你已被对方拉黑,无法发送消息',
  332. icon: 'none',
  333. duration: 3000
  334. });
  335. }
  336. // 加载历史消息
  337. await this.loadMessages();
  338. // 监听新消息
  339. this.listenMessages();
  340. },
  341. onUnload() {
  342. // 页面卸载时移除监听
  343. timManager.offMessage(this.handleNewMessage);
  344. },
  345. methods: {
  346. /**
  347. * 初始化 TIM
  348. */
  349. async initTIM() {
  350. try {
  351. // 如果未初始化,先初始化
  352. if (!timManager.tim) {
  353. timManager.init(1600109674); // ✅ 已更新为正确的 SDKAppID
  354. }
  355. // 如果未登录,获取 userSig 并登录
  356. if (!timManager.isLogin) {
  357. // 先导入当前用户和目标用户到腾讯云IM
  358. await this.importUsers();
  359. // 从后端获取 userSig
  360. const userSig = await this.getUserSig();
  361. await timManager.login(this.userId, userSig);
  362. }
  363. this.isLogin = true;
  364. console.log('✅ TIM 初始化完成');
  365. } catch (error) {
  366. console.error('❌ TIM 初始化失败:', error);
  367. uni.showToast({
  368. title: '连接失败,请重试',
  369. icon: 'none'
  370. });
  371. }
  372. },
  373. /**
  374. * 跳转到VIP页面
  375. */
  376. goToVipPage() {
  377. console.log('点击跳转VIP页面');
  378. // 替换为你的实际VIP页面路径(例如会员开通页面)
  379. uni.navigateTo({
  380. url: '/pages/vip/index', // 请根据项目实际路径修改
  381. success: () => {
  382. console.log('跳转VIP页面成功');
  383. },
  384. fail: (err) => {
  385. console.error('跳转VIP页面失败:', err);
  386. uni.showToast({
  387. title: 'VIP页面不存在',
  388. icon: 'none'
  389. });
  390. }
  391. });
  392. },
  393. more(userid) {
  394. console.log('点击了更多按钮,开始跳转...', userid);
  395. // 如果目标页面是普通页面,用navigateTo(保留当前页面);如果是tabbar页面,用switchTab
  396. uni.navigateTo({
  397. url: `/pages/message/more?userid=${userid}`,
  398. success: () => {
  399. console.log('跳转成功');
  400. },
  401. fail: (err) => {
  402. console.error('跳转失败:', err);
  403. uni.showToast({
  404. title: '页面不存在或路径错误',
  405. icon: 'none'
  406. });
  407. }
  408. });
  409. },
  410. /**
  411. * 导入用户到腾讯云IM
  412. */
  413. async importUsers() {
  414. try {
  415. console.log('📥 开始导入用户到腾讯云IM...');
  416. console.log(' - 当前用户ID:', this.userId, '(类型:', typeof this.userId, ')');
  417. console.log(' - 目标用户ID:', this.targetUserId, '(类型:', typeof this.targetUserId, ')');
  418. // 验证用户ID
  419. if (!this.userId || this.userId === 'undefined' || this.userId === 'null') {
  420. throw new Error('当前用户ID无效: ' + this.userId);
  421. }
  422. if (!this.targetUserId || this.targetUserId === 'undefined' || this.targetUserId === 'null') {
  423. throw new Error('目标用户ID无效: ' + this.targetUserId);
  424. }
  425. // 导入当前用户(确保userId是字符串)
  426. const currentUserRes = await uni.request({
  427. url: 'http://localhost:1004/api/im/importUser',
  428. method: 'POST',
  429. data: {
  430. userId: String(this.userId),
  431. nickname: '用户' + this.userId
  432. },
  433. header: {
  434. 'Content-Type': 'application/json'
  435. }
  436. });
  437. console.log(' - 当前用户导入结果:', currentUserRes[1].data);
  438. // 导入目标用户(确保userId是字符串)
  439. const targetUserRes = await uni.request({
  440. url: 'http://localhost:1004/api/im/importUser',
  441. method: 'POST',
  442. data: {
  443. userId: String(this.targetUserId),
  444. nickname: this.targetUserName || '用户' + this.targetUserId
  445. },
  446. header: {
  447. 'Content-Type': 'application/json'
  448. }
  449. });
  450. console.log(' - 目标用户导入结果:', targetUserRes[1].data);
  451. console.log('✅ 用户导入成功');
  452. } catch (error) {
  453. console.log('⚠️ 用户导入失败(可能已存在):', error);
  454. // 导入失败不影响登录,因为用户可能已经存在
  455. }
  456. },
  457. /**
  458. * 获取 UserSig
  459. */
  460. async getUserSig() {
  461. try {
  462. const [err, res] = await uni.request({
  463. url: 'http://localhost:1004/api/im/getUserSig',
  464. method: 'GET',
  465. data: {
  466. userId: this.userId
  467. }
  468. });
  469. if (err) {
  470. throw new Error('请求失败');
  471. }
  472. if (res.data && res.data.code === 200) {
  473. return res.data.data.userSig;
  474. } else {
  475. throw new Error('获取 UserSig 失败');
  476. }
  477. } catch (error) {
  478. console.error('❌ 获取 UserSig 失败:', error);
  479. throw error;
  480. }
  481. },
  482. /**
  483. * 等待 SDK Ready
  484. */
  485. async waitForSDKReady() {
  486. return new Promise((resolve) => {
  487. // 如果已经 ready,立即返回
  488. if (timManager.isLogin) {
  489. console.log('✅ SDK 已就绪');
  490. resolve();
  491. return;
  492. }
  493. // 否则等待 SDK ready 事件
  494. console.log('⏳ 等待 SDK 就绪...');
  495. const checkReady = setInterval(() => {
  496. if (timManager.isLogin) {
  497. console.log('✅ SDK 已就绪');
  498. clearInterval(checkReady);
  499. resolve();
  500. }
  501. }, 100); // 每 100ms 检查一次
  502. // 超时保护(10秒后强制继续)
  503. setTimeout(() => {
  504. console.log('⚠️ 等待 SDK 就绪超时,继续执行');
  505. clearInterval(checkReady);
  506. resolve();
  507. }, 10000);
  508. });
  509. },
  510. /**
  511. * 加载历史消息
  512. */
  513. async loadMessages() {
  514. try {
  515. const res = await timManager.tim.getMessageList({
  516. conversationID: this.conversationID,
  517. count: 20
  518. });
  519. const messageList = res.data.messageList;
  520. this.nextReqMessageID = res.data.nextReqMessageID;
  521. this.noMore = !res.data.isCompleted;
  522. // 转换为我们的消息格式
  523. this.messages = messageList.map(msg => this.convertMessage(msg));
  524. // 滚动到底部
  525. this.$nextTick(() => {
  526. this.scrollToBottom();
  527. });
  528. // 标记已读
  529. await timManager.setMessageRead(this.conversationID);
  530. } catch (error) {
  531. console.error('❌ 加载消息失败:', error);
  532. }
  533. },
  534. /**
  535. * 加载更多消息(上拉)
  536. */
  537. async loadMoreMessages() {
  538. if (this.loading || !this.nextReqMessageID) {
  539. return;
  540. }
  541. this.loading = true;
  542. try {
  543. const res = await timManager.tim.getMessageList({
  544. conversationID: this.conversationID,
  545. nextReqMessageID: this.nextReqMessageID,
  546. count: 20
  547. });
  548. const messageList = res.data.messageList;
  549. this.nextReqMessageID = res.data.nextReqMessageID;
  550. this.noMore = !res.data.isCompleted;
  551. // 转换并添加到消息列表前面
  552. const newMessages = messageList.map(msg => this.convertMessage(msg));
  553. this.messages = [...newMessages, ...this.messages];
  554. } catch (error) {
  555. console.error('❌ 加载更多消息失败:', error);
  556. } finally {
  557. this.loading = false;
  558. }
  559. },
  560. /**
  561. * 监听新消息
  562. */
  563. listenMessages() {
  564. const handleNewMessage = (event) => {
  565. // 兼容不同格式的事件数据
  566. const messageList = event.data || event || [];
  567. // 确保是数组格式
  568. const messagesToProcess = Array.isArray(messageList) ? messageList : [messageList];
  569. messagesToProcess.forEach(msg => {
  570. // 只处理当前会话的消息
  571. if (msg.conversationID === this.conversationID) {
  572. // 查找消息在本地列表中的位置
  573. const existingIndex = this.messages.findIndex(m => m.messageId === msg.ID);
  574. if (existingIndex > -1) {
  575. // 更新现有消息状态(使用$set确保视图更新)
  576. this.$set(this.messages, existingIndex, this.convertMessage(msg));
  577. } else {
  578. // 添加新消息
  579. this.messages.push(this.convertMessage(msg));
  580. this.$nextTick(() => {
  581. this.scrollToBottom();
  582. });
  583. }
  584. // 标记已读
  585. timManager.setMessageRead(this.conversationID);
  586. }
  587. });
  588. };
  589. this.handleNewMessage = handleNewMessage;
  590. timManager.onMessage(handleNewMessage);
  591. // 添加消息状态变更监听
  592. if (timManager.tim) {
  593. timManager.tim.on(TIM.EVENT.MESSAGE_STATUS_CHANGED, handleNewMessage);
  594. }
  595. },
  596. /**
  597. * 转换消息格式
  598. */
  599. convertMessage(timMsg) {
  600. let sendStatus = 1; // 默认发送中
  601. // 完善的状态判断逻辑
  602. if (timMsg.status === TIM.TYPES.MSG_STATUS_SEND_SUCC ||
  603. timMsg.status === 'success' ||
  604. timMsg.status === TIM.TYPES.MSG_STATUS_RECEIVED) {
  605. sendStatus = 2; // 已送达
  606. } else if (timMsg.status === TIM.TYPES.MSG_STATUS_SEND_FAIL ||
  607. timMsg.status === 'fail') {
  608. sendStatus = 4; // 发送失败
  609. } else if (timMsg.status === TIM.TYPES.MSG_STATUS_HAS_READ ||
  610. timMsg.status === 'read') {
  611. sendStatus = 3; // 已读
  612. } else if (timMsg.status === TIM.TYPES.MSG_STATUS_SENDING) {
  613. sendStatus = 1; // 发送中
  614. }
  615. return {
  616. messageId: timMsg.ID,
  617. fromUserId: timMsg.from,
  618. toUserId: timMsg.to,
  619. messageType: timMsg.type === TIM.TYPES.MSG_TEXT ? 1 :
  620. timMsg.type === TIM.TYPES.MSG_IMAGE ? 2 :
  621. timMsg.type === TIM.TYPES.MSG_SOUND ? 3 :
  622. timMsg.type === TIM.TYPES.MSG_VIDEO ? 4 : 1,
  623. content: timMsg.type === TIM.TYPES.MSG_TEXT ? timMsg.payload.text : '[图片]',
  624. mediaUrl: timMsg.type === TIM.TYPES.MSG_IMAGE ? timMsg.payload.imageInfoArray?.[0]?.url : '',
  625. sendStatus: sendStatus,
  626. sendTime: new Date(timMsg.time * 1000),
  627. isRecalled: timMsg.isRevoked,
  628. fromUserName: timMsg.from === this.userId ? '我' : this.targetUserName
  629. };
  630. },
  631. /**
  632. * 检查对方是否拉黑自己
  633. */
  634. async checkIsBlockedByTarget() {
  635. try {
  636. const [err, res] = await uni.request({
  637. url: 'http://localhost:8083/api/chatfriend/checkBlock',
  638. method: 'POST',
  639. data: {
  640. userId: this.userId, // 自己的ID
  641. targetUserId: this.targetUserId // 对方的ID
  642. },
  643. header: {
  644. 'Content-Type': 'application/json'
  645. }
  646. });
  647. console.log('拉黑检查接口响应:', res.data); // 方便调试
  648. if (err) {
  649. console.error('网络请求失败:', err);
  650. return false; // 网络错误时默认按“未被拉黑”处理(避免误拦截)
  651. }
  652. // 严格校验接口返回格式
  653. if (!res.data || res.data.code !== 200) {
  654. console.error('接口返回格式错误:', res.data);
  655. return false;
  656. }
  657. // 关键修复:后端返回 data:true 表示“已被拉黑”,直接返回该值
  658. // 你的接口中 data 就是布尔值,无需额外解析
  659. const isBlocked = res.data.data;
  660. console.log('是否被拉黑:', isBlocked); // 确认这里输出为 true(被拉黑时)
  661. return isBlocked;
  662. } catch (error) {
  663. console.error('检查拉黑状态失败:', error);
  664. return false;
  665. }
  666. },
  667. /**
  668. * 发送文本消息
  669. */
  670. async sendTextMessage() {
  671. if (this.hasMessageLimit && this.remainingCount <= 0) {
  672. uni.showToast({
  673. title: '今日消息发送次数已用完,开通VIP无限制',
  674. icon: 'none',
  675. duration: 2000
  676. });
  677. return;
  678. }
  679. if (!this.inputText.trim()) {
  680. return;
  681. }
  682. const content = this.inputText;
  683. this.inputText = '';
  684. // 先检查是否被拉黑
  685. const isBlocked = await this.checkIsBlockedByTarget();
  686. if (isBlocked) {
  687. // 被拉黑时的处理保持不变
  688. const failedMessage = {
  689. messageId: 'failed_' + Date.now(),
  690. fromUserId: this.userId,
  691. toUserId: this.targetUserId,
  692. messageType: 1,
  693. content: content,
  694. sendStatus: 4, // 4表示发送失败
  695. sendTime: new Date(),
  696. fromUserName: '我'
  697. };
  698. this.messages.push(failedMessage);
  699. this.scrollToBottom();
  700. uni.showToast({
  701. title: '消息发送失败',
  702. icon: 'none'
  703. });
  704. return;
  705. }
  706. // 创建临时消息显示"发送中"
  707. const tempMessageId = 'temp_' + Date.now();
  708. const tempMessage = {
  709. messageId: tempMessageId,
  710. fromUserId: this.userId,
  711. toUserId: this.targetUserId,
  712. messageType: 1,
  713. content: content,
  714. sendStatus: 1, // 发送中
  715. sendTime: new Date(),
  716. fromUserName: '我'
  717. };
  718. this.messages.push(tempMessage);
  719. this.scrollToBottom();
  720. // 未被拉黑,正常发送
  721. try {
  722. const sendPromise = timManager.sendTextMessage(this.targetUserId, content);
  723. const timeoutPromise = new Promise((_, reject) => {
  724. setTimeout(() => reject(new Error('发送超时')), 15000);
  725. });
  726. const message = await Promise.race([sendPromise, timeoutPromise]);
  727. // 替换临时消息
  728. const tempIndex = this.messages.findIndex(m => m.messageId === tempMessageId);
  729. if (tempIndex > -1) {
  730. const convertedMsg = this.convertMessage(message);
  731. // 强制设置为已送达
  732. convertedMsg.sendStatus = 2;
  733. this.$set(this.messages, tempIndex, convertedMsg);
  734. }
  735. console.log('✅ 消息发送成功');
  736. this.syncMessageToMySQL(message);
  737. if (!this.isVip) {
  738. await this.updateMessageCount();
  739. }
  740. } catch (error) {
  741. console.error('❌ 消息发送失败:', error);
  742. // 更新临时消息为失败状态
  743. const tempIndex = this.messages.findIndex(m => m.messageId === tempMessageId);
  744. if (tempIndex > -1) {
  745. this.$set(this.messages[tempIndex], 'sendStatus', 4);
  746. }
  747. // 恢复输入框内容
  748. this.inputText = content;
  749. uni.showToast({
  750. title: '发送失败: ' + error.message,
  751. icon: 'none'
  752. });
  753. }
  754. },
  755. /**
  756. * 选择图片
  757. */
  758. chooseImage() {
  759. uni.chooseImage({
  760. count: 1,
  761. sizeType: ['compressed'],
  762. sourceType: ['album', 'camera'],
  763. success: async (res) => {
  764. // 1. 先检查是否被拉黑
  765. const isBlocked = await this.checkIsBlockedByTarget();
  766. if (isBlocked) {
  767. uni.showToast({
  768. title: '你已被对方拉黑,无法发送消息',
  769. icon: 'none'
  770. });
  771. return;
  772. }
  773. const tempFilePath = res.tempFilePaths[0];
  774. try {
  775. uni.showLoading({ title: '发送中...' });
  776. const message = await timManager.sendImageMessage(this.targetUserId, tempFilePath);
  777. this.messages.push(this.convertMessage(message));
  778. this.scrollToBottom();
  779. uni.hideLoading();
  780. console.log('✅ 图片发送成功');
  781. } catch (error) {
  782. uni.hideLoading();
  783. console.error('❌ 图片发送失败:', error);
  784. uni.showToast({
  785. title: '发送失败',
  786. icon: 'none'
  787. });
  788. }
  789. }
  790. });
  791. this.showMorePanel = false;
  792. },
  793. /**
  794. * 输入框内容变化
  795. */
  796. onInputChange() {
  797. // 腾讯云 IM 可以实现正在输入状态,这里暂时省略
  798. console.log('输入中...');
  799. },
  800. /**
  801. * 同步消息到MySQL数据库(双重存储保障)
  802. */
  803. async syncMessageToMySQL(timMessage) {
  804. try {
  805. console.log('🔄 同步消息到MySQL...', timMessage.ID);
  806. // 构建同步参数
  807. const syncData = {
  808. messageId: timMessage.ID,
  809. fromUserId: timMessage.from,
  810. toUserId: timMessage.to,
  811. messageType: this.getMessageType(timMessage),
  812. content: this.getMessageContent(timMessage),
  813. sendTime: timMessage.time // TIM返回的是秒级时间戳
  814. };
  815. // 如果是图片消息,添加媒体信息
  816. if (timMessage.type === 'TIMImageElem' && timMessage.payload.imageInfoArray) {
  817. const imageInfo = timMessage.payload.imageInfoArray[0];
  818. syncData.mediaUrl = imageInfo.imageUrl;
  819. syncData.thumbnailUrl = imageInfo.imageUrl;
  820. }
  821. // 调用后端同步接口
  822. const res = await uni.request({
  823. url: 'http://localhost:1004/api/chat/syncTIMMessage',
  824. method: 'POST',
  825. data: syncData,
  826. header: {
  827. 'Content-Type': 'application/json'
  828. }
  829. });
  830. if (res[1].data.code === 200) {
  831. console.log('✅ 消息已同步到MySQL:', timMessage.ID);
  832. } else {
  833. console.warn('⚠️ 消息同步失败:', res[1].data.message);
  834. }
  835. } catch (error) {
  836. console.error('❌ 同步消息到MySQL失败:', error);
  837. // 同步失败不影响聊天功能,只记录日志
  838. }
  839. },
  840. /**
  841. * 获取消息类型
  842. */
  843. getMessageType(timMessage) {
  844. const typeMap = {
  845. 'TIMTextElem': 1, // 文本
  846. 'TIMImageElem': 2, // 图片
  847. 'TIMSoundElem': 3, // 语音
  848. 'TIMVideoFileElem': 4, // 视频
  849. 'TIMFileElem': 5 // 文件
  850. };
  851. return typeMap[timMessage.type] || 1;
  852. },
  853. /**
  854. * 获取消息内容
  855. */
  856. getMessageContent(timMessage) {
  857. switch (timMessage.type) {
  858. case 'TIMTextElem':
  859. return timMessage.payload.text || '';
  860. case 'TIMImageElem':
  861. return '[图片]';
  862. case 'TIMSoundElem':
  863. return '[语音]';
  864. case 'TIMVideoFileElem':
  865. return '[视频]';
  866. case 'TIMFileElem':
  867. return '[文件]';
  868. default:
  869. return '[未知消息]';
  870. }
  871. },
  872. /**
  873. * 滚动到底部
  874. */
  875. scrollToBottom() {
  876. this.$nextTick(() => {
  877. const lastIndex = this.messages.length - 1;
  878. this.scrollToView = 'msg-' + lastIndex;
  879. });
  880. },
  881. /**
  882. * 判断是否显示时间分隔线
  883. */
  884. shouldShowTime(msg, index) {
  885. if (index === 0) return true;
  886. const prevMsg = this.messages[index - 1];
  887. const timeDiff = new Date(msg.sendTime) - new Date(prevMsg.sendTime);
  888. // 超过5分钟显示时间
  889. return timeDiff > 5 * 60 * 1000;
  890. },
  891. /**
  892. * 格式化消息时间(用于时间分隔线)
  893. */
  894. formatMessageTime(time) {
  895. const date = new Date(time);
  896. const now = new Date();
  897. const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
  898. const yesterday = new Date(today - 86400000);
  899. // 今天
  900. if (date >= today) {
  901. return date.toLocaleTimeString('zh-CN', {
  902. hour: '2-digit',
  903. minute: '2-digit'
  904. });
  905. }
  906. // 昨天
  907. if (date >= yesterday) {
  908. return '昨天 ' + date.toLocaleTimeString('zh-CN', {
  909. hour: '2-digit',
  910. minute: '2-digit'
  911. });
  912. }
  913. // 本周
  914. if (date > new Date(now - 7 * 86400000)) {
  915. const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
  916. return days[date.getDay()] + ' ' + date.toLocaleTimeString('zh-CN', {
  917. hour: '2-digit',
  918. minute: '2-digit'
  919. });
  920. }
  921. // 更早
  922. return date.toLocaleString('zh-CN', {
  923. month: '2-digit',
  924. day: '2-digit',
  925. hour: '2-digit',
  926. minute: '2-digit'
  927. });
  928. },
  929. /**
  930. * 格式化时间(消息状态用)
  931. */
  932. formatTime(time) {
  933. const date = new Date(time);
  934. const now = new Date();
  935. const diff = now - date;
  936. if (diff < 60000) {
  937. return '刚刚';
  938. } else if (diff < 3600000) {
  939. return Math.floor(diff / 60000) + '分钟前';
  940. } else if (diff < 86400000) {
  941. return Math.floor(diff / 3600000) + '小时前';
  942. } else {
  943. return date.toLocaleString('zh-CN', {
  944. month: '2-digit',
  945. day: '2-digit',
  946. hour: '2-digit',
  947. minute: '2-digit'
  948. });
  949. }
  950. },
  951. /**
  952. * 预览图片
  953. */
  954. previewImage(url) {
  955. uni.previewImage({
  956. urls: [url],
  957. current: url
  958. });
  959. },
  960. /**
  961. * 返回
  962. */
  963. goBack() {
  964. uni.navigateBack({
  965. success: () => {
  966. // 通知消息列表页面刷新
  967. uni.$emit('refreshConversations');
  968. }
  969. });
  970. },
  971. /**
  972. * 显示消息操作菜单
  973. */
  974. showMessageMenu(msg, index) {
  975. this.selectedMessage = msg;
  976. this.selectedMessageIndex = index;
  977. this.showMessageAction = true;
  978. // 计算菜单位置
  979. uni.createSelectorQuery().select('.message-item').boundingClientRect(rect => {
  980. if (rect) {
  981. this.menuTop = rect.top + rect.height;
  982. }
  983. }).exec();
  984. },
  985. /**
  986. * 隐藏消息操作菜单
  987. */
  988. hideMessageMenu() {
  989. this.showMessageAction = false;
  990. this.selectedMessage = null;
  991. this.selectedMessageIndex = -1;
  992. },
  993. /**
  994. * 复制消息
  995. */
  996. copyMessage() {
  997. if (!this.selectedMessage || this.selectedMessage.messageType !== 1) {
  998. return;
  999. }
  1000. uni.setClipboardData({
  1001. data: this.selectedMessage.content,
  1002. success: () => {
  1003. uni.showToast({
  1004. title: '已复制',
  1005. icon: 'success'
  1006. });
  1007. }
  1008. });
  1009. this.hideMessageMenu();
  1010. },
  1011. /**
  1012. * 判断是否可以撤回
  1013. */
  1014. canRecall(msg) {
  1015. const diff = Date.now() - new Date(msg.sendTime).getTime();
  1016. return diff < 2 * 60 * 1000; // 2分钟内可撤回
  1017. },
  1018. /**
  1019. * 撤回消息
  1020. */
  1021. async recallMessage() {
  1022. if (!this.selectedMessage) {
  1023. return;
  1024. }
  1025. try {
  1026. // 查找TIM消息对象
  1027. const timMessage = await timManager.tim.findMessage(this.selectedMessage.messageId);
  1028. if (timMessage) {
  1029. await timManager.revokeMessage(timMessage);
  1030. // 更新本地消息状态
  1031. this.selectedMessage.isRecalled = true;
  1032. this.selectedMessage.content = '你撤回了一条消息';
  1033. uni.showToast({
  1034. title: '已撤回',
  1035. icon: 'success'
  1036. });
  1037. }
  1038. } catch (error) {
  1039. console.error('撤回失败:', error);
  1040. uni.showToast({
  1041. title: '撤回失败',
  1042. icon: 'none'
  1043. });
  1044. }
  1045. this.hideMessageMenu();
  1046. },
  1047. /**
  1048. * 删除消息
  1049. */
  1050. deleteMessage() {
  1051. if (!this.selectedMessage) {
  1052. return;
  1053. }
  1054. uni.showModal({
  1055. title: '确认删除',
  1056. content: '确定要删除这条消息吗?',
  1057. success: (res) => {
  1058. if (res.confirm) {
  1059. // 从列表中删除
  1060. this.messages.splice(this.selectedMessageIndex, 1);
  1061. uni.showToast({
  1062. title: '已删除',
  1063. icon: 'success'
  1064. });
  1065. }
  1066. }
  1067. });
  1068. this.hideMessageMenu();
  1069. },
  1070. /**
  1071. * 处理消息点击
  1072. */
  1073. handleMessageClick(msg) {
  1074. // 如果是发送失败的消息,提示重试
  1075. if (msg.sendStatus === 4) {
  1076. uni.showModal({
  1077. title: '发送失败',
  1078. content: '消息发送失败,是否重试?',
  1079. success: (res) => {
  1080. if (res.confirm) {
  1081. this.retryMessage(msg);
  1082. }
  1083. }
  1084. });
  1085. }
  1086. },
  1087. /**
  1088. * 重试发送消息
  1089. */
  1090. async retryMessage(msg) {
  1091. if (msg.messageType !== 1) {
  1092. uni.showToast({ title: '暂不支持重发该类型消息', icon: 'none' });
  1093. return;
  1094. }
  1095. const isBlocked = await this.checkIsBlockedByTarget();
  1096. if (isBlocked) {
  1097. const index = this.messages.findIndex(m => m.messageId === msg.messageId);
  1098. if (index > -1) {
  1099. this.$set(this.messages[index], 'sendStatus', 4);
  1100. }
  1101. uni.showToast({ title: '对方已拉黑你,无法发送', icon: 'none' });
  1102. return;
  1103. }
  1104. try {
  1105. const index = this.messages.findIndex(m => m.messageId === msg.messageId);
  1106. if (index > -1) {
  1107. this.$set(this.messages[index], 'sendStatus', 1); // 发送中
  1108. }
  1109. const message = await timManager.sendTextMessage(this.targetUserId, msg.content);
  1110. // 更新消息状态为已送达
  1111. if (index > -1) {
  1112. const convertedMsg = this.convertMessage(message);
  1113. convertedMsg.sendStatus = 2; // 强制已送达
  1114. convertedMsg.messageId = msg.messageId; // 保持原ID
  1115. this.$set(this.messages, index, convertedMsg);
  1116. }
  1117. console.log('✅ 消息重发成功');
  1118. this.syncMessageToMySQL(message);
  1119. } catch (error) {
  1120. console.error('❌ 消息重发失败:', error);
  1121. const index = this.messages.findIndex(m => m.messageId === msg.messageId);
  1122. if (index > -1) {
  1123. this.$set(this.messages[index], 'sendStatus', 4);
  1124. }
  1125. uni.showToast({ title: '发送失败', icon: 'none' });
  1126. }
  1127. },
  1128. // 其他功能方法
  1129. switchInputType() {
  1130. this.inputType = this.inputType === 'text' ? 'voice' : 'text';
  1131. },
  1132. startVoiceRecord() {
  1133. uni.showToast({
  1134. title: '按住说话',
  1135. icon: 'none'
  1136. });
  1137. },
  1138. stopVoiceRecord() {
  1139. uni.showToast({
  1140. title: '语音功能开发中',
  1141. icon: 'none'
  1142. });
  1143. },
  1144. insertEmoji(emoji) {
  1145. this.inputText += emoji;
  1146. this.showEmojiPanel = false;
  1147. },
  1148. chooseVideo() {
  1149. uni.showToast({
  1150. title: '视频功能开发中',
  1151. icon: 'none'
  1152. });
  1153. this.showMorePanel = false;
  1154. },
  1155. chooseFile() {
  1156. uni.showToast({
  1157. title: '文件功能开发中',
  1158. icon: 'none'
  1159. });
  1160. this.showMorePanel = false;
  1161. },
  1162. playVoice() {
  1163. uni.showToast({
  1164. title: '语音播放功能开发中',
  1165. icon: 'none'
  1166. });
  1167. },
  1168. showMoreOptions() {
  1169. this.showMoreOptionsModal = true;
  1170. },
  1171. closeMoreOptions() {
  1172. this.showMoreOptionsModal = false;
  1173. },
  1174. /**
  1175. * 查看用户资料(跳转到原有more页面)
  1176. */
  1177. goToUserProfile() {
  1178. this.closeMoreOptions();
  1179. uni.navigateTo({
  1180. url: `/pages/message/more?userid=${this.targetUserId}`,
  1181. fail: (err) => {
  1182. console.error('跳转失败:', err);
  1183. uni.showToast({
  1184. title: '页面不存在',
  1185. icon: 'none'
  1186. });
  1187. }
  1188. });
  1189. },
  1190. /**
  1191. * 显示拉黑确认弹窗
  1192. */
  1193. blockFriend() {
  1194. this.closeMoreOptions();
  1195. this.showBlockConfirmModal = true;
  1196. },
  1197. /**
  1198. * 关闭拉黑确认弹窗
  1199. */
  1200. closeBlockConfirm() {
  1201. this.showBlockConfirmModal = false;
  1202. },
  1203. /**
  1204. * 从后端获取VIP状态和今日剩余发送次数
  1205. */
  1206. async getUserMessageLimit() {
  1207. try {
  1208. const [err, res] = await uni.request({
  1209. url: 'http://localhost:1004/api/chat/getUserMessageLimit',
  1210. method: 'GET',
  1211. data: {
  1212. userId: this.userId ,// 已在onLoad中初始化的当前用户ID
  1213. targetUserId: this.targetUserId
  1214. },
  1215. header: {
  1216. 'Content-Type': 'application/json'
  1217. }
  1218. });
  1219. if (err) throw new Error('网络请求失败');
  1220. if (res.data.code !== 200) throw new Error(res.data.message || '获取限制信息失败');
  1221. const { isVip, remainingCount, hasMessageLimit } = res.data.data;
  1222. this.isVip = isVip;
  1223. this.remainingCount = remainingCount;
  1224. this.hasMessageLimit = hasMessageLimit;
  1225. console.log('✅ 用户消息限制信息:', { isVip, remainingCount, hasMessageLimit });
  1226. } catch (error) {
  1227. console.error('❌ 获取消息限制失败:', error);
  1228. // 异常降级:默认非VIP,剩余5次
  1229. this.isVip = false;
  1230. this.remainingCount = 5;
  1231. this.hasMessageLimit = true;
  1232. }
  1233. },
  1234. /**
  1235. * 发送成功后,更新后端计数并同步前端剩余次数
  1236. */
  1237. async updateMessageCount() {
  1238. try {
  1239. const [err, res] = await uni.request({
  1240. url: 'http://localhost:8083/api/chat/updateMessageCount',
  1241. method: 'get',
  1242. data: {
  1243. userId: this.userId ,// 已在onLoad中初始化的当前用户ID
  1244. targetUserId: this.targetUserId
  1245. },
  1246. header: {
  1247. 'Content-Type': 'application/json'
  1248. }
  1249. });
  1250. if (err) throw new Error('更新计数失败');
  1251. if (res.data.code === 200) {
  1252. this.remainingCount = res.data.data.remainingCount; // 同步后端返回的剩余次数
  1253. }
  1254. } catch (error) {
  1255. console.error('❌ 更新发送次数失败:', error);
  1256. // 前端本地降级:避免影响用户体验,本地暂减1(刷新页面后同步真实数据)
  1257. if (this.remainingCount > 0) {
  1258. this.remainingCount--;
  1259. }
  1260. }
  1261. },
  1262. /**
  1263. * 确认拉黑好友
  1264. */
  1265. async confirmBlockFriend() {
  1266. try {
  1267. uni.showLoading({
  1268. title: '处理中...'
  1269. });
  1270. // 调用后端拉黑接口(根据实际接口调整)
  1271. const [err, res] = await uni.request({
  1272. url: 'http://localhost:8083/api/chatfriend/block',
  1273. method: 'POST',
  1274. data: {
  1275. userId: this.userId,
  1276. targetUserId: this.targetUserId,
  1277. targetUserName: this.targetUserName,
  1278. targetUserAvatar: this.targetUserAvatar
  1279. },
  1280. header: {
  1281. 'Content-Type': 'application/json',
  1282. // 'Authorization': 'Bearer ' + uni.getStorageSync('token')
  1283. }
  1284. });
  1285. uni.hideLoading();
  1286. if (err) throw new Error('网络请求失败');
  1287. if (res.data && res.data.code === 200) {
  1288. uni.showToast({ title: '拉黑成功', icon: 'success' });
  1289. this.closeBlockConfirm();
  1290. // 触发拉黑列表更新事件,通知消息页面实时刷新
  1291. uni.$emit('blacklistUpdated');
  1292. // 拉黑成功后立即返回消息列表页面(优化体验)
  1293. setTimeout(() => {
  1294. uni.navigateBack({
  1295. delta: 1,
  1296. success: () => {
  1297. // 返回成功后再次触发一次刷新,确保万无一失
  1298. uni.$emit('blacklistUpdated');
  1299. }
  1300. });
  1301. }, 1500);
  1302. } else {
  1303. throw new Error(res.data?.message || '拉黑失败');
  1304. }
  1305. } catch (error) {
  1306. console.error('拉黑失败:', error);
  1307. uni.showToast({ title: error.message || '拉黑失败', icon: 'none' });
  1308. }
  1309. },
  1310. }
  1311. };
  1312. </script>
  1313. <style scoped>
  1314. /* 弹窗遮罩 */
  1315. .modal-mask {
  1316. position: fixed;
  1317. top: 0;
  1318. left: 0;
  1319. right: 0;
  1320. bottom: 0;
  1321. background-color: rgba(0, 0, 0, 0.5);
  1322. z-index: 10000;
  1323. display: flex;
  1324. align-items: center;
  1325. justify-content: center;
  1326. }
  1327. /* 更多选项弹窗内容 */
  1328. .modal-content {
  1329. width: 70%;
  1330. background-color: #fff;
  1331. border-radius: 20rpx;
  1332. overflow: hidden;
  1333. }
  1334. .modal-header {
  1335. padding: 30rpx;
  1336. text-align: center;
  1337. border-bottom: 1px solid #eee;
  1338. }
  1339. .modal-title {
  1340. font-size: 32rpx;
  1341. font-weight: bold;
  1342. display: block;
  1343. }
  1344. .modal-subtitle {
  1345. font-size: 24rpx;
  1346. color: #999;
  1347. display: block;
  1348. margin-top: 10rpx;
  1349. }
  1350. .modal-body {
  1351. padding: 20rpx 0;
  1352. }
  1353. .modal-item {
  1354. display: flex;
  1355. align-items: center;
  1356. padding: 25rpx 40rpx;
  1357. font-size: 30rpx;
  1358. }
  1359. .modal-item.danger {
  1360. color: #fa5151;
  1361. }
  1362. .item-icon {
  1363. font-size: 32rpx;
  1364. margin-right: 20rpx;
  1365. }
  1366. .modal-footer {
  1367. padding: 20rpx;
  1368. border-top: 1px solid #eee;
  1369. }
  1370. .modal-close-btn {
  1371. width: 94%;
  1372. background-color: #f5f5f5;
  1373. border: none;
  1374. border-radius: 10rpx;
  1375. padding: 20rpx;
  1376. font-size: 30rpx;
  1377. }
  1378. /* 确认弹窗样式 */
  1379. .confirm-modal {
  1380. width: 60%;
  1381. background-color: #fff;
  1382. border-radius: 20rpx;
  1383. padding: 40rpx;
  1384. text-align: center;
  1385. }
  1386. .confirm-title {
  1387. font-size: 32rpx;
  1388. font-weight: bold;
  1389. margin-bottom: 30rpx;
  1390. }
  1391. .confirm-content {
  1392. font-size: 28rpx;
  1393. color: #666;
  1394. margin-bottom: 40rpx;
  1395. line-height: 1.5;
  1396. }
  1397. .confirm-buttons {
  1398. display: flex;
  1399. justify-content: space-between;
  1400. }
  1401. .confirm-btn {
  1402. flex: 1;
  1403. margin: 0 10rpx;
  1404. padding: 20rpx;
  1405. border-radius: 10rpx;
  1406. border: none;
  1407. font-size: 28rpx;
  1408. }
  1409. .confirm-btn.cancel {
  1410. background-color: #f5f5f5;
  1411. }
  1412. .confirm-btn.confirm {
  1413. background-color: #fa5151;
  1414. color: #fff;
  1415. }
  1416. .chat-page {
  1417. display: flex;
  1418. flex-direction: column;
  1419. height: 100vh;
  1420. background-color: #f5f5f5;
  1421. }
  1422. /* 顶部导航 */
  1423. .chat-header {
  1424. display: flex;
  1425. align-items: center;
  1426. justify-content: space-between;
  1427. padding: 20rpx 30rpx;
  1428. background-color: #fff;
  1429. border-bottom: 1px solid #e5e5e5;
  1430. }
  1431. .header-left, .header-right {
  1432. width: 80rpx;
  1433. }
  1434. .icon-back, .icon-more {
  1435. font-size: 40rpx;
  1436. }
  1437. .header-center {
  1438. flex: 1;
  1439. text-align: center;
  1440. }
  1441. .chat-title {
  1442. display: block;
  1443. font-size: 36rpx;
  1444. font-weight: bold;
  1445. }
  1446. .online-status {
  1447. display: block;
  1448. font-size: 24rpx;
  1449. color: #999;
  1450. margin-top: 5rpx;
  1451. }
  1452. .online-status.online {
  1453. color: #07c160;
  1454. }
  1455. /* 消息列表 */
  1456. .message-list {
  1457. flex: 1;
  1458. padding: 20rpx;
  1459. overflow-y: scroll;
  1460. }
  1461. .loading-tip {
  1462. text-align: center;
  1463. padding: 20rpx;
  1464. color: #999;
  1465. font-size: 28rpx;
  1466. }
  1467. .message-item {
  1468. display: flex;
  1469. margin-bottom: 30rpx;
  1470. }
  1471. .message-item.message-self {
  1472. flex-direction: row-reverse;
  1473. }
  1474. .avatar {
  1475. width: 80rpx;
  1476. height: 80rpx;
  1477. border-radius: 8rpx;
  1478. margin: 0 20rpx;
  1479. }
  1480. .message-content-wrapper {
  1481. max-width: 70%;
  1482. display: inline-block;
  1483. }
  1484. .message-item.message-self .message-content-wrapper {
  1485. text-align: right; /* 关键:让气泡和状态提示整体右对齐 */
  1486. }
  1487. .message-name {
  1488. display: block;
  1489. font-size: 24rpx;
  1490. color: #999;
  1491. margin-bottom: 10rpx;
  1492. }
  1493. .message-bubble {
  1494. padding: 20rpx;
  1495. border-radius: 8rpx;
  1496. background-color: #fff;
  1497. word-wrap: break-word;
  1498. display: inline-block; /* 关键:气泡宽度由内容决定 */
  1499. max-width: 100%; /* 防止内容过长超出容器 */
  1500. position: relative;
  1501. }
  1502. .message-self .message-bubble {
  1503. background-color: #95ec69;
  1504. border-top-right-radius: 4rpx;
  1505. }
  1506. .message-bubble.bubble-self {
  1507. background-color: #95ec69;
  1508. }
  1509. .message-text {
  1510. font-size: 30rpx;
  1511. line-height: 1.5;
  1512. }
  1513. .message-image {
  1514. max-width: 400rpx;
  1515. border-radius: 8rpx;
  1516. }
  1517. .message-voice {
  1518. display: flex;
  1519. align-items: center;
  1520. gap: 10rpx;
  1521. }
  1522. .message-video {
  1523. width: 400rpx;
  1524. height: 300rpx;
  1525. }
  1526. .message-recalled {
  1527. color: #999;
  1528. font-size: 28rpx;
  1529. }
  1530. .message-status {
  1531. text-align: right;
  1532. font-size: 24rpx;
  1533. color: #999;
  1534. margin-top: 5rpx;
  1535. }
  1536. .message-status .read {
  1537. color: #07c160;
  1538. }
  1539. .message-status .failed {
  1540. color: #fa5151;
  1541. }
  1542. .message-time {
  1543. display: block;
  1544. text-align: right;
  1545. font-size: 22rpx;
  1546. color: #ccc;
  1547. margin-top: 5rpx;
  1548. }
  1549. /* 输入框 */
  1550. .input-bar {
  1551. display: flex;
  1552. align-items: center;
  1553. padding: 20rpx;
  1554. background-color: #fff;
  1555. border-top: 1px solid #e5e5e5;
  1556. }
  1557. .input-icon {
  1558. width: 80rpx;
  1559. height: 80rpx;
  1560. display: flex;
  1561. align-items: center;
  1562. justify-content: center;
  1563. font-size: 50rpx;
  1564. }
  1565. .input-field {
  1566. flex: 1;
  1567. height: 70rpx;
  1568. padding: 0 20rpx;
  1569. background-color: #f5f5f5;
  1570. border-radius: 8rpx;
  1571. font-size: 30rpx;
  1572. }
  1573. .voice-button {
  1574. flex: 1;
  1575. height: 70rpx;
  1576. line-height: 70rpx;
  1577. background-color: #f5f5f5;
  1578. border-radius: 8rpx;
  1579. text-align: center;
  1580. font-size: 30rpx;
  1581. border: none;
  1582. }
  1583. /* 表情面板 */
  1584. .emoji-panel {
  1585. display: flex;
  1586. flex-wrap: wrap;
  1587. padding: 20rpx;
  1588. background-color: #fff;
  1589. border-top: 1px solid #e5e5e5;
  1590. }
  1591. .emoji-item {
  1592. width: 80rpx;
  1593. height: 80rpx;
  1594. display: flex;
  1595. align-items: center;
  1596. justify-content: center;
  1597. font-size: 60rpx;
  1598. }
  1599. /* 更多功能面板 */
  1600. .more-panel {
  1601. display: flex;
  1602. padding: 40rpx;
  1603. background-color: #fff;
  1604. border-top: 1px solid #e5e5e5;
  1605. }
  1606. .more-item {
  1607. display: flex;
  1608. flex-direction: column;
  1609. align-items: center;
  1610. margin: 0 40rpx;
  1611. }
  1612. .more-icon {
  1613. width: 100rpx;
  1614. height: 100rpx;
  1615. display: flex;
  1616. align-items: center;
  1617. justify-content: center;
  1618. font-size: 60rpx;
  1619. background-color: #f5f5f5;
  1620. border-radius: 16rpx;
  1621. margin-bottom: 10rpx;
  1622. }
  1623. .more-text {
  1624. font-size: 24rpx;
  1625. color: #666;
  1626. }
  1627. /* 时间分隔线 */
  1628. .time-divider {
  1629. text-align: center;
  1630. padding: 20rpx 0;
  1631. }
  1632. .time-text {
  1633. display: inline-block;
  1634. padding: 8rpx 20rpx;
  1635. background-color: rgba(0, 0, 0, 0.1);
  1636. border-radius: 8rpx;
  1637. font-size: 22rpx;
  1638. color: #999;
  1639. }
  1640. /* 消息气泡失败状态 */
  1641. .bubble-failed {
  1642. background-color: #95ec69;
  1643. opacity: 0.6;
  1644. border: 2rpx solid #fa5151;
  1645. }
  1646. /* 消息状态优化 */
  1647. .message-status .sending {
  1648. color: #576b95;
  1649. }
  1650. .message-status .failed-group {
  1651. display: flex;
  1652. align-items: center;
  1653. gap: 10rpx;
  1654. }
  1655. .message-status .retry-btn {
  1656. color: #576b95;
  1657. text-decoration: underline;
  1658. cursor: pointer;
  1659. }
  1660. /* 消息操作菜单遮罩 */
  1661. .message-action-mask {
  1662. position: fixed;
  1663. top: 0;
  1664. left: 0;
  1665. right: 0;
  1666. bottom: 0;
  1667. background-color: rgba(0, 0, 0, 0.4);
  1668. z-index: 9999;
  1669. display: flex;
  1670. align-items: center;
  1671. justify-content: center;
  1672. }
  1673. /* 消息操作菜单 */
  1674. .message-action-menu {
  1675. width: 600rpx;
  1676. background-color: #fff;
  1677. border-radius: 20rpx;
  1678. overflow: hidden;
  1679. }
  1680. .message-action-menu .menu-item {
  1681. display: flex;
  1682. align-items: center;
  1683. justify-content: center;
  1684. gap: 15rpx;
  1685. padding: 30rpx;
  1686. font-size: 32rpx;
  1687. color: #333;
  1688. border-bottom: 1rpx solid #f0f0f0;
  1689. transition: background-color 0.2s;
  1690. }
  1691. .message-action-menu .menu-item:active {
  1692. background-color: #f5f5f5;
  1693. }
  1694. .message-action-menu .menu-item.cancel {
  1695. color: #999;
  1696. border-bottom: none;
  1697. margin-top: 20rpx;
  1698. border-top: 10rpx solid #f5f5f5;
  1699. }
  1700. .message-action-menu .menu-icon {
  1701. font-size: 36rpx;
  1702. }
  1703. /* 消息发送限制提示 */
  1704. .message-limit-tip {
  1705. padding: 10rpx 20rpx;
  1706. font-size: 24rpx;
  1707. text-align: center;
  1708. background-color: #fff;
  1709. border-bottom: 1px solid #f5f5f5;
  1710. }
  1711. .vip-tip {
  1712. color: #ff9500; /* VIP橙色提示 */
  1713. }
  1714. .limit-tip {
  1715. color: #666; /* 普通灰色提示 */
  1716. }
  1717. .vip-link {
  1718. color: #2c9fff; /* 蓝色文字 */
  1719. text-decoration: underline; /* 下划线 */
  1720. cursor: pointer; /* 鼠标悬浮时显示手型 */
  1721. margin-left: 5rpx;
  1722. }
  1723. /* 点击时添加轻微反馈 */
  1724. .vip-link:active {
  1725. opacity: 0.7; /* 点击时透明度降低 */
  1726. }
  1727. </style>