chat.vue 89 KB

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