chat.vue 87 KB

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