chat.vue 90 KB

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