chat.vue 82 KB

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