chat.vue 91 KB

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