chat.vue 82 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936
  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
  108. v-else-if="msg.messageType === 3"
  109. class="message-voice"
  110. :style="{width: getVoiceWidth(msg.duration)}"
  111. @click.stop="toggleVoicePlay(msg)">
  112. <text class="voice-duration">{{ msg.duration }}''</text>
  113. <view class="voice-icon-wrapper" :class="{playing: playingVoiceId === msg.messageId}">
  114. <image
  115. class="voice-icon"
  116. :src="msg.fromUserId === userId ? 'http://115.190.125.125:9000/static-images/%E6%88%91%E6%96%B9%E8%AF%AD%E9%9F%B3%E6%B6%88%E6%81%AF' : 'http://115.190.125.125:9000/static-images/%E5%AF%B9%E6%96%B9%E8%AF%AD%E9%9F%B3%E6%B6%88%E6%81%AF'"
  117. mode="aspectFit"></image>
  118. </view>
  119. <!-- 暂停后的继续播放按钮 -->
  120. <view
  121. v-if="pausedVoiceId === msg.messageId"
  122. class="voice-resume-btn"
  123. :class="{'resume-btn-left': msg.fromUserId === userId, 'resume-btn-right': msg.fromUserId !== userId}"
  124. @click.stop="resumeVoice">
  125. <text class="resume-icon">▶</text>
  126. </view>
  127. </view>
  128. <!-- 视频消息 -->
  129. <video
  130. v-else-if="msg.messageType === 4"
  131. class="message-video"
  132. :src="msg.mediaUrl"
  133. controls />
  134. <!-- 撤回消息 -->
  135. <text v-if="msg.isRecalled" class="message-recalled">
  136. 消息已撤回
  137. </text>
  138. </view>
  139. <!-- 消息状态(自己的消息) -->
  140. <view v-if="msg.fromUserId === userId" class="message-status">
  141. <text v-if="msg.sendStatus === 4" class="status-failed">发送失败</text>
  142. <text v-else-if="msg.isPeerRead" class="status-read">已读</text>
  143. <text v-else class="status-unread">未读</text>
  144. </view>
  145. </view>
  146. </view>
  147. </view>
  148. </scroll-view>
  149. <!-- 新增:消息发送限制提示 -->
  150. <view class="message-limit-tip">
  151. <!-- 同时判断isVip和hasMessageLimit,增强可靠性 -->
  152. <text v-if="isVip || !hasMessageLimit" class="vip-tip">✨ VIP特权:无发送次数限制</text>
  153. <text v-else class="limit-tip">
  154. 今日剩余可发送消息:{{ Math.max(remainingCount, 0) }} 条<text class="vip-link" @click="goToVipPage">(非VIP每日限5条)</text>
  155. </text>
  156. </view>
  157. <!-- 输入框 -->
  158. <view class="input-bar">
  159. <!-- 语音按钮 -->
  160. <view class="input-icon" @click="switchInputType">
  161. <image
  162. v-if="inputType === 'text'"
  163. class="icon-image"
  164. src="http://115.190.125.125:9000/static-images/%E8%AF%AD%E9%9F%B3%E6%B6%88%E6%81%AF%E6%8C%89%E9%92%AE"
  165. mode="aspectFit" />
  166. <text v-else>⌨️</text>
  167. </view>
  168. <!-- 文本输入 -->
  169. <input
  170. v-if="inputType === 'text'"
  171. class="input-field"
  172. v-model="inputText"
  173. placeholder="说点什么..."
  174. confirm-type="send"
  175. @confirm="sendTextMessage"
  176. @input="onInputChange" />
  177. <!-- 语音按钮 -->
  178. <button
  179. v-else
  180. class="voice-button"
  181. @touchstart="startVoiceRecord"
  182. @touchmove="onVoiceTouchMove"
  183. @touchend="stopVoiceRecord"
  184. @touchcancel="cancelVoiceRecord">
  185. 按住说话
  186. </button>
  187. <!-- 表情按钮 -->
  188. <view v-if="inputType === 'text'" class="input-icon" @click="showEmojiPanel = !showEmojiPanel">
  189. <text>😊</text>
  190. </view>
  191. <!-- 发送按钮 -->
  192. <view v-if="inputType === 'text'" class="send-button" :class="{disabled: !inputText.trim()}" @click="sendTextMessage">
  193. <text>发送</text>
  194. </view>
  195. </view>
  196. <!-- 表情面板 -->
  197. <view v-if="showEmojiPanel" class="emoji-panel">
  198. <text
  199. v-for="emoji in emojis"
  200. :key="emoji"
  201. class="emoji-item"
  202. @click="insertEmoji(emoji)">
  203. {{ emoji }}
  204. </text>
  205. </view>
  206. <!-- 消息操作菜单 -->
  207. <view v-if="showMessageAction" class="message-action-mask" @click="hideMessageMenu">
  208. <view class="message-action-menu" @click.stop>
  209. <view class="menu-item" @click="copyMessage" v-if="selectedMessage && selectedMessage.messageType === 1">
  210. <text class="menu-icon">📋</text>
  211. <text>复制</text>
  212. </view>
  213. <view class="menu-item" @click="recallMessage" v-if="selectedMessage && selectedMessage.fromUserId === userId && canRecall(selectedMessage)">
  214. <text class="menu-icon">↩️</text>
  215. <text>撤回</text>
  216. </view>
  217. <view class="menu-item" @click="deleteMessage">
  218. <text class="menu-icon">🗑️</text>
  219. <text>删除</text>
  220. </view>
  221. <view class="menu-item cancel" @click="hideMessageMenu">
  222. <text>取消</text>
  223. </view>
  224. </view>
  225. </view>
  226. <!-- 录音中提示 -->
  227. <view v-if="showVoiceRecording" class="voice-recording-mask">
  228. <view class="voice-recording-box" :class="{'canceling': voiceCanceling}">
  229. <view class="voice-wave-container">
  230. <view class="voice-wave-bar bar1" :style="{transform: `scaleY(${voiceVolume})`}"></view>
  231. <view class="voice-wave-bar bar2" :style="{transform: `scaleY(${voiceVolume * 1.2})`}"></view>
  232. <view class="voice-wave-bar bar3" :style="{transform: `scaleY(${voiceVolume * 1.5})`}"></view>
  233. <view class="voice-wave-bar bar4" :style="{transform: `scaleY(${voiceVolume * 1.3})`}"></view>
  234. <view class="voice-wave-bar bar5" :style="{transform: `scaleY(${voiceVolume})`}"></view>
  235. </view>
  236. <text class="voice-text">{{ voiceCanceling ? '松开取消发送' : '正在录音...' }}</text>
  237. <text class="voice-time">{{ voiceRecordingTime }}''</text>
  238. <text class="voice-tip" v-if="!voiceCanceling">松开发送,上滑取消</text>
  239. </view>
  240. </view>
  241. </view>
  242. </template>
  243. <script>
  244. import timManager from '@/utils/tim-manager.js';
  245. import TIM from 'tim-wx-sdk';
  246. export default {
  247. data() {
  248. return {
  249. isBlockedByTarget: false,
  250. userId: null,
  251. userAvatar: '',
  252. targetUserId: null,
  253. targetUserName: '',
  254. targetUserAvatar: '',
  255. messages: [],
  256. inputText: '',
  257. inputType: 'text',
  258. conversationID: '',
  259. scrollToView: '',
  260. showEmojiPanel: false,
  261. isLogin: false,
  262. // 消息操作菜单
  263. showMessageAction: false,
  264. selectedMessage: null,
  265. selectedMessageIndex: -1,
  266. menuTop: 0,
  267. // 加载更多
  268. loading: false,
  269. noMore: false,
  270. nextReqMessageID: '',
  271. isTargetOnline: false,
  272. emojis: ['😀', '😃', '😄', '😁', '😆', '😅', '😂', '🤣', '😊', '😇', '🙂', '🙃', '😉', '😌', '😍', '🥰', '😘', '😗', '😙', '😚', '😋', '😛', '😝', '😜', '🤪', '🤨', '🧐', '🤓', '😎', '🤩', '🥳'],
  273. showMoreOptionsModal: false, // 控制更多选项弹窗显示
  274. showBlockConfirmModal: false, // 控制拉黑确认弹窗显示
  275. isVip: false, // 是否VIP用户
  276. remainingCount: 5, // 剩余可发送消息数(非VIP默认5)
  277. hasMessageLimit: true, // 是否有发送限制(VIP为false)
  278. // 语音录制相关
  279. recorderManager: null, // 录音管理器
  280. isRecording: false, // 是否正在录音
  281. voiceStartTime: 0, // 录音开始时间
  282. voiceDuration: 0, // 录音时长
  283. voiceTempPath: '', // 录音临时文件路径
  284. showVoiceRecording: false, // 显示录音中提示
  285. voiceRecordingTime: 0, // 录音计时(秒)
  286. voiceRecordingTimer: null, // 录音计时器
  287. voiceTouchStartY: 0, // 录音按下时的Y坐标
  288. voiceCanceling: false, // 是否正在取消录音
  289. voiceVolume: 0.3, // 录音音量(0-1),控制波形高度
  290. playingVoiceId: null, // 当前播放的语音消息ID
  291. pausedVoiceId: null, // 当前暂停的语音消息ID
  292. currentAudioContext: null // 当前音频上下文
  293. };
  294. },
  295. async onLoad(options) {
  296. console.log('=== 聊天页面加载 ===');
  297. // 严格验证登录状态
  298. const token = uni.getStorageSync('token');
  299. const userInfo = uni.getStorageSync('userInfo');
  300. const storedUserId = uni.getStorageSync('userId');
  301. console.log('登录状态检查:');
  302. console.log('- token:', token ? '存在' : '不存在');
  303. console.log('- userInfo:', userInfo);
  304. console.log('- storedUserId:', storedUserId);
  305. if (!token || !userInfo) {
  306. console.error('❌ 未登录或登录信息不完整');
  307. uni.showModal({
  308. title: '需要登录',
  309. content: '请先登录后再进行聊天',
  310. showCancel: false,
  311. success: () => {
  312. uni.reLaunch({
  313. url: '/pages/page3/page3'
  314. });
  315. }
  316. });
  317. return;
  318. }
  319. // 优先使用 storage 中的 userId,确保一致性
  320. let rawUserId = storedUserId || userInfo.userId || userInfo.id || userInfo.user_id;
  321. // 转换为数字类型(确保与消息列表页面一致)
  322. if (typeof rawUserId === 'string') {
  323. rawUserId = parseInt(rawUserId);
  324. }
  325. if (!rawUserId || isNaN(rawUserId)) {
  326. console.error('❌ 无法获取有效的用户ID');
  327. uni.showModal({
  328. title: '用户信息错误',
  329. content: '无法获取用户ID,请重新登录',
  330. showCancel: false,
  331. success: () => {
  332. uni.removeStorageSync('token');
  333. uni.removeStorageSync('userInfo');
  334. uni.removeStorageSync('userId');
  335. uni.reLaunch({
  336. url: '/pages/page3/page3'
  337. });
  338. }
  339. });
  340. return;
  341. }
  342. // 保存用户ID(TIM需要字符串格式)
  343. this.userId = String(rawUserId);
  344. this.userAvatar = userInfo.avatar || userInfo.avatarUrl || '/static/default-avatar.svg';
  345. // 获取对方用户信息(确保是字符串格式)
  346. this.targetUserId = String(options.targetUserId);
  347. this.targetUserName = decodeURIComponent(options.targetUserName || '用户');
  348. this.targetUserAvatar = decodeURIComponent(options.targetUserAvatar || '/static/default-avatar.svg');
  349. // 生成会话 ID
  350. this.conversationID = `C2C${this.targetUserId}`;
  351. console.log('✅ 聊天页面初始化成功:');
  352. console.log(' - 当前用户ID:', rawUserId, '(TIM格式:', this.userId, ')');
  353. console.log(' - 对方用户ID:', this.targetUserId);
  354. console.log(' - 会话ID:', this.conversationID);
  355. // 初始化 TIM
  356. await this.initTIM();
  357. // 获取用户消息发送限制(VIP状态+剩余次数)
  358. await this.getUserMessageLimit();
  359. // 等待 SDK Ready 后再加载消息
  360. await this.waitForSDKReady();
  361. // 先检查拉黑状态
  362. this.isBlockedByTarget = await this.checkIsBlockedByTarget();
  363. if (this.isBlockedByTarget) {
  364. uni.showToast({
  365. title: '你已被对方拉黑,无法发送消息',
  366. icon: 'none',
  367. duration: 3000
  368. });
  369. }
  370. // 加载历史消息
  371. await this.loadMessages();
  372. // 监听新消息
  373. this.listenMessages();
  374. // 监听已读回执(确保在 SDK Ready 之后调用)
  375. this.listenMessageReadReceipt();
  376. // 标记当前会话的消息为已读
  377. this.markConversationRead();
  378. // 初始化在线状态监听(HTTP 轮询方式)
  379. this.initOnlineStatusPolling();
  380. // 如果有预设消息,自动发送
  381. if (options.message) {
  382. const message = decodeURIComponent(options.message);
  383. console.log('检测到预设消息,准备自动发送:', message);
  384. // 等待一下再发送,确保TIM已经初始化完成
  385. setTimeout(() => {
  386. this.inputText = message;
  387. this.sendTextMessage();
  388. }, 1500);
  389. }
  390. },
  391. onUnload() {
  392. // 页面卸载时移除监听
  393. timManager.offMessage(this.handleNewMessage);
  394. // 移除消息状态变更监听(已注释)
  395. /*
  396. if (timManager.tim && this.handleStatusChange) {
  397. timManager.tim.off(TIM.EVENT.MESSAGE_STATUS_CHANGED, this.handleStatusChange);
  398. }
  399. */
  400. },
  401. methods: {
  402. /**
  403. * 计算语音消息宽度(根据时长动态变化)
  404. * @param {Number} duration 语音时长(秒)
  405. * @return {String} 宽度值
  406. */
  407. getVoiceWidth(duration) {
  408. // 基础宽度 100rpx,每秒增加 10rpx,最大 400rpx
  409. const baseWidth = 100;
  410. const widthPerSecond = 10;
  411. const maxWidth = 400;
  412. const width = Math.min(baseWidth + (duration * widthPerSecond), maxWidth);
  413. return width + 'rpx';
  414. },
  415. /**
  416. * 初始化 TIM
  417. */
  418. async initTIM() {
  419. try {
  420. // 如果未初始化,先初始化
  421. if (!timManager.tim) {
  422. timManager.init(1600109674); // ✅ 已更新为正确的 SDKAppID
  423. }
  424. // 如果未登录,获取 userSig 并登录
  425. if (!timManager.isLogin) {
  426. // 先导入当前用户和目标用户到腾讯云IM
  427. await this.importUsers();
  428. // 从后端获取 userSig
  429. const userSig = await this.getUserSig();
  430. await timManager.login(this.userId, userSig);
  431. }
  432. this.isLogin = true;
  433. console.log('✅ TIM 初始化完成');
  434. } catch (error) {
  435. console.error('❌ TIM 初始化失败:', error);
  436. uni.showToast({
  437. title: '连接失败,请重试',
  438. icon: 'none'
  439. });
  440. }
  441. },
  442. /**
  443. * 跳转到VIP页面
  444. */
  445. goToVipPage() {
  446. console.log('点击跳转VIP页面');
  447. // 替换为你的实际VIP页面路径(例如会员开通页面)
  448. uni.navigateTo({
  449. url: '/pages/vip/index', // 请根据项目实际路径修改
  450. success: () => {
  451. console.log('跳转VIP页面成功');
  452. },
  453. fail: (err) => {
  454. console.error('跳转VIP页面失败:', err);
  455. uni.showToast({
  456. title: 'VIP页面不存在',
  457. icon: 'none'
  458. });
  459. }
  460. });
  461. },
  462. more(userid) {
  463. console.log('点击了更多按钮,开始跳转...', userid);
  464. // 如果目标页面是普通页面,用navigateTo(保留当前页面);如果是tabbar页面,用switchTab
  465. uni.navigateTo({
  466. url: `/pages/message/more?userid=${userid}`,
  467. success: () => {
  468. console.log('跳转成功');
  469. },
  470. fail: (err) => {
  471. console.error('跳转失败:', err);
  472. uni.showToast({
  473. title: '页面不存在或路径错误',
  474. icon: 'none'
  475. });
  476. }
  477. });
  478. },
  479. /**
  480. * 导入用户到腾讯云IM
  481. */
  482. async importUsers() {
  483. try {
  484. console.log('📥 开始导入用户到腾讯云IM...');
  485. console.log(' - 当前用户ID:', this.userId, '(类型:', typeof this.userId, ')');
  486. console.log(' - 目标用户ID:', this.targetUserId, '(类型:', typeof this.targetUserId, ')');
  487. // 验证用户ID
  488. if (!this.userId || this.userId === 'undefined' || this.userId === 'null') {
  489. throw new Error('当前用户ID无效: ' + this.userId);
  490. }
  491. if (!this.targetUserId || this.targetUserId === 'undefined' || this.targetUserId === 'null') {
  492. throw new Error('目标用户ID无效: ' + this.targetUserId);
  493. }
  494. // 导入当前用户(确保userId是字符串)
  495. const currentUserRes = await uni.request({
  496. url: 'http://localhost:1004/api/im/importUser',
  497. method: 'POST',
  498. data: {
  499. userId: String(this.userId),
  500. nickname: '用户' + this.userId
  501. },
  502. header: {
  503. 'Content-Type': 'application/json'
  504. }
  505. });
  506. console.log(' - 当前用户导入结果:', currentUserRes[1].data);
  507. // 导入目标用户(确保userId是字符串)
  508. const targetUserRes = await uni.request({
  509. url: 'http://localhost:1004/api/im/importUser',
  510. method: 'POST',
  511. data: {
  512. userId: String(this.targetUserId),
  513. nickname: this.targetUserName || '用户' + this.targetUserId
  514. },
  515. header: {
  516. 'Content-Type': 'application/json'
  517. }
  518. });
  519. console.log(' - 目标用户导入结果:', targetUserRes[1].data);
  520. console.log('✅ 用户导入成功');
  521. } catch (error) {
  522. console.log('⚠️ 用户导入失败(可能已存在):', error);
  523. // 导入失败不影响登录,因为用户可能已经存在
  524. }
  525. },
  526. /**
  527. * 获取 UserSig
  528. */
  529. async getUserSig() {
  530. try {
  531. const [err, res] = await uni.request({
  532. url: 'http://localhost:1004/api/im/getUserSig',
  533. method: 'GET',
  534. data: {
  535. userId: this.userId
  536. }
  537. });
  538. if (err) {
  539. throw new Error('请求失败');
  540. }
  541. if (res.data && res.data.code === 200) {
  542. return res.data.data.userSig;
  543. } else {
  544. throw new Error('获取 UserSig 失败');
  545. }
  546. } catch (error) {
  547. console.error('❌ 获取 UserSig 失败:', error);
  548. throw error;
  549. }
  550. },
  551. /**
  552. * 等待 SDK Ready
  553. */
  554. async waitForSDKReady() {
  555. return new Promise((resolve) => {
  556. // 如果已经 ready,立即返回
  557. if (timManager.isLogin) {
  558. console.log('✅ SDK 已就绪');
  559. resolve();
  560. return;
  561. }
  562. // 否则等待 SDK ready 事件
  563. console.log('⏳ 等待 SDK 就绪...');
  564. const checkReady = setInterval(() => {
  565. if (timManager.isLogin) {
  566. console.log('✅ SDK 已就绪');
  567. clearInterval(checkReady);
  568. resolve();
  569. }
  570. }, 100); // 每 100ms 检查一次
  571. // 超时保护(10秒后强制继续)
  572. setTimeout(() => {
  573. console.log('⚠️ 等待 SDK 就绪超时,继续执行');
  574. clearInterval(checkReady);
  575. resolve();
  576. }, 10000);
  577. });
  578. },
  579. /**
  580. * 加载历史消息
  581. */
  582. async loadMessages() {
  583. try {
  584. const res = await timManager.tim.getMessageList({
  585. conversationID: this.conversationID,
  586. count: 20
  587. });
  588. const messageList = res.data.messageList;
  589. this.nextReqMessageID = res.data.nextReqMessageID;
  590. this.noMore = !res.data.isCompleted;
  591. // 转换为我们的消息格式
  592. this.messages = messageList.map(msg => this.convertMessage(msg));
  593. // 滚动到底部
  594. this.$nextTick(() => {
  595. this.scrollToBottom();
  596. });
  597. // 标记已读
  598. await timManager.setMessageRead(this.conversationID);
  599. } catch (error) {
  600. console.error('❌ 加载消息失败:', error);
  601. }
  602. },
  603. /**
  604. * 加载更多消息(上拉)
  605. */
  606. async loadMoreMessages() {
  607. if (this.loading || !this.nextReqMessageID) {
  608. return;
  609. }
  610. this.loading = true;
  611. try {
  612. const res = await timManager.tim.getMessageList({
  613. conversationID: this.conversationID,
  614. nextReqMessageID: this.nextReqMessageID,
  615. count: 20
  616. });
  617. const messageList = res.data.messageList;
  618. this.nextReqMessageID = res.data.nextReqMessageID;
  619. this.noMore = !res.data.isCompleted;
  620. // 转换并添加到消息列表前面
  621. const newMessages = messageList.map(msg => this.convertMessage(msg));
  622. this.messages = [...newMessages, ...this.messages];
  623. } catch (error) {
  624. console.error('❌ 加载更多消息失败:', error);
  625. } finally {
  626. this.loading = false;
  627. }
  628. },
  629. /**
  630. * 监听新消息
  631. */
  632. listenMessages() {
  633. const handleNewMessage = (event) => {
  634. // 兼容不同格式的事件数据
  635. const messageList = event.data || event || [];
  636. // 确保是数组格式
  637. const messagesToProcess = Array.isArray(messageList) ? messageList : [messageList];
  638. messagesToProcess.forEach(msg => {
  639. // 只处理当前会话的消息
  640. if (msg.conversationID === this.conversationID) {
  641. // 查找消息在本地列表中的位置
  642. const existingIndex = this.messages.findIndex(m => m.messageId === msg.ID);
  643. if (existingIndex > -1) {
  644. // 更新现有消息状态(使用$set确保视图更新)
  645. this.$set(this.messages, existingIndex, this.convertMessage(msg));
  646. } else {
  647. // 添加新消息
  648. this.messages.push(this.convertMessage(msg));
  649. this.$nextTick(() => {
  650. this.scrollToBottom();
  651. });
  652. }
  653. // 标记已读(通知对方:我已阅读他发送的消息)
  654. console.log('📖 收到新消息,标记会话已读:', this.conversationID);
  655. timManager.setMessageRead(this.conversationID);
  656. }
  657. });
  658. };
  659. this.handleNewMessage = handleNewMessage;
  660. timManager.onMessage(handleNewMessage);
  661. // 添加消息状态变更监听
  662. // 注释原因:TIM.EVENT.MESSAGE_STATUS_CHANGED 在当前SDK版本中可能不存在,导致参数验证失败
  663. // 消息状态更新已通过 handleNewMessage 处理,暂时不需要单独监听
  664. /*
  665. if (timManager.tim) {
  666. const handleStatusChange = (event) => {
  667. console.log('📝 消息状态变更:', event);
  668. // MESSAGE_STATUS_CHANGED 事件的数据结构不同
  669. if (event && event.data && Array.isArray(event.data)) {
  670. event.data.forEach(msg => {
  671. if (msg.conversationID === this.conversationID) {
  672. const existingIndex = this.messages.findIndex(m => m.messageId === msg.ID);
  673. if (existingIndex > -1) {
  674. this.$set(this.messages, existingIndex, this.convertMessage(msg));
  675. }
  676. }
  677. });
  678. }
  679. };
  680. this.handleStatusChange = handleStatusChange;
  681. timManager.tim.on(TIM.EVENT.MESSAGE_STATUS_CHANGED, handleStatusChange);
  682. }
  683. */
  684. },
  685. /**
  686. * 转换消息格式
  687. */
  688. convertMessage(timMsg) {
  689. let sendStatus = 1; // 默认发送中
  690. // 完善的状态判断逻辑
  691. if (timMsg.status === TIM.TYPES.MSG_STATUS_SEND_SUCC ||
  692. timMsg.status === 'success' ||
  693. timMsg.status === TIM.TYPES.MSG_STATUS_RECEIVED) {
  694. sendStatus = 2; // 已送达
  695. } else if (timMsg.status === TIM.TYPES.MSG_STATUS_SEND_FAIL ||
  696. timMsg.status === 'fail') {
  697. sendStatus = 4; // 发送失败
  698. } else if (timMsg.status === TIM.TYPES.MSG_STATUS_HAS_READ ||
  699. timMsg.status === 'read') {
  700. sendStatus = 3; // 已读
  701. } else if (timMsg.status === TIM.TYPES.MSG_STATUS_SENDING) {
  702. sendStatus = 1; // 发送中
  703. }
  704. // 处理不同类型消息的URL和时长
  705. let mediaUrl = '';
  706. let duration = 0;
  707. let messageType = 1;
  708. let content = '';
  709. if (timMsg.type === TIM.TYPES.MSG_TEXT) {
  710. messageType = 1;
  711. content = timMsg.payload.text;
  712. } else if (timMsg.type === TIM.TYPES.MSG_IMAGE && timMsg.payload.imageInfoArray) {
  713. messageType = 2;
  714. content = '[图片]';
  715. mediaUrl = timMsg.payload.imageInfoArray[0]?.url || '';
  716. } else if (timMsg.type === TIM.TYPES.MSG_SOUND) {
  717. // 原生语音消息
  718. messageType = 3;
  719. content = '[语音]';
  720. mediaUrl = timMsg.payload.url || timMsg.payload.remoteAudioUrl || '';
  721. duration = timMsg.payload.second || 0;
  722. } else if (timMsg.type === TIM.TYPES.MSG_CUSTOM) {
  723. // 自定义消息(我们的语音消息)
  724. try {
  725. const customData = JSON.parse(timMsg.payload.data);
  726. if (customData.type === 'voice') {
  727. messageType = 3;
  728. content = '[语音]';
  729. mediaUrl = customData.url;
  730. // duration已经是秒数,直接使用
  731. duration = parseInt(customData.duration) || 0;
  732. }
  733. } catch (e) {
  734. console.error('解析自定义消息失败:', e);
  735. }
  736. } else if (timMsg.type === TIM.TYPES.MSG_VIDEO) {
  737. messageType = 4;
  738. content = '[视频]';
  739. }
  740. // 对于自己发送的消息,使用 TIM SDK 的 isPeerRead 值
  741. // TIM SDK 会根据 peerReadTime 自动更新这个字段
  742. let isPeerRead = false;
  743. if (timMsg.from === this.userId) {
  744. // 自己发送的消息,使用 TIM SDK 的 isPeerRead 值
  745. isPeerRead = timMsg.isPeerRead || false;
  746. } else {
  747. // 对方发送的消息,不需要 isPeerRead 字段
  748. isPeerRead = false;
  749. }
  750. return {
  751. messageId: timMsg.ID,
  752. fromUserId: timMsg.from,
  753. toUserId: timMsg.to,
  754. messageType: messageType,
  755. content: content || '[消息]',
  756. mediaUrl: mediaUrl,
  757. duration: duration,
  758. payload: timMsg.payload, // 保留原始payload
  759. sendStatus: sendStatus,
  760. sendTime: new Date(timMsg.time * 1000),
  761. isRecalled: timMsg.isRevoked,
  762. fromUserName: timMsg.from === this.userId ? '我' : this.targetUserName,
  763. isPeerRead: isPeerRead // 对方是否已读(只对自己发送的消息有意义)
  764. };
  765. },
  766. /**
  767. * 检查对方是否拉黑自己
  768. */
  769. async checkIsBlockedByTarget() {
  770. try {
  771. const [err, res] = await uni.request({
  772. url: 'http://localhost:8083/api/chatfriend/checkBlock',
  773. method: 'POST',
  774. data: {
  775. userId: this.userId, // 自己的ID
  776. targetUserId: this.targetUserId // 对方的ID
  777. },
  778. header: {
  779. 'Content-Type': 'application/json'
  780. }
  781. });
  782. console.log('拉黑检查接口响应:', res.data); // 方便调试
  783. if (err) {
  784. console.error('网络请求失败:', err);
  785. return false; // 网络错误时默认按“未被拉黑”处理(避免误拦截)
  786. }
  787. // 严格校验接口返回格式
  788. if (!res.data || res.data.code !== 200) {
  789. console.error('接口返回格式错误:', res.data);
  790. return false;
  791. }
  792. // 关键修复:后端返回 data:true 表示“已被拉黑”,直接返回该值
  793. // 你的接口中 data 就是布尔值,无需额外解析
  794. const isBlocked = res.data.data;
  795. console.log('是否被拉黑:', isBlocked); // 确认这里输出为 true(被拉黑时)
  796. return isBlocked;
  797. } catch (error) {
  798. console.error('检查拉黑状态失败:', error);
  799. return false;
  800. }
  801. },
  802. /**
  803. * 监听已读回执
  804. */
  805. listenMessageReadReceipt() {
  806. console.log('🔔 开始注册已读回执监听器...');
  807. if (!timManager.tim) {
  808. console.warn('⚠️ TIM 未初始化,无法监听已读回执');
  809. return;
  810. }
  811. console.log('✅ TIM 对象已就绪,准备监听 MESSAGE_READ_BY_PEER 事件');
  812. // 监听消息已读回执事件
  813. const handleMessageReadByPeer = (event) => {
  814. console.log('=== 📖 收到已读回执事件 ===');
  815. console.log(' - 完整事件对象:', event);
  816. console.log(' - 事件数据:', JSON.stringify(event.data));
  817. // event.data 包含已读的消息列表
  818. if (event.data && Array.isArray(event.data)) {
  819. event.data.forEach(item => {
  820. console.log(' - 处理会话:', item.conversationID, '当前会话:', this.conversationID);
  821. // 只处理当前会话的消息
  822. if (item.conversationID === this.conversationID) {
  823. console.log('✅ 对方已阅读当前会话的消息');
  824. let updatedCount = 0;
  825. // 更新本地消息列表中所有未读消息的状态
  826. this.messages.forEach((msg, index) => {
  827. // 只更新自己发送的且未被标记为已读的消息
  828. if (msg.fromUserId === this.userId && !msg.isPeerRead && msg.sendStatus !== 4) {
  829. this.$set(this.messages[index], 'isPeerRead', true);
  830. updatedCount++;
  831. console.log(` - 消息 ${msg.messageId} 已标记为已读`);
  832. }
  833. });
  834. console.log(`✅ 共更新 ${updatedCount} 条消息为已读状态`);
  835. }
  836. });
  837. }
  838. };
  839. this.handleMessageReadByPeer = handleMessageReadByPeer;
  840. timManager.tim.on(TIM.EVENT.MESSAGE_READ_BY_PEER, handleMessageReadByPeer);
  841. console.log('✅ 已监听消息已读回执');
  842. },
  843. /**
  844. * 标记当前会话的消息为已读
  845. * 注意:这会通知对方"我已阅读他发送的消息",触发对方的 MESSAGE_READ_BY_PEER 事件
  846. */
  847. async markConversationRead() {
  848. try {
  849. if (!timManager.tim || !this.conversationID) {
  850. console.warn('⚠️ TIM 未初始化或会话ID为空');
  851. return;
  852. }
  853. console.log('📖 标记会话已读:', this.conversationID);
  854. // 调用 TIM SDK 标记会话已读
  855. // 这会通知对方:他发送给我的消息已被阅读
  856. await timManager.tim.setMessageRead({ conversationID: this.conversationID });
  857. console.log('✅ 会话已标记为已读,已通知对方');
  858. } catch (error) {
  859. console.error('❌ 标记会话已读失败:', error);
  860. }
  861. },
  862. /**
  863. * 发送文本消息
  864. */
  865. async sendTextMessage() {
  866. if (this.hasMessageLimit && this.remainingCount <= 0) {
  867. uni.showToast({
  868. title: '今日消息发送次数已用完,开通VIP无限制',
  869. icon: 'none',
  870. duration: 2000
  871. });
  872. return;
  873. }
  874. if (!this.inputText.trim()) {
  875. return;
  876. }
  877. const content = this.inputText;
  878. this.inputText = '';
  879. // 先检查是否被拉黑
  880. const isBlocked = await this.checkIsBlockedByTarget();
  881. if (isBlocked) {
  882. // 被拉黑时的处理保持不变
  883. const failedMessage = {
  884. messageId: 'failed_' + Date.now(),
  885. fromUserId: this.userId,
  886. toUserId: this.targetUserId,
  887. messageType: 1,
  888. content: content,
  889. sendStatus: 4, // 4表示发送失败
  890. sendTime: new Date(),
  891. fromUserName: '我'
  892. };
  893. this.messages.push(failedMessage);
  894. this.scrollToBottom();
  895. uni.showToast({
  896. title: '消息发送失败',
  897. icon: 'none'
  898. });
  899. return;
  900. }
  901. // 创建临时消息显示"发送中"
  902. const tempMessageId = 'temp_' + Date.now();
  903. const tempMessage = {
  904. messageId: tempMessageId,
  905. fromUserId: this.userId,
  906. toUserId: this.targetUserId,
  907. messageType: 1,
  908. content: content,
  909. sendStatus: 1, // 发送中
  910. sendTime: new Date(),
  911. fromUserName: '我'
  912. };
  913. this.messages.push(tempMessage);
  914. this.scrollToBottom();
  915. // 未被拉黑,正常发送
  916. try {
  917. const sendPromise = timManager.sendTextMessage(this.targetUserId, content);
  918. const timeoutPromise = new Promise((_, reject) => {
  919. setTimeout(() => reject(new Error('发送超时')), 15000);
  920. });
  921. const message = await Promise.race([sendPromise, timeoutPromise]);
  922. // 替换临时消息
  923. const tempIndex = this.messages.findIndex(m => m.messageId === tempMessageId);
  924. if (tempIndex > -1) {
  925. const convertedMsg = this.convertMessage(message);
  926. // 强制设置为已送达
  927. convertedMsg.sendStatus = 2;
  928. this.$set(this.messages, tempIndex, convertedMsg);
  929. }
  930. console.log('✅ 消息发送成功');
  931. this.syncMessageToMySQL(message);
  932. if (!this.isVip) {
  933. await this.updateMessageCount();
  934. }
  935. } catch (error) {
  936. console.error('❌ 消息发送失败:', error);
  937. // 更新临时消息为失败状态
  938. const tempIndex = this.messages.findIndex(m => m.messageId === tempMessageId);
  939. if (tempIndex > -1) {
  940. this.$set(this.messages[tempIndex], 'sendStatus', 4);
  941. }
  942. // 恢复输入框内容
  943. this.inputText = content;
  944. uni.showToast({
  945. title: '发送失败: ' + error.message,
  946. icon: 'none'
  947. });
  948. }
  949. },
  950. /**
  951. * 选择图片
  952. */
  953. chooseImage() {
  954. uni.chooseImage({
  955. count: 1,
  956. sizeType: ['compressed'],
  957. sourceType: ['album', 'camera'],
  958. success: async (res) => {
  959. // 1. 先检查是否被拉黑
  960. const isBlocked = await this.checkIsBlockedByTarget();
  961. if (isBlocked) {
  962. uni.showToast({
  963. title: '你已被对方拉黑,无法发送消息',
  964. icon: 'none'
  965. });
  966. return;
  967. }
  968. const tempFilePath = res.tempFilePaths[0];
  969. try {
  970. uni.showLoading({ title: '发送中...' });
  971. const message = await timManager.sendImageMessage(this.targetUserId, tempFilePath);
  972. this.messages.push(this.convertMessage(message));
  973. this.scrollToBottom();
  974. uni.hideLoading();
  975. console.log('✅ 图片发送成功');
  976. } catch (error) {
  977. uni.hideLoading();
  978. console.error('❌ 图片发送失败:', error);
  979. uni.showToast({
  980. title: '发送失败',
  981. icon: 'none'
  982. });
  983. }
  984. }
  985. });
  986. },
  987. /**
  988. * 输入框内容变化
  989. */
  990. onInputChange() {
  991. // 腾讯云 IM 可以实现正在输入状态,这里暂时省略
  992. console.log('输入中...');
  993. },
  994. /**
  995. * 同步消息到MySQL数据库(双重存储保障)
  996. */
  997. async syncMessageToMySQL(timMessage) {
  998. try {
  999. console.log('🔄 同步消息到MySQL...', timMessage.ID);
  1000. // 构建同步参数
  1001. const syncData = {
  1002. messageId: timMessage.ID,
  1003. fromUserId: timMessage.from,
  1004. toUserId: timMessage.to,
  1005. messageType: this.getMessageType(timMessage),
  1006. content: this.getMessageContent(timMessage),
  1007. sendTime: timMessage.time // TIM返回的是秒级时间戳
  1008. };
  1009. // 如果是图片消息,添加媒体信息
  1010. if (timMessage.type === 'TIMImageElem' && timMessage.payload.imageInfoArray) {
  1011. const imageInfo = timMessage.payload.imageInfoArray[0];
  1012. syncData.mediaUrl = imageInfo.imageUrl;
  1013. syncData.thumbnailUrl = imageInfo.imageUrl;
  1014. }
  1015. // 如果是语音消息,添加语音信息
  1016. if (timMessage.type === 'TIMSoundElem' && timMessage.payload) {
  1017. syncData.mediaUrl = timMessage.payload.url || timMessage.payload.remoteAudioUrl;
  1018. syncData.duration = timMessage.payload.second || 0;
  1019. syncData.mediaSize = timMessage.payload.size || 0;
  1020. }
  1021. // 如果是自定义消息(我们的语音消息)
  1022. if (timMessage.type === 'TIMCustomElem' && timMessage.payload) {
  1023. try {
  1024. const customData = JSON.parse(timMessage.payload.data);
  1025. if (customData.type === 'voice') {
  1026. syncData.mediaUrl = customData.url;
  1027. syncData.duration = customData.duration;
  1028. syncData.mediaSize = customData.size || 0;
  1029. }
  1030. } catch (e) {
  1031. console.error('解析自定义消息失败:', e);
  1032. }
  1033. }
  1034. // 调用后端同步接口
  1035. const res = await uni.request({
  1036. url: 'http://localhost:1004/api/chat/syncTIMMessage',
  1037. method: 'POST',
  1038. data: syncData,
  1039. header: {
  1040. 'Content-Type': 'application/json'
  1041. }
  1042. });
  1043. if (res[1].data.code === 200) {
  1044. console.log('✅ 消息已同步到MySQL:', timMessage.ID);
  1045. } else {
  1046. console.warn('⚠️ 消息同步失败:', res[1].data.message);
  1047. }
  1048. } catch (error) {
  1049. console.error('❌ 同步消息到MySQL失败:', error);
  1050. // 同步失败不影响聊天功能,只记录日志
  1051. }
  1052. },
  1053. /**
  1054. * 获取消息类型
  1055. */
  1056. getMessageType(timMessage) {
  1057. const typeMap = {
  1058. 'TIMTextElem': 1, // 文本
  1059. 'TIMImageElem': 2, // 图片
  1060. 'TIMSoundElem': 3, // 语音
  1061. 'TIMVideoFileElem': 4, // 视频
  1062. 'TIMFileElem': 5 // 文件
  1063. };
  1064. // 处理自定义消息(我们的语音消息)
  1065. if (timMessage.type === 'TIMCustomElem' && timMessage.payload) {
  1066. try {
  1067. const customData = JSON.parse(timMessage.payload.data);
  1068. if (customData.type === 'voice') {
  1069. return 3; // 语音消息
  1070. }
  1071. } catch (e) {
  1072. console.error('解析自定义消息类型失败:', e);
  1073. }
  1074. }
  1075. return typeMap[timMessage.type] || 1;
  1076. },
  1077. /**
  1078. * 获取消息内容
  1079. */
  1080. getMessageContent(timMessage) {
  1081. switch (timMessage.type) {
  1082. case 'TIMTextElem':
  1083. return timMessage.payload.text || '';
  1084. case 'TIMImageElem':
  1085. return '[图片]';
  1086. case 'TIMSoundElem':
  1087. return '[语音]';
  1088. case 'TIMVideoFileElem':
  1089. return '[视频]';
  1090. case 'TIMFileElem':
  1091. return '[文件]';
  1092. default:
  1093. return '[未知消息]';
  1094. }
  1095. },
  1096. /**
  1097. * 滚动到底部
  1098. */
  1099. scrollToBottom() {
  1100. this.$nextTick(() => {
  1101. const lastIndex = this.messages.length - 1;
  1102. this.scrollToView = 'msg-' + lastIndex;
  1103. });
  1104. },
  1105. /**
  1106. * 判断是否显示时间分隔线
  1107. */
  1108. shouldShowTime(msg, index) {
  1109. if (index === 0) return true;
  1110. const prevMsg = this.messages[index - 1];
  1111. const timeDiff = new Date(msg.sendTime) - new Date(prevMsg.sendTime);
  1112. // 超过5分钟显示时间
  1113. return timeDiff > 5 * 60 * 1000;
  1114. },
  1115. /**
  1116. * 格式化消息时间(用于时间分隔线)
  1117. */
  1118. formatMessageTime(time) {
  1119. const date = new Date(time);
  1120. const now = new Date();
  1121. const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
  1122. const yesterday = new Date(today - 86400000);
  1123. // 今天
  1124. if (date >= today) {
  1125. return date.toLocaleTimeString('zh-CN', {
  1126. hour: '2-digit',
  1127. minute: '2-digit'
  1128. });
  1129. }
  1130. // 昨天
  1131. if (date >= yesterday) {
  1132. return '昨天 ' + date.toLocaleTimeString('zh-CN', {
  1133. hour: '2-digit',
  1134. minute: '2-digit'
  1135. });
  1136. }
  1137. // 本周
  1138. if (date > new Date(now - 7 * 86400000)) {
  1139. const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
  1140. return days[date.getDay()] + ' ' + date.toLocaleTimeString('zh-CN', {
  1141. hour: '2-digit',
  1142. minute: '2-digit'
  1143. });
  1144. }
  1145. // 更早
  1146. return date.toLocaleString('zh-CN', {
  1147. month: '2-digit',
  1148. day: '2-digit',
  1149. hour: '2-digit',
  1150. minute: '2-digit'
  1151. });
  1152. },
  1153. /**
  1154. * 格式化时间(消息状态用)
  1155. */
  1156. formatTime(time) {
  1157. const date = new Date(time);
  1158. const now = new Date();
  1159. const diff = now - date;
  1160. if (diff < 60000) {
  1161. return '刚刚';
  1162. } else if (diff < 3600000) {
  1163. return Math.floor(diff / 60000) + '分钟前';
  1164. } else if (diff < 86400000) {
  1165. return Math.floor(diff / 3600000) + '小时前';
  1166. } else {
  1167. return date.toLocaleString('zh-CN', {
  1168. month: '2-digit',
  1169. day: '2-digit',
  1170. hour: '2-digit',
  1171. minute: '2-digit'
  1172. });
  1173. }
  1174. },
  1175. /**
  1176. * 预览图片
  1177. */
  1178. previewImage(url) {
  1179. uni.previewImage({
  1180. urls: [url],
  1181. current: url
  1182. });
  1183. },
  1184. /**
  1185. * 返回
  1186. */
  1187. goBack() {
  1188. uni.navigateBack({
  1189. success: () => {
  1190. // 通知消息列表页面刷新
  1191. uni.$emit('refreshConversations');
  1192. }
  1193. });
  1194. },
  1195. /**
  1196. * 显示消息操作菜单
  1197. */
  1198. showMessageMenu(msg, index) {
  1199. this.selectedMessage = msg;
  1200. this.selectedMessageIndex = index;
  1201. this.showMessageAction = true;
  1202. // 计算菜单位置
  1203. uni.createSelectorQuery().select('.message-item').boundingClientRect(rect => {
  1204. if (rect) {
  1205. this.menuTop = rect.top + rect.height;
  1206. }
  1207. }).exec();
  1208. },
  1209. /**
  1210. * 隐藏消息操作菜单
  1211. */
  1212. hideMessageMenu() {
  1213. this.showMessageAction = false;
  1214. this.selectedMessage = null;
  1215. this.selectedMessageIndex = -1;
  1216. },
  1217. /**
  1218. * 复制消息
  1219. */
  1220. copyMessage() {
  1221. if (!this.selectedMessage || this.selectedMessage.messageType !== 1) {
  1222. return;
  1223. }
  1224. uni.setClipboardData({
  1225. data: this.selectedMessage.content,
  1226. success: () => {
  1227. uni.showToast({
  1228. title: '已复制',
  1229. icon: 'success'
  1230. });
  1231. }
  1232. });
  1233. this.hideMessageMenu();
  1234. },
  1235. /**
  1236. * 判断是否可以撤回
  1237. */
  1238. canRecall(msg) {
  1239. const diff = Date.now() - new Date(msg.sendTime).getTime();
  1240. return diff < 2 * 60 * 1000; // 2分钟内可撤回
  1241. },
  1242. /**
  1243. * 撤回消息
  1244. */
  1245. async recallMessage() {
  1246. if (!this.selectedMessage) {
  1247. return;
  1248. }
  1249. try {
  1250. // 查找TIM消息对象
  1251. const timMessage = await timManager.tim.findMessage(this.selectedMessage.messageId);
  1252. if (timMessage) {
  1253. await timManager.revokeMessage(timMessage);
  1254. // 更新本地消息状态
  1255. this.selectedMessage.isRecalled = true;
  1256. this.selectedMessage.content = '你撤回了一条消息';
  1257. uni.showToast({
  1258. title: '已撤回',
  1259. icon: 'success'
  1260. });
  1261. }
  1262. } catch (error) {
  1263. console.error('撤回失败:', error);
  1264. uni.showToast({
  1265. title: '撤回失败',
  1266. icon: 'none'
  1267. });
  1268. }
  1269. this.hideMessageMenu();
  1270. },
  1271. /**
  1272. * 删除消息
  1273. */
  1274. deleteMessage() {
  1275. if (!this.selectedMessage) {
  1276. return;
  1277. }
  1278. uni.showModal({
  1279. title: '确认删除',
  1280. content: '确定要删除这条消息吗?',
  1281. success: (res) => {
  1282. if (res.confirm) {
  1283. // 从列表中删除
  1284. this.messages.splice(this.selectedMessageIndex, 1);
  1285. uni.showToast({
  1286. title: '已删除',
  1287. icon: 'success'
  1288. });
  1289. }
  1290. }
  1291. });
  1292. this.hideMessageMenu();
  1293. },
  1294. /**
  1295. * 处理消息点击
  1296. */
  1297. handleMessageClick(msg) {
  1298. // 如果是发送失败的消息,提示重试
  1299. if (msg.sendStatus === 4) {
  1300. uni.showModal({
  1301. title: '发送失败',
  1302. content: '消息发送失败,是否重试?',
  1303. success: (res) => {
  1304. if (res.confirm) {
  1305. this.retryMessage(msg);
  1306. }
  1307. }
  1308. });
  1309. }
  1310. },
  1311. /**
  1312. * 重试发送消息
  1313. */
  1314. async retryMessage(msg) {
  1315. if (msg.messageType !== 1) {
  1316. uni.showToast({ title: '暂不支持重发该类型消息', icon: 'none' });
  1317. return;
  1318. }
  1319. const isBlocked = await this.checkIsBlockedByTarget();
  1320. if (isBlocked) {
  1321. const index = this.messages.findIndex(m => m.messageId === msg.messageId);
  1322. if (index > -1) {
  1323. this.$set(this.messages[index], 'sendStatus', 4);
  1324. }
  1325. uni.showToast({ title: '对方已拉黑你,无法发送', icon: 'none' });
  1326. return;
  1327. }
  1328. try {
  1329. const index = this.messages.findIndex(m => m.messageId === msg.messageId);
  1330. if (index > -1) {
  1331. this.$set(this.messages[index], 'sendStatus', 1); // 发送中
  1332. }
  1333. const message = await timManager.sendTextMessage(this.targetUserId, msg.content);
  1334. // 更新消息状态为已送达
  1335. if (index > -1) {
  1336. const convertedMsg = this.convertMessage(message);
  1337. convertedMsg.sendStatus = 2; // 强制已送达
  1338. convertedMsg.messageId = msg.messageId; // 保持原ID
  1339. this.$set(this.messages, index, convertedMsg);
  1340. }
  1341. console.log('✅ 消息重发成功');
  1342. this.syncMessageToMySQL(message);
  1343. } catch (error) {
  1344. console.error('❌ 消息重发失败:', error);
  1345. const index = this.messages.findIndex(m => m.messageId === msg.messageId);
  1346. if (index > -1) {
  1347. this.$set(this.messages[index], 'sendStatus', 4);
  1348. }
  1349. uni.showToast({ title: '发送失败', icon: 'none' });
  1350. }
  1351. },
  1352. // 其他功能方法
  1353. switchInputType() {
  1354. this.inputType = this.inputType === 'text' ? 'voice' : 'text';
  1355. },
  1356. /**
  1357. * 开始录音
  1358. */
  1359. startVoiceRecord(e) {
  1360. console.log('🎤 [按住说话] startVoiceRecord 方法被调用');
  1361. // 记录触摸起始位置
  1362. this.voiceTouchStartY = e.touches[0].clientY;
  1363. this.voiceCanceling = false;
  1364. // 检查消息发送限制
  1365. if (this.hasMessageLimit && this.remainingCount <= 0) {
  1366. uni.showToast({
  1367. title: '今日消息发送次数已用完',
  1368. icon: 'none'
  1369. });
  1370. return;
  1371. }
  1372. // 初始化录音管理器
  1373. if (!this.recorderManager) {
  1374. console.log('📱 初始化录音管理器');
  1375. this.recorderManager = uni.getRecorderManager();
  1376. // 录音开始
  1377. this.recorderManager.onStart(() => {
  1378. console.log('✅ 录音开始回调触发');
  1379. this.isRecording = true;
  1380. this.showVoiceRecording = true;
  1381. this.voiceStartTime = Date.now();
  1382. this.voiceRecordingTime = 0;
  1383. this.voiceVolume = 0.3;
  1384. console.log(' - isRecording:', this.isRecording);
  1385. console.log(' - showVoiceRecording:', this.showVoiceRecording);
  1386. // 启动计时器
  1387. let volumeDirection = 1;
  1388. let currentVolume = 0.3;
  1389. this.voiceRecordingTimer = setInterval(() => {
  1390. this.voiceRecordingTime = Math.floor((Date.now() - this.voiceStartTime) / 1000);
  1391. // 检查是否达到60秒,自动停止录音
  1392. if (this.voiceRecordingTime >= 60) {
  1393. console.log('⏰ 录音时长达到60秒,自动停止');
  1394. clearInterval(this.voiceRecordingTimer);
  1395. this.voiceRecordingTimer = null;
  1396. this.voiceCanceling = false; // 确保不是取消状态
  1397. if (this.recorderManager) {
  1398. this.recorderManager.stop();
  1399. }
  1400. return;
  1401. }
  1402. // 模拟更真实的音量波动
  1403. if (Math.random() > 0.2) {
  1404. currentVolume += volumeDirection * (0.1 + Math.random() * 0.2);
  1405. if (currentVolume > 1.0) {
  1406. currentVolume = 1.0;
  1407. volumeDirection = -1;
  1408. } else if (currentVolume < 0.4) {
  1409. currentVolume = 0.4;
  1410. volumeDirection = 1;
  1411. }
  1412. this.voiceVolume = currentVolume;
  1413. } else {
  1414. this.voiceVolume = Math.max(0.2, this.voiceVolume * 0.8);
  1415. }
  1416. }, 100);
  1417. });
  1418. // 录音结束
  1419. this.recorderManager.onStop((res) => {
  1420. console.log('🎤 录音结束:', res, ', voiceCanceling:', this.voiceCanceling);
  1421. this.isRecording = false;
  1422. this.showVoiceRecording = false;
  1423. // 清除计时器
  1424. if (this.voiceRecordingTimer) {
  1425. clearInterval(this.voiceRecordingTimer);
  1426. this.voiceRecordingTimer = null;
  1427. }
  1428. // 如果是取消状态,不发送
  1429. if (this.voiceCanceling) {
  1430. console.log('❌ 录音已取消,不发送');
  1431. this.voiceCanceling = false;
  1432. return;
  1433. }
  1434. this.voiceTempPath = res.tempFilePath;
  1435. this.voiceDuration = Math.floor(res.duration / 1000); // 转换为秒
  1436. console.log(' - 文件路径:', this.voiceTempPath);
  1437. console.log(' - 时长:', this.voiceDuration, '秒');
  1438. // 时长验证
  1439. if (this.voiceDuration < 1) {
  1440. uni.showToast({
  1441. title: '录音时间太短',
  1442. icon: 'none'
  1443. });
  1444. return;
  1445. }
  1446. if (this.voiceDuration > 60) {
  1447. uni.showToast({
  1448. title: '录音时间不能超过60秒',
  1449. icon: 'none'
  1450. });
  1451. return;
  1452. }
  1453. // 发送语音消息
  1454. this.sendVoiceMessage();
  1455. });
  1456. // 录音错误
  1457. this.recorderManager.onError((err) => {
  1458. console.error('❌ 录音错误:', err);
  1459. // 立即清理录音状态和界面
  1460. this.isRecording = false;
  1461. this.showVoiceRecording = false;
  1462. this.voiceCanceling = true;
  1463. // 清除计时器
  1464. if (this.voiceRecordingTimer) {
  1465. clearInterval(this.voiceRecordingTimer);
  1466. this.voiceRecordingTimer = null;
  1467. }
  1468. // 如果是权限错误,不显示任何提示(用户会看到系统权限弹窗)
  1469. // 其他错误才显示提示
  1470. if (err.errCode !== 'authorize' && err.errMsg && !err.errMsg.includes('authorize')) {
  1471. uni.showToast({
  1472. title: '录音失败',
  1473. icon: 'none'
  1474. });
  1475. }
  1476. console.log('✅ 已清理录音状态,隐藏录音界面');
  1477. });
  1478. }
  1479. // 开始录音(等待 onStart 回调后才显示界面)
  1480. console.log('🎙️ 调用 recorderManager.start()');
  1481. try {
  1482. this.recorderManager.start({
  1483. format: 'mp3',
  1484. sampleRate: 16000,
  1485. numberOfChannels: 1,
  1486. encodeBitRate: 48000
  1487. });
  1488. console.log('✅ recorderManager.start() 调用成功');
  1489. } catch (err) {
  1490. console.error('❌ recorderManager.start() 调用失败:', err);
  1491. this.isRecording = false;
  1492. this.showVoiceRecording = false;
  1493. }
  1494. },
  1495. /**
  1496. * 停止录音
  1497. */
  1498. stopVoiceRecord() {
  1499. console.log('🎤 [松开] stopVoiceRecord 方法被调用, isRecording:', this.isRecording, ', voiceCanceling:', this.voiceCanceling);
  1500. // 清除计时器
  1501. if (this.voiceRecordingTimer) {
  1502. clearInterval(this.voiceRecordingTimer);
  1503. this.voiceRecordingTimer = null;
  1504. }
  1505. // 如果正在取消,则取消录音
  1506. if (this.voiceCanceling) {
  1507. console.log('🚫 检测到取消状态,调用 cancelVoiceRecord');
  1508. this.cancelVoiceRecord();
  1509. return;
  1510. }
  1511. if (this.isRecording && this.recorderManager) {
  1512. const duration = Date.now() - this.voiceStartTime;
  1513. // 录音时间太短
  1514. if (duration < 1000) {
  1515. this.recorderManager.stop();
  1516. this.isRecording = false;
  1517. this.showVoiceRecording = false;
  1518. uni.showToast({
  1519. title: '录音时间太短',
  1520. icon: 'none'
  1521. });
  1522. return;
  1523. }
  1524. this.recorderManager.stop();
  1525. }
  1526. },
  1527. /**
  1528. * 触摸移动 - 检测上滑取消
  1529. */
  1530. onVoiceTouchMove(e) {
  1531. if (!this.isRecording) return;
  1532. const currentY = e.touches[0].clientY;
  1533. const deltaY = this.voiceTouchStartY - currentY;
  1534. // 上滑超过100px,显示取消提示
  1535. if (deltaY > 100) {
  1536. this.voiceCanceling = true;
  1537. console.log('⬆️ 上滑取消录音');
  1538. } else {
  1539. this.voiceCanceling = false;
  1540. }
  1541. },
  1542. /**
  1543. * 取消录音
  1544. */
  1545. cancelVoiceRecord() {
  1546. console.log('❌ 取消录音, voiceCanceling:', this.voiceCanceling);
  1547. // 清除计时器
  1548. if (this.voiceRecordingTimer) {
  1549. clearInterval(this.voiceRecordingTimer);
  1550. this.voiceRecordingTimer = null;
  1551. }
  1552. // 先设置取消状态,再停止录音
  1553. // 这样onStop回调中能正确判断
  1554. if (!this.voiceCanceling) {
  1555. this.voiceCanceling = true;
  1556. }
  1557. if (this.recorderManager && this.isRecording) {
  1558. this.recorderManager.stop(); // 这会触发onStop回调
  1559. } else {
  1560. // 如果没有在录音,直接重置状态
  1561. this.isRecording = false;
  1562. this.showVoiceRecording = false;
  1563. this.voiceCanceling = false;
  1564. }
  1565. uni.showToast({
  1566. title: '已取消录音',
  1567. icon: 'none'
  1568. });
  1569. },
  1570. /**
  1571. * 发送语音消息
  1572. */
  1573. async sendVoiceMessage() {
  1574. // 检查是否被拉黑
  1575. const isBlocked = await this.checkIsBlockedByTarget();
  1576. if (isBlocked) {
  1577. uni.showToast({
  1578. title: '你已被对方拉黑,无法发送消息',
  1579. icon: 'none'
  1580. });
  1581. return;
  1582. }
  1583. try {
  1584. uni.showLoading({ title: '上传中...' });
  1585. // 第一步:上传语音文件到MinIO
  1586. const uploadResult = await this.uploadVoiceToMinIO();
  1587. if (!uploadResult.success) {
  1588. throw new Error(uploadResult.message || '上传失败');
  1589. }
  1590. console.log('✅ 语音文件上传成功:', uploadResult.fileUrl);
  1591. uni.showLoading({ title: '发送中...' });
  1592. // 第二步:通过腾讯IM发送语音消息(携带MinIO URL)
  1593. const message = await timManager.sendVoiceMessage(
  1594. this.targetUserId,
  1595. uploadResult.fileUrl,
  1596. this.voiceDuration,
  1597. uploadResult.fileSize
  1598. );
  1599. // 添加到消息列表
  1600. this.messages.push(this.convertMessage(message));
  1601. this.scrollToBottom();
  1602. uni.hideLoading();
  1603. console.log('✅ 语音消息发送成功');
  1604. // 同步到MySQL
  1605. this.syncMessageToMySQL(message);
  1606. // 更新消息计数
  1607. if (!this.isVip) {
  1608. await this.updateMessageCount();
  1609. }
  1610. } catch (error) {
  1611. uni.hideLoading();
  1612. console.error('❌ 语音消息发送失败:', error);
  1613. uni.showToast({
  1614. title: '发送失败: ' + error.message,
  1615. icon: 'none'
  1616. });
  1617. }
  1618. },
  1619. /**
  1620. * 上传语音文件到MinIO
  1621. */
  1622. async uploadVoiceToMinIO() {
  1623. try {
  1624. console.log('📤 开始上传语音文件到MinIO...');
  1625. console.log(' - 文件路径:', this.voiceTempPath);
  1626. console.log(' - 时长:', this.voiceDuration, '秒');
  1627. // 使用uni.uploadFile上传到后端MinIO接口
  1628. const [err, res] = await uni.uploadFile({
  1629. url: 'http://localhost:1004/api/voice/upload',
  1630. filePath: this.voiceTempPath,
  1631. name: 'file',
  1632. header: {
  1633. 'Content-Type': 'multipart/form-data'
  1634. }
  1635. });
  1636. if (err) {
  1637. console.error('❌ 上传请求失败:', err);
  1638. return {
  1639. success: false,
  1640. message: '网络请求失败'
  1641. };
  1642. }
  1643. // 解析响应
  1644. const result = JSON.parse(res.data);
  1645. console.log('📥 MinIO上传响应:', result);
  1646. if (result.success) {
  1647. return {
  1648. success: true,
  1649. fileUrl: result.fileUrl,
  1650. fileSize: result.fileSize
  1651. };
  1652. } else {
  1653. return {
  1654. success: false,
  1655. message: result.message || '上传失败'
  1656. };
  1657. }
  1658. } catch (error) {
  1659. console.error('❌ 上传语音文件失败:', error);
  1660. return {
  1661. success: false,
  1662. message: error.message || '上传异常'
  1663. };
  1664. }
  1665. },
  1666. insertEmoji(emoji) {
  1667. this.inputText += emoji;
  1668. this.showEmojiPanel = false;
  1669. },
  1670. chooseVideo() {
  1671. uni.showToast({
  1672. title: '视频功能开发中',
  1673. icon: 'none'
  1674. });
  1675. },
  1676. chooseFile() {
  1677. uni.showToast({
  1678. title: '文件功能开发中',
  1679. icon: 'none'
  1680. });
  1681. },
  1682. /**
  1683. * 切换语音播放/暂停
  1684. */
  1685. toggleVoicePlay(msg) {
  1686. // 如果正在播放这条语音,则暂停
  1687. if (this.playingVoiceId === msg.messageId) {
  1688. this.pauseVoice(msg);
  1689. } else {
  1690. // 否则开始播放
  1691. this.playVoice(msg);
  1692. }
  1693. },
  1694. /**
  1695. * 播放语音
  1696. */
  1697. playVoice(msg) {
  1698. console.log('📢 [播放语音] 开始 - messageId:', msg.messageId);
  1699. if (!msg.mediaUrl) {
  1700. // 如果是TIM消息,从payload中获取URL
  1701. const audioUrl = msg.payload?.url || msg.payload?.remoteAudioUrl;
  1702. if (!audioUrl) {
  1703. uni.showToast({
  1704. title: '语音文件不存在',
  1705. icon: 'none'
  1706. });
  1707. return;
  1708. }
  1709. msg.mediaUrl = audioUrl;
  1710. }
  1711. // 如果有其他语音正在播放,先停止
  1712. if (this.currentAudioContext) {
  1713. console.log('⏹️ 停止之前的语音');
  1714. this.currentAudioContext.stop();
  1715. this.currentAudioContext.destroy();
  1716. this.currentAudioContext = null;
  1717. }
  1718. // 清除暂停状态
  1719. this.pausedVoiceId = null;
  1720. // 设置当前播放的语音ID,触发动画
  1721. this.playingVoiceId = msg.messageId;
  1722. console.log('🎬 [动画开始] playingVoiceId =', this.playingVoiceId);
  1723. // 创建音频上下文
  1724. const innerAudioContext = uni.createInnerAudioContext();
  1725. innerAudioContext.src = msg.mediaUrl;
  1726. innerAudioContext.loop = false; // 不循环播放
  1727. this.currentAudioContext = innerAudioContext;
  1728. innerAudioContext.onPlay(() => {
  1729. console.log('🔊 开始播放语音');
  1730. });
  1731. innerAudioContext.onEnded(() => {
  1732. console.log('✅ 语音播放完成');
  1733. this.playingVoiceId = null; // 停止动画
  1734. this.pausedVoiceId = null;
  1735. this.currentAudioContext = null;
  1736. console.log('🛑 [动画停止] playingVoiceId =', this.playingVoiceId);
  1737. innerAudioContext.destroy();
  1738. });
  1739. innerAudioContext.onError((err) => {
  1740. console.error('❌ 语音播放失败:', err);
  1741. this.playingVoiceId = null; // 停止动画
  1742. this.pausedVoiceId = null;
  1743. this.currentAudioContext = null;
  1744. console.log('🛑 [动画停止-错误] playingVoiceId =', this.playingVoiceId);
  1745. uni.showToast({
  1746. title: '播放失败',
  1747. icon: 'none'
  1748. });
  1749. innerAudioContext.destroy();
  1750. });
  1751. innerAudioContext.play();
  1752. },
  1753. /**
  1754. * 暂停语音
  1755. */
  1756. pauseVoice(msg) {
  1757. if (this.currentAudioContext) {
  1758. this.currentAudioContext.pause();
  1759. this.playingVoiceId = null; // 停止动画
  1760. this.pausedVoiceId = msg.messageId; // 设置暂停状态
  1761. console.log('⏸️ [暂停] playingVoiceId =', this.playingVoiceId, ', pausedVoiceId =', this.pausedVoiceId);
  1762. }
  1763. },
  1764. /**
  1765. * 继续播放语音
  1766. */
  1767. resumeVoice() {
  1768. if (this.currentAudioContext && this.pausedVoiceId) {
  1769. this.currentAudioContext.play();
  1770. this.playingVoiceId = this.pausedVoiceId; // 恢复动画
  1771. const resumedId = this.pausedVoiceId;
  1772. this.pausedVoiceId = null; // 清除暂停状态
  1773. console.log('▶️ [继续播放] playingVoiceId =', this.playingVoiceId, ', pausedVoiceId =', this.pausedVoiceId);
  1774. }
  1775. },
  1776. showMoreOptions() {
  1777. this.showMoreOptionsModal = true;
  1778. },
  1779. closeMoreOptions() {
  1780. this.showMoreOptionsModal = false;
  1781. },
  1782. /**
  1783. * 查看用户资料(跳转到原有more页面)
  1784. */
  1785. goToUserProfile() {
  1786. this.closeMoreOptions();
  1787. uni.navigateTo({
  1788. url: `/pages/message/more?userid=${this.targetUserId}`,
  1789. fail: (err) => {
  1790. console.error('跳转失败:', err);
  1791. uni.showToast({
  1792. title: '页面不存在',
  1793. icon: 'none'
  1794. });
  1795. }
  1796. });
  1797. },
  1798. /**
  1799. * 显示拉黑确认弹窗
  1800. */
  1801. blockFriend() {
  1802. this.closeMoreOptions();
  1803. this.showBlockConfirmModal = true;
  1804. },
  1805. /**
  1806. * 关闭拉黑确认弹窗
  1807. */
  1808. closeBlockConfirm() {
  1809. this.showBlockConfirmModal = false;
  1810. },
  1811. /**
  1812. * 从后端获取VIP状态和今日剩余发送次数
  1813. */
  1814. async getUserMessageLimit() {
  1815. try {
  1816. const [err, res] = await uni.request({
  1817. url: 'http://localhost:1004/api/chat/getUserMessageLimit',
  1818. method: 'GET',
  1819. data: {
  1820. userId: this.userId ,// 已在onLoad中初始化的当前用户ID
  1821. targetUserId: this.targetUserId
  1822. },
  1823. header: {
  1824. 'Content-Type': 'application/json'
  1825. }
  1826. });
  1827. if (err) throw new Error('网络请求失败');
  1828. if (res.data.code !== 200) throw new Error(res.data.message || '获取限制信息失败');
  1829. const { isVip, remainingCount, hasMessageLimit } = res.data.data;
  1830. this.isVip = isVip;
  1831. this.remainingCount = remainingCount;
  1832. this.hasMessageLimit = hasMessageLimit;
  1833. console.log('✅ 用户消息限制信息:', { isVip, remainingCount, hasMessageLimit });
  1834. } catch (error) {
  1835. console.error('❌ 获取消息限制失败:', error);
  1836. // 异常降级:默认非VIP,剩余5次
  1837. this.isVip = false;
  1838. this.remainingCount = 5;
  1839. this.hasMessageLimit = true;
  1840. }
  1841. },
  1842. /**
  1843. * 发送成功后,更新后端计数并同步前端剩余次数
  1844. */
  1845. async updateMessageCount() {
  1846. try {
  1847. const [err, res] = await uni.request({
  1848. url: 'http://localhost:8083/api/chat/updateMessageCount',
  1849. method: 'get',
  1850. data: {
  1851. userId: this.userId ,// 已在onLoad中初始化的当前用户ID
  1852. targetUserId: this.targetUserId
  1853. },
  1854. header: {
  1855. 'Content-Type': 'application/json'
  1856. }
  1857. });
  1858. if (err) throw new Error('更新计数失败');
  1859. if (res.data.code === 200) {
  1860. this.remainingCount = res.data.data.remainingCount; // 同步后端返回的剩余次数
  1861. }
  1862. } catch (error) {
  1863. console.error('❌ 更新发送次数失败:', error);
  1864. // 前端本地降级:避免影响用户体验,本地暂减1(刷新页面后同步真实数据)
  1865. if (this.remainingCount > 0) {
  1866. this.remainingCount--;
  1867. }
  1868. }
  1869. },
  1870. /**
  1871. * 确认拉黑好友
  1872. */
  1873. async confirmBlockFriend() {
  1874. try {
  1875. uni.showLoading({
  1876. title: '处理中...'
  1877. });
  1878. // 调用后端拉黑接口(根据实际接口调整)
  1879. const [err, res] = await uni.request({
  1880. url: 'http://localhost:8083/api/chatfriend/block',
  1881. method: 'POST',
  1882. data: {
  1883. userId: this.userId,
  1884. targetUserId: this.targetUserId,
  1885. targetUserName: this.targetUserName,
  1886. targetUserAvatar: this.targetUserAvatar
  1887. },
  1888. header: {
  1889. 'Content-Type': 'application/json',
  1890. // 'Authorization': 'Bearer ' + uni.getStorageSync('token')
  1891. }
  1892. });
  1893. uni.hideLoading();
  1894. if (err) throw new Error('网络请求失败');
  1895. if (res.data && res.data.code === 200) {
  1896. uni.showToast({ title: '拉黑成功', icon: 'success' });
  1897. this.closeBlockConfirm();
  1898. // 触发拉黑列表更新事件,通知消息页面实时刷新
  1899. uni.$emit('blacklistUpdated');
  1900. // 拉黑成功后立即返回消息列表页面(优化体验)
  1901. setTimeout(() => {
  1902. uni.navigateBack({
  1903. delta: 1,
  1904. success: () => {
  1905. // 返回成功后再次触发一次刷新,确保万无一失
  1906. uni.$emit('blacklistUpdated');
  1907. }
  1908. });
  1909. }, 1500);
  1910. } else {
  1911. throw new Error(res.data?.message || '拉黑失败');
  1912. }
  1913. } catch (error) {
  1914. console.error('拉黑失败:', error);
  1915. uni.showToast({ title: error.message || '拉黑失败', icon: 'none' });
  1916. }
  1917. },
  1918. /**
  1919. * 初始化在线状态监听(WebSocket 实时推送 + HTTP 轮询)
  1920. */
  1921. async initOnlineStatusPolling() {
  1922. console.log('🔄 初始化在线状态监听(WebSocket + HTTP)');
  1923. const timPresenceManager = require('@/utils/tim-presence-manager.js').default;
  1924. // 1. 立即查询一次
  1925. await this.checkOnlineStatus();
  1926. // 2. 监听 WebSocket 实时推送(实时性强)
  1927. this.onlineStatusCallback = (status) => {
  1928. console.log(`⚡ 实时收到用户 ${this.targetUserId} 状态变更: ${status}`);
  1929. this.isTargetOnline = (status === 'online');
  1930. };
  1931. timPresenceManager.onStatusChange(this.targetUserId, this.onlineStatusCallback);
  1932. // 3. 启动 HTTP 轮询作为补充(30秒间隔)
  1933. this.onlineStatusTimer = setInterval(() => {
  1934. this.checkOnlineStatus();
  1935. }, 30000);
  1936. console.log('✅ 在线状态监听已启动(WebSocket 实时 + HTTP 轮询)');
  1937. },
  1938. /**
  1939. * 查询在线状态
  1940. */
  1941. async checkOnlineStatus() {
  1942. try {
  1943. const [err, res] = await uni.request({
  1944. url: 'http://localhost:8083/api/online/checkStatus',
  1945. method: 'GET',
  1946. data: {
  1947. userId: this.targetUserId
  1948. }
  1949. });
  1950. if (!err && res.data && res.data.code === 200) {
  1951. this.isTargetOnline = res.data.data.online || false;
  1952. console.log(`� 用户 ${this.targetUserId} 在线状态:`, this.isTargetOnline);
  1953. }
  1954. } catch (error) {
  1955. console.error('❌ 查询在线状态失败:', error);
  1956. }
  1957. }
  1958. },
  1959. /**
  1960. * 页面卸载时清理
  1961. */
  1962. onUnload() {
  1963. console.log('=== 聊天页面卸载 ===');
  1964. // 清理在线状态轮询
  1965. if (this.onlineStatusTimer) {
  1966. clearInterval(this.onlineStatusTimer);
  1967. this.onlineStatusTimer = null;
  1968. console.log('✅ 已停止在线状态轮询');
  1969. }
  1970. // 清理 WebSocket 监听
  1971. if (this.onlineStatusCallback) {
  1972. const timPresenceManager = require('@/utils/tim-presence-manager.js').default;
  1973. timPresenceManager.offStatusChange(this.targetUserId, this.onlineStatusCallback);
  1974. console.log('✅ 已清理 WebSocket 监听');
  1975. }
  1976. // 清理已读回执监听
  1977. if (this.handleMessageReadByPeer && timManager.tim) {
  1978. timManager.tim.off(TIM.EVENT.MESSAGE_READ_BY_PEER, this.handleMessageReadByPeer);
  1979. console.log('✅ 已清理已读回执监听');
  1980. }
  1981. // 清理新消息监听
  1982. if (this.handleNewMessage) {
  1983. timManager.offMessage(this.handleNewMessage);
  1984. console.log('✅ 已清理新消息监听');
  1985. }
  1986. }
  1987. };
  1988. </script>
  1989. <style scoped>
  1990. /* 弹窗遮罩 */
  1991. .modal-mask {
  1992. position: fixed;
  1993. top: 0;
  1994. left: 0;
  1995. right: 0;
  1996. bottom: 0;
  1997. background-color: rgba(0, 0, 0, 0.5);
  1998. z-index: 10000;
  1999. display: flex;
  2000. align-items: center;
  2001. justify-content: center;
  2002. }
  2003. /* 更多选项弹窗内容 */
  2004. .modal-content {
  2005. width: 70%;
  2006. background-color: #fff;
  2007. border-radius: 20rpx;
  2008. overflow: hidden;
  2009. }
  2010. .modal-header {
  2011. padding: 30rpx;
  2012. text-align: center;
  2013. border-bottom: 1px solid #eee;
  2014. }
  2015. .modal-title {
  2016. font-size: 32rpx;
  2017. font-weight: bold;
  2018. display: block;
  2019. }
  2020. .modal-subtitle {
  2021. font-size: 24rpx;
  2022. color: #999;
  2023. display: block;
  2024. margin-top: 10rpx;
  2025. }
  2026. .modal-body {
  2027. padding: 20rpx 0;
  2028. }
  2029. .modal-item {
  2030. display: flex;
  2031. align-items: center;
  2032. padding: 25rpx 40rpx;
  2033. font-size: 30rpx;
  2034. }
  2035. .modal-item.danger {
  2036. color: #fa5151;
  2037. }
  2038. .item-icon {
  2039. font-size: 32rpx;
  2040. margin-right: 20rpx;
  2041. }
  2042. .modal-footer {
  2043. padding: 20rpx;
  2044. border-top: 1px solid #eee;
  2045. }
  2046. .modal-close-btn {
  2047. width: 94%;
  2048. background-color: #f5f5f5;
  2049. border: none;
  2050. border-radius: 10rpx;
  2051. padding: 20rpx;
  2052. font-size: 30rpx;
  2053. }
  2054. /* 确认弹窗样式 */
  2055. .confirm-modal {
  2056. width: 60%;
  2057. background-color: #fff;
  2058. border-radius: 20rpx;
  2059. padding: 40rpx;
  2060. text-align: center;
  2061. }
  2062. .confirm-title {
  2063. font-size: 32rpx;
  2064. font-weight: bold;
  2065. margin-bottom: 30rpx;
  2066. }
  2067. .confirm-content {
  2068. font-size: 28rpx;
  2069. color: #666;
  2070. margin-bottom: 40rpx;
  2071. line-height: 1.5;
  2072. }
  2073. .confirm-buttons {
  2074. display: flex;
  2075. justify-content: space-between;
  2076. }
  2077. .confirm-btn {
  2078. flex: 1;
  2079. margin: 0 10rpx;
  2080. padding: 20rpx;
  2081. border-radius: 10rpx;
  2082. border: none;
  2083. font-size: 28rpx;
  2084. }
  2085. .confirm-btn.cancel {
  2086. background-color: #f5f5f5;
  2087. }
  2088. .confirm-btn.confirm {
  2089. background-color: #fa5151;
  2090. color: #fff;
  2091. }
  2092. .chat-page {
  2093. display: flex;
  2094. flex-direction: column;
  2095. height: 100vh;
  2096. background-color: #f5f5f5;
  2097. }
  2098. /* 顶部导航 */
  2099. .chat-header {
  2100. display: flex;
  2101. align-items: center;
  2102. justify-content: space-between;
  2103. padding: 20rpx 30rpx;
  2104. background-color: #fff;
  2105. border-bottom: 1px solid #e5e5e5;
  2106. }
  2107. .header-left, .header-right {
  2108. width: 80rpx;
  2109. }
  2110. .icon-back, .icon-more {
  2111. font-size: 40rpx;
  2112. }
  2113. .header-center {
  2114. flex: 1;
  2115. text-align: center;
  2116. }
  2117. .chat-title {
  2118. display: block;
  2119. font-size: 36rpx;
  2120. font-weight: bold;
  2121. }
  2122. .online-status {
  2123. display: block;
  2124. font-size: 24rpx;
  2125. color: #999;
  2126. margin-top: 5rpx;
  2127. }
  2128. .online-status.online {
  2129. color: #07c160;
  2130. }
  2131. /* 消息列表 */
  2132. .message-list {
  2133. flex: 1;
  2134. padding: 20rpx;
  2135. overflow-y: scroll;
  2136. }
  2137. .loading-tip {
  2138. text-align: center;
  2139. padding: 20rpx;
  2140. color: #999;
  2141. font-size: 28rpx;
  2142. }
  2143. .message-item {
  2144. display: flex;
  2145. margin-bottom: 30rpx;
  2146. }
  2147. .message-item.message-self {
  2148. flex-direction: row-reverse;
  2149. }
  2150. .avatar {
  2151. width: 80rpx;
  2152. height: 80rpx;
  2153. border-radius: 8rpx;
  2154. margin: 0 20rpx;
  2155. }
  2156. .message-content-wrapper {
  2157. max-width: 70%;
  2158. display: inline-block;
  2159. }
  2160. .message-item.message-self .message-content-wrapper {
  2161. text-align: right; /* 关键:让气泡和状态提示整体右对齐 */
  2162. }
  2163. .message-name {
  2164. display: block;
  2165. font-size: 24rpx;
  2166. color: #999;
  2167. margin-bottom: 10rpx;
  2168. }
  2169. .message-bubble {
  2170. padding: 20rpx;
  2171. border-radius: 8rpx;
  2172. background-color: #fff;
  2173. word-wrap: break-word;
  2174. display: inline-block; /* 关键:气泡宽度由内容决定 */
  2175. max-width: 100%; /* 防止内容过长超出容器 */
  2176. position: relative;
  2177. }
  2178. .message-self .message-bubble {
  2179. background-color: #95ec69;
  2180. border-top-right-radius: 4rpx;
  2181. }
  2182. .message-bubble.bubble-self {
  2183. background-color: #95ec69;
  2184. }
  2185. .message-text {
  2186. font-size: 30rpx;
  2187. line-height: 1.5;
  2188. }
  2189. .message-image {
  2190. max-width: 400rpx;
  2191. border-radius: 8rpx;
  2192. }
  2193. .message-voice {
  2194. display: flex;
  2195. align-items: center;
  2196. gap: 12rpx;
  2197. padding: 0rpx 0;
  2198. min-width: 30rpx;
  2199. max-width: 400rpx;
  2200. cursor: pointer;
  2201. -webkit-tap-highlight-color: transparent;
  2202. outline: none;
  2203. border: none;
  2204. position: relative;
  2205. }
  2206. .voice-duration {
  2207. font-size: 27rpx;
  2208. color: #333;
  2209. flex-shrink: 0;
  2210. line-height: 1;
  2211. }
  2212. .voice-icon-wrapper {
  2213. display: flex;
  2214. flex-shrink: 0;
  2215. line-height: 0;
  2216. position: relative;
  2217. top: 1rpx;
  2218. }
  2219. .voice-icon {
  2220. width: 22rpx;
  2221. height: 22rpx;
  2222. display: block;
  2223. transform: none;
  2224. animation: none;
  2225. }
  2226. .voice-icon-wrapper.playing .voice-icon {
  2227. animation: voice-bounce 0.6s ease-in-out infinite;
  2228. }
  2229. .voice-resume-btn {
  2230. position: absolute;
  2231. top: 50%;
  2232. transform: translateY(-50%);
  2233. width: 32rpx;
  2234. height: 32rpx;
  2235. background: #07c160;
  2236. border-radius: 50%;
  2237. display: flex;
  2238. align-items: center;
  2239. justify-content: center;
  2240. box-shadow: 0 2rpx 8rpx rgba(7, 193, 96, 0.3);
  2241. }
  2242. .voice-resume-btn.resume-btn-left {
  2243. left: -40rpx;
  2244. }
  2245. .voice-resume-btn.resume-btn-right {
  2246. right: -40rpx;
  2247. }
  2248. .resume-icon {
  2249. color: #fff;
  2250. font-size: 16rpx;
  2251. margin-left: 2rpx;
  2252. }
  2253. @keyframes voice-bounce {
  2254. 0%, 100% {
  2255. transform: scale(1);
  2256. }
  2257. 50% {
  2258. transform: scale(1.2);
  2259. }
  2260. }
  2261. .message-video {
  2262. width: 400rpx;
  2263. height: 300rpx;
  2264. }
  2265. .message-recalled {
  2266. color: #999;
  2267. font-size: 28rpx;
  2268. }
  2269. .message-status {
  2270. text-align: right;
  2271. font-size: 22rpx;
  2272. color: #999;
  2273. margin-top: 8rpx;
  2274. }
  2275. .message-status .status-unread {
  2276. color: #999;
  2277. }
  2278. .message-status .status-read {
  2279. color: #07c160;
  2280. }
  2281. .message-status .status-failed {
  2282. color: #fa5151;
  2283. }
  2284. .message-time {
  2285. display: block;
  2286. text-align: right;
  2287. font-size: 22rpx;
  2288. color: #ccc;
  2289. margin-top: 5rpx;
  2290. }
  2291. /* 输入框 */
  2292. .input-bar {
  2293. display: flex;
  2294. align-items: center;
  2295. padding: 20rpx;
  2296. background-color: #fff;
  2297. border-top: 1px solid #e5e5e5;
  2298. }
  2299. .input-icon {
  2300. width: 80rpx;
  2301. height: 80rpx;
  2302. display: flex;
  2303. align-items: center;
  2304. justify-content: center;
  2305. font-size: 50rpx;
  2306. }
  2307. .input-icon .icon-image {
  2308. width: 50rpx;
  2309. height: 50rpx;
  2310. }
  2311. .send-button {
  2312. padding: 0 30rpx;
  2313. height: 70rpx;
  2314. line-height: 70rpx;
  2315. background-color: #07c160;
  2316. color: #fff;
  2317. border-radius: 8rpx;
  2318. text-align: center;
  2319. font-size: 28rpx;
  2320. margin-left: 10rpx;
  2321. transition: opacity 0.3s;
  2322. }
  2323. .send-button.disabled {
  2324. opacity: 0.5;
  2325. background-color: #95ec69;
  2326. }
  2327. .input-field {
  2328. flex: 1;
  2329. height: 70rpx;
  2330. padding: 0 20rpx;
  2331. background-color: #f5f5f5;
  2332. border-radius: 8rpx;
  2333. font-size: 30rpx;
  2334. }
  2335. .voice-button {
  2336. flex: 1;
  2337. height: 70rpx;
  2338. line-height: 70rpx;
  2339. background-color: #f5f5f5;
  2340. border-radius: 8rpx;
  2341. text-align: center;
  2342. font-size: 30rpx;
  2343. border: none;
  2344. }
  2345. /* 表情面板 */
  2346. .emoji-panel {
  2347. display: flex;
  2348. flex-wrap: wrap;
  2349. padding: 20rpx;
  2350. background-color: #fff;
  2351. border-top: 1px solid #e5e5e5;
  2352. }
  2353. .emoji-item {
  2354. width: 80rpx;
  2355. height: 80rpx;
  2356. display: flex;
  2357. align-items: center;
  2358. justify-content: center;
  2359. font-size: 60rpx;
  2360. }
  2361. /* 更多功能面板 */
  2362. .more-panel {
  2363. display: flex;
  2364. padding: 40rpx;
  2365. background-color: #fff;
  2366. border-top: 1px solid #e5e5e5;
  2367. }
  2368. .more-item {
  2369. display: flex;
  2370. flex-direction: column;
  2371. align-items: center;
  2372. margin: 0 40rpx;
  2373. }
  2374. .more-icon {
  2375. width: 100rpx;
  2376. height: 100rpx;
  2377. display: flex;
  2378. align-items: center;
  2379. justify-content: center;
  2380. font-size: 60rpx;
  2381. background-color: #f5f5f5;
  2382. border-radius: 16rpx;
  2383. margin-bottom: 10rpx;
  2384. }
  2385. .more-text {
  2386. font-size: 24rpx;
  2387. color: #666;
  2388. }
  2389. /* 时间分隔线 */
  2390. .time-divider {
  2391. text-align: center;
  2392. padding: 20rpx 0;
  2393. }
  2394. .time-text {
  2395. display: inline-block;
  2396. padding: 8rpx 20rpx;
  2397. background-color: rgba(0, 0, 0, 0.1);
  2398. border-radius: 8rpx;
  2399. font-size: 22rpx;
  2400. color: #999;
  2401. }
  2402. /* 消息气泡失败状态 */
  2403. .bubble-failed {
  2404. background-color: #95ec69;
  2405. opacity: 0.6;
  2406. border: 2rpx solid #fa5151;
  2407. }
  2408. /* 消息状态优化 */
  2409. .message-status .sending {
  2410. color: #576b95;
  2411. }
  2412. .message-status .failed-group {
  2413. display: flex;
  2414. align-items: center;
  2415. gap: 10rpx;
  2416. }
  2417. .message-status .retry-btn {
  2418. color: #576b95;
  2419. text-decoration: underline;
  2420. cursor: pointer;
  2421. }
  2422. /* 消息操作菜单遮罩 */
  2423. .message-action-mask {
  2424. position: fixed;
  2425. top: 0;
  2426. left: 0;
  2427. right: 0;
  2428. bottom: 0;
  2429. background-color: rgba(0, 0, 0, 0.4);
  2430. z-index: 9999;
  2431. display: flex;
  2432. align-items: center;
  2433. justify-content: center;
  2434. }
  2435. /* 消息操作菜单 */
  2436. .message-action-menu {
  2437. width: 600rpx;
  2438. background-color: #fff;
  2439. border-radius: 20rpx;
  2440. overflow: hidden;
  2441. }
  2442. .message-action-menu .menu-item {
  2443. display: flex;
  2444. align-items: center;
  2445. justify-content: center;
  2446. gap: 15rpx;
  2447. padding: 30rpx;
  2448. font-size: 32rpx;
  2449. color: #333;
  2450. border-bottom: 1rpx solid #f0f0f0;
  2451. transition: background-color 0.2s;
  2452. }
  2453. .message-action-menu .menu-item:active {
  2454. background-color: #f5f5f5;
  2455. }
  2456. .message-action-menu .menu-item.cancel {
  2457. color: #999;
  2458. border-bottom: none;
  2459. margin-top: 20rpx;
  2460. border-top: 10rpx solid #f5f5f5;
  2461. }
  2462. .message-action-menu .menu-icon {
  2463. font-size: 36rpx;
  2464. }
  2465. /* 消息发送限制提示 */
  2466. .message-limit-tip {
  2467. padding: 10rpx 20rpx;
  2468. font-size: 24rpx;
  2469. text-align: center;
  2470. background-color: #fff;
  2471. border-bottom: 1px solid #f5f5f5;
  2472. }
  2473. .vip-tip {
  2474. color: #ff9500; /* VIP橙色提示 */
  2475. }
  2476. .limit-tip {
  2477. color: #666; /* 普通灰色提示 */
  2478. }
  2479. .vip-link {
  2480. color: #2c9fff; /* 蓝色文字 */
  2481. text-decoration: underline; /* 下划线 */
  2482. cursor: pointer; /* 鼠标悬浮时显示手型 */
  2483. margin-left: 5rpx;
  2484. }
  2485. /* 点击时添加轻微反馈 */
  2486. .vip-link:active {
  2487. opacity: 0.7; /* 点击时透明度降低 */
  2488. }
  2489. /* 录音中提示遮罩 */
  2490. .voice-recording-mask {
  2491. position: fixed;
  2492. top: 0;
  2493. left: 0;
  2494. right: 0;
  2495. bottom: 0;
  2496. background-color: rgba(0, 0, 0, 0.6);
  2497. z-index: 10000;
  2498. display: flex;
  2499. align-items: center;
  2500. justify-content: center;
  2501. }
  2502. /* 录音提示框 */
  2503. .voice-recording-box {
  2504. width: 300rpx;
  2505. height: 300rpx;
  2506. background-color: rgba(0, 0, 0, 0.8);
  2507. border-radius: 20rpx;
  2508. display: flex;
  2509. flex-direction: column;
  2510. align-items: center;
  2511. justify-content: center;
  2512. color: #fff;
  2513. transition: background-color 0.3s;
  2514. }
  2515. .voice-recording-box.canceling {
  2516. background-color: rgba(220, 38, 38, 0.9);
  2517. }
  2518. .voice-wave-container {
  2519. display: flex;
  2520. align-items: center;
  2521. justify-content: center;
  2522. gap: 8rpx;
  2523. height: 100rpx;
  2524. margin-bottom: 20rpx;
  2525. }
  2526. .voice-wave-bar {
  2527. width: 6rpx;
  2528. background: #fff;
  2529. border-radius: 3rpx;
  2530. transition: transform 0.1s ease-out;
  2531. transform-origin: center;
  2532. }
  2533. .voice-wave-bar.bar1 {
  2534. height: 30rpx;
  2535. }
  2536. .voice-wave-bar.bar2 {
  2537. height: 45rpx;
  2538. }
  2539. .voice-wave-bar.bar3 {
  2540. height: 60rpx;
  2541. }
  2542. .voice-wave-bar.bar4 {
  2543. height: 50rpx;
  2544. }
  2545. .voice-wave-bar.bar5 {
  2546. height: 35rpx;
  2547. }
  2548. .voice-text {
  2549. font-size: 32rpx;
  2550. margin-bottom: 10rpx;
  2551. }
  2552. .voice-time {
  2553. font-size: 48rpx;
  2554. font-weight: bold;
  2555. color: #07c160;
  2556. margin: 10rpx 0;
  2557. }
  2558. .voice-tip {
  2559. font-size: 24rpx;
  2560. color: #ccc;
  2561. }
  2562. </style>