chat.vue 94 KB

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