chat.vue 88 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091
  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. let updatedCount = 0;
  906. // 🔥 直接使用事件数据中的消息对象(它们已经带有 isPeerRead: true)
  907. event.data.forEach(readMessage => {
  908. console.log(' - 处理消息:', readMessage.ID, '会话:', readMessage.conversationID);
  909. // 只处理当前会话的消息
  910. if (readMessage.conversationID === this.conversationID) {
  911. // 在本地消息列表中查找对应的消息
  912. const localMsgIndex = this.messages.findIndex(msg => msg.messageId === readMessage.ID);
  913. if (localMsgIndex > -1) {
  914. const localMsg = this.messages[localMsgIndex];
  915. // 只更新自己发送的未读消息
  916. if (localMsg.fromUserId === this.userId && !localMsg.isPeerRead) {
  917. this.$set(this.messages[localMsgIndex], 'isPeerRead', true);
  918. updatedCount++;
  919. console.log(` - ✅ 消息 ${readMessage.ID} 已标记为已读`);
  920. }
  921. } else {
  922. console.log(` - ⚠️ 本地未找到消息 ${readMessage.ID}`);
  923. }
  924. }
  925. });
  926. if (updatedCount > 0) {
  927. console.log(`✅ 共更新 ${updatedCount} 条消息为已读状态`);
  928. } else {
  929. console.log('⚠️ 没有消息需要更新');
  930. }
  931. }
  932. };
  933. // 🔥 使用 timManager 的全局已读回执监听
  934. this.handleMessageReadByPeer = handleMessageReadByPeer;
  935. timManager.onMessageRead(handleMessageReadByPeer);
  936. console.log('✅ 已通过 timManager 注册消息已读回执监听');
  937. },
  938. /**
  939. * 标记当前会话的消息为已读
  940. * 注意:这会通知对方"我已阅读他发送的消息",触发对方的 MESSAGE_READ_BY_PEER 事件
  941. */
  942. async markConversationRead() {
  943. try {
  944. if (!timManager.tim || !this.conversationID) {
  945. console.warn('⚠️ TIM 未初始化或会话ID为空');
  946. return;
  947. }
  948. console.log('📖 标记会话已读:', this.conversationID);
  949. // 调用 TIM SDK 标记会话已读
  950. // 这会通知对方:他发送给我的消息已被阅读
  951. await timManager.tim.setMessageRead({ conversationID: this.conversationID });
  952. console.log('✅ 会话已标记为已读,已通知对方');
  953. } catch (error) {
  954. console.error('❌ 标记会话已读失败:', error);
  955. }
  956. },
  957. /**
  958. * 发送文本消息
  959. */
  960. async sendTextMessage() {
  961. if (this.hasMessageLimit && this.remainingCount <= 0) {
  962. uni.showToast({
  963. title: '今日消息发送次数已用完,开通VIP无限制',
  964. icon: 'none',
  965. duration: 2000
  966. });
  967. return;
  968. }
  969. if (!this.inputText.trim()) {
  970. return;
  971. }
  972. const content = this.inputText;
  973. this.inputText = '';
  974. // 先检查是否被拉黑
  975. const isBlocked = await this.checkIsBlockedByTarget();
  976. if (isBlocked) {
  977. // 被拉黑时的处理保持不变
  978. const failedMessage = {
  979. messageId: 'failed_' + Date.now(),
  980. fromUserId: this.userId,
  981. toUserId: this.targetUserId,
  982. messageType: 1,
  983. content: content,
  984. sendStatus: 4, // 4表示发送失败
  985. sendTime: new Date(),
  986. fromUserName: '我'
  987. };
  988. this.messages.push(failedMessage);
  989. this.scrollToBottom();
  990. uni.showToast({
  991. title: '消息发送失败',
  992. icon: 'none'
  993. });
  994. return;
  995. }
  996. // 创建临时消息显示"发送中"
  997. const tempMessageId = 'temp_' + Date.now();
  998. const tempMessage = {
  999. messageId: tempMessageId,
  1000. fromUserId: this.userId,
  1001. toUserId: this.targetUserId,
  1002. messageType: 1,
  1003. content: content,
  1004. sendStatus: 1, // 发送中
  1005. sendTime: new Date(),
  1006. fromUserName: '我'
  1007. };
  1008. this.messages.push(tempMessage);
  1009. this.scrollToBottom();
  1010. // 未被拉黑,正常发送
  1011. try {
  1012. const sendPromise = timManager.sendTextMessage(this.targetUserId, content);
  1013. const timeoutPromise = new Promise((_, reject) => {
  1014. setTimeout(() => reject(new Error('发送超时')), 15000);
  1015. });
  1016. const message = await Promise.race([sendPromise, timeoutPromise]);
  1017. // 替换临时消息
  1018. const tempIndex = this.messages.findIndex(m => m.messageId === tempMessageId);
  1019. if (tempIndex > -1) {
  1020. const convertedMsg = this.convertMessage(message);
  1021. // 强制设置为已送达
  1022. convertedMsg.sendStatus = 2;
  1023. this.$set(this.messages, tempIndex, convertedMsg);
  1024. }
  1025. console.log('✅ 消息发送成功');
  1026. this.syncMessageToMySQL(message);
  1027. if (!this.isVip) {
  1028. await this.updateMessageCount();
  1029. }
  1030. } catch (error) {
  1031. console.error('❌ 消息发送失败:', error);
  1032. // 更新临时消息为失败状态
  1033. const tempIndex = this.messages.findIndex(m => m.messageId === tempMessageId);
  1034. if (tempIndex > -1) {
  1035. this.$set(this.messages[tempIndex], 'sendStatus', 4);
  1036. }
  1037. // 恢复输入框内容
  1038. this.inputText = content;
  1039. uni.showToast({
  1040. title: '发送失败: ' + error.message,
  1041. icon: 'none'
  1042. });
  1043. }
  1044. },
  1045. /**
  1046. * 选择图片
  1047. */
  1048. chooseImage() {
  1049. uni.chooseImage({
  1050. count: 1,
  1051. sizeType: ['compressed'],
  1052. sourceType: ['album', 'camera'],
  1053. success: async (res) => {
  1054. // 1. 先检查是否被拉黑
  1055. const isBlocked = await this.checkIsBlockedByTarget();
  1056. if (isBlocked) {
  1057. uni.showToast({
  1058. title: '你已被对方拉黑,无法发送消息',
  1059. icon: 'none'
  1060. });
  1061. return;
  1062. }
  1063. const tempFilePath = res.tempFilePaths[0];
  1064. try {
  1065. uni.showLoading({ title: '发送中...' });
  1066. const message = await timManager.sendImageMessage(this.targetUserId, tempFilePath);
  1067. this.messages.push(this.convertMessage(message));
  1068. this.scrollToBottom();
  1069. uni.hideLoading();
  1070. console.log('✅ 图片发送成功');
  1071. } catch (error) {
  1072. uni.hideLoading();
  1073. console.error('❌ 图片发送失败:', error);
  1074. uni.showToast({
  1075. title: '发送失败',
  1076. icon: 'none'
  1077. });
  1078. }
  1079. }
  1080. });
  1081. },
  1082. /**
  1083. * 输入框内容变化
  1084. */
  1085. onInputChange() {
  1086. // 腾讯云 IM 可以实现正在输入状态,这里暂时省略
  1087. console.log('输入中...');
  1088. },
  1089. /**
  1090. * 同步消息到MySQL数据库(双重存储保障)
  1091. */
  1092. async syncMessageToMySQL(timMessage) {
  1093. try {
  1094. console.log('🔄 同步消息到MySQL...', timMessage.ID);
  1095. // 构建同步参数
  1096. const syncData = {
  1097. messageId: timMessage.ID,
  1098. fromUserId: timMessage.from,
  1099. toUserId: timMessage.to,
  1100. messageType: this.getMessageType(timMessage),
  1101. content: this.getMessageContent(timMessage),
  1102. sendTime: timMessage.time // TIM返回的是秒级时间戳
  1103. };
  1104. // 如果是图片消息,添加媒体信息
  1105. if (timMessage.type === 'TIMImageElem' && timMessage.payload.imageInfoArray) {
  1106. const imageInfo = timMessage.payload.imageInfoArray[0];
  1107. syncData.mediaUrl = imageInfo.imageUrl;
  1108. syncData.thumbnailUrl = imageInfo.imageUrl;
  1109. }
  1110. // 如果是语音消息,添加语音信息
  1111. if (timMessage.type === 'TIMSoundElem' && timMessage.payload) {
  1112. syncData.mediaUrl = timMessage.payload.url || timMessage.payload.remoteAudioUrl;
  1113. syncData.duration = timMessage.payload.second || 0;
  1114. syncData.mediaSize = timMessage.payload.size || 0;
  1115. }
  1116. // 如果是自定义消息(我们的语音消息)
  1117. if (timMessage.type === 'TIMCustomElem' && timMessage.payload) {
  1118. try {
  1119. const customData = JSON.parse(timMessage.payload.data);
  1120. if (customData.type === 'voice') {
  1121. syncData.mediaUrl = customData.url;
  1122. syncData.duration = customData.duration;
  1123. syncData.mediaSize = customData.size || 0;
  1124. }
  1125. } catch (e) {
  1126. console.error('解析自定义消息失败:', e);
  1127. }
  1128. }
  1129. // 调用后端同步接口
  1130. const res = await uni.request({
  1131. url: 'http://localhost:1004/api/chat/syncTIMMessage',
  1132. method: 'POST',
  1133. data: syncData,
  1134. header: {
  1135. 'Content-Type': 'application/json'
  1136. }
  1137. });
  1138. if (res[1].data.code === 200) {
  1139. console.log('✅ 消息已同步到MySQL:', timMessage.ID);
  1140. } else {
  1141. console.warn('⚠️ 消息同步失败:', res[1].data.message);
  1142. }
  1143. } catch (error) {
  1144. console.error('❌ 同步消息到MySQL失败:', error);
  1145. // 同步失败不影响聊天功能,只记录日志
  1146. }
  1147. },
  1148. /**
  1149. * 获取消息类型
  1150. */
  1151. getMessageType(timMessage) {
  1152. const typeMap = {
  1153. 'TIMTextElem': 1, // 文本
  1154. 'TIMImageElem': 2, // 图片
  1155. 'TIMSoundElem': 3, // 语音
  1156. 'TIMVideoFileElem': 4, // 视频
  1157. 'TIMFileElem': 5 // 文件
  1158. };
  1159. // 处理自定义消息(我们的语音消息)
  1160. if (timMessage.type === 'TIMCustomElem' && timMessage.payload) {
  1161. try {
  1162. const customData = JSON.parse(timMessage.payload.data);
  1163. if (customData.type === 'voice') {
  1164. return 3; // 语音消息
  1165. }
  1166. } catch (e) {
  1167. console.error('解析自定义消息类型失败:', e);
  1168. }
  1169. }
  1170. return typeMap[timMessage.type] || 1;
  1171. },
  1172. /**
  1173. * 获取消息内容
  1174. */
  1175. getMessageContent(timMessage) {
  1176. switch (timMessage.type) {
  1177. case 'TIMTextElem':
  1178. return timMessage.payload.text || '';
  1179. case 'TIMImageElem':
  1180. return '[图片]';
  1181. case 'TIMSoundElem':
  1182. return '[语音]';
  1183. case 'TIMVideoFileElem':
  1184. return '[视频]';
  1185. case 'TIMFileElem':
  1186. return '[文件]';
  1187. case 'TIMCustomElem':
  1188. // 处理自定义消息(我们的语音消息)
  1189. try {
  1190. const customData = JSON.parse(timMessage.payload.data);
  1191. if (customData.type === 'voice') {
  1192. return '[语音]';
  1193. }
  1194. } catch (e) {
  1195. console.error('解析自定义消息内容失败:', e);
  1196. }
  1197. return '[未知消息]';
  1198. default:
  1199. return '[未知消息]';
  1200. }
  1201. },
  1202. /**
  1203. * 滚动到底部
  1204. */
  1205. scrollToBottom() {
  1206. this.$nextTick(() => {
  1207. const lastIndex = this.messages.length - 1;
  1208. this.scrollToView = 'msg-' + lastIndex;
  1209. });
  1210. },
  1211. /**
  1212. * 判断是否显示时间分隔线
  1213. */
  1214. shouldShowTime(msg, index) {
  1215. if (index === 0) return true;
  1216. const prevMsg = this.messages[index - 1];
  1217. const timeDiff = new Date(msg.sendTime) - new Date(prevMsg.sendTime);
  1218. // 超过5分钟显示时间
  1219. return timeDiff > 5 * 60 * 1000;
  1220. },
  1221. /**
  1222. * 格式化消息时间(用于时间分隔线)
  1223. */
  1224. formatMessageTime(time) {
  1225. const date = new Date(time);
  1226. const now = new Date();
  1227. const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
  1228. const yesterday = new Date(today - 86400000);
  1229. // 今天
  1230. if (date >= today) {
  1231. return date.toLocaleTimeString('zh-CN', {
  1232. hour: '2-digit',
  1233. minute: '2-digit'
  1234. });
  1235. }
  1236. // 昨天
  1237. if (date >= yesterday) {
  1238. return '昨天 ' + date.toLocaleTimeString('zh-CN', {
  1239. hour: '2-digit',
  1240. minute: '2-digit'
  1241. });
  1242. }
  1243. // 本周
  1244. if (date > new Date(now - 7 * 86400000)) {
  1245. const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
  1246. return days[date.getDay()] + ' ' + date.toLocaleTimeString('zh-CN', {
  1247. hour: '2-digit',
  1248. minute: '2-digit'
  1249. });
  1250. }
  1251. // 更早
  1252. return date.toLocaleString('zh-CN', {
  1253. month: '2-digit',
  1254. day: '2-digit',
  1255. hour: '2-digit',
  1256. minute: '2-digit'
  1257. });
  1258. },
  1259. /**
  1260. * 格式化时间(消息状态用)
  1261. */
  1262. formatTime(time) {
  1263. const date = new Date(time);
  1264. const now = new Date();
  1265. const diff = now - date;
  1266. if (diff < 60000) {
  1267. return '刚刚';
  1268. } else if (diff < 3600000) {
  1269. return Math.floor(diff / 60000) + '分钟前';
  1270. } else if (diff < 86400000) {
  1271. return Math.floor(diff / 3600000) + '小时前';
  1272. } else {
  1273. return date.toLocaleString('zh-CN', {
  1274. month: '2-digit',
  1275. day: '2-digit',
  1276. hour: '2-digit',
  1277. minute: '2-digit'
  1278. });
  1279. }
  1280. },
  1281. /**
  1282. * 预览图片
  1283. */
  1284. previewImage(url) {
  1285. uni.previewImage({
  1286. urls: [url],
  1287. current: url
  1288. });
  1289. },
  1290. /**
  1291. * 返回
  1292. */
  1293. goBack() {
  1294. uni.navigateBack({
  1295. success: () => {
  1296. // 通知消息列表页面刷新
  1297. uni.$emit('refreshConversations');
  1298. }
  1299. });
  1300. },
  1301. /**
  1302. * 显示消息操作菜单
  1303. */
  1304. showMessageMenu(msg, index) {
  1305. this.selectedMessage = msg;
  1306. this.selectedMessageIndex = index;
  1307. this.showMessageAction = true;
  1308. // 计算菜单位置
  1309. uni.createSelectorQuery().select('.message-item').boundingClientRect(rect => {
  1310. if (rect) {
  1311. this.menuTop = rect.top + rect.height;
  1312. }
  1313. }).exec();
  1314. },
  1315. /**
  1316. * 隐藏消息操作菜单
  1317. */
  1318. hideMessageMenu() {
  1319. this.showMessageAction = false;
  1320. this.selectedMessage = null;
  1321. this.selectedMessageIndex = -1;
  1322. },
  1323. /**
  1324. * 复制消息
  1325. */
  1326. copyMessage() {
  1327. if (!this.selectedMessage || this.selectedMessage.messageType !== 1) {
  1328. return;
  1329. }
  1330. uni.setClipboardData({
  1331. data: this.selectedMessage.content,
  1332. success: () => {
  1333. uni.showToast({
  1334. title: '已复制',
  1335. icon: 'success'
  1336. });
  1337. }
  1338. });
  1339. this.hideMessageMenu();
  1340. },
  1341. /**
  1342. * 判断是否可以撤回
  1343. */
  1344. canRecall(msg) {
  1345. const diff = Date.now() - new Date(msg.sendTime).getTime();
  1346. return diff < 2 * 60 * 1000; // 2分钟内可撤回
  1347. },
  1348. /**
  1349. * 撤回消息
  1350. */
  1351. async recallMessage() {
  1352. if (!this.selectedMessage) {
  1353. return;
  1354. }
  1355. try {
  1356. // 查找TIM消息对象
  1357. const timMessage = await timManager.tim.findMessage(this.selectedMessage.messageId);
  1358. if (timMessage) {
  1359. await timManager.revokeMessage(timMessage);
  1360. // 更新本地消息状态
  1361. this.selectedMessage.isRecalled = true;
  1362. this.selectedMessage.content = '你撤回了一条消息';
  1363. uni.showToast({
  1364. title: '已撤回',
  1365. icon: 'success'
  1366. });
  1367. }
  1368. } catch (error) {
  1369. console.error('撤回失败:', error);
  1370. uni.showToast({
  1371. title: '撤回失败',
  1372. icon: 'none'
  1373. });
  1374. }
  1375. this.hideMessageMenu();
  1376. },
  1377. /**
  1378. * 删除消息
  1379. */
  1380. deleteMessage() {
  1381. if (!this.selectedMessage) {
  1382. return;
  1383. }
  1384. uni.showModal({
  1385. title: '确认删除',
  1386. content: '确定要删除这条消息吗?',
  1387. success: (res) => {
  1388. if (res.confirm) {
  1389. // 从列表中删除
  1390. this.messages.splice(this.selectedMessageIndex, 1);
  1391. uni.showToast({
  1392. title: '已删除',
  1393. icon: 'success'
  1394. });
  1395. }
  1396. }
  1397. });
  1398. this.hideMessageMenu();
  1399. },
  1400. /**
  1401. * 处理消息点击
  1402. */
  1403. handleMessageClick(msg) {
  1404. // 如果是发送失败的消息,提示重试
  1405. if (msg.sendStatus === 4) {
  1406. uni.showModal({
  1407. title: '发送失败',
  1408. content: '消息发送失败,是否重试?',
  1409. success: (res) => {
  1410. if (res.confirm) {
  1411. this.retryMessage(msg);
  1412. }
  1413. }
  1414. });
  1415. }
  1416. },
  1417. /**
  1418. * 重试发送消息
  1419. */
  1420. async retryMessage(msg) {
  1421. if (msg.messageType !== 1) {
  1422. uni.showToast({ title: '暂不支持重发该类型消息', icon: 'none' });
  1423. return;
  1424. }
  1425. const isBlocked = await this.checkIsBlockedByTarget();
  1426. if (isBlocked) {
  1427. const index = this.messages.findIndex(m => m.messageId === msg.messageId);
  1428. if (index > -1) {
  1429. this.$set(this.messages[index], 'sendStatus', 4);
  1430. }
  1431. uni.showToast({ title: '对方已拉黑你,无法发送', icon: 'none' });
  1432. return;
  1433. }
  1434. try {
  1435. const index = this.messages.findIndex(m => m.messageId === msg.messageId);
  1436. if (index > -1) {
  1437. this.$set(this.messages[index], 'sendStatus', 1); // 发送中
  1438. }
  1439. const message = await timManager.sendTextMessage(this.targetUserId, msg.content);
  1440. // 更新消息状态为已送达
  1441. if (index > -1) {
  1442. const convertedMsg = this.convertMessage(message);
  1443. convertedMsg.sendStatus = 2; // 强制已送达
  1444. convertedMsg.messageId = msg.messageId; // 保持原ID
  1445. this.$set(this.messages, index, convertedMsg);
  1446. }
  1447. console.log('✅ 消息重发成功');
  1448. this.syncMessageToMySQL(message);
  1449. } catch (error) {
  1450. console.error('❌ 消息重发失败:', error);
  1451. const index = this.messages.findIndex(m => m.messageId === msg.messageId);
  1452. if (index > -1) {
  1453. this.$set(this.messages[index], 'sendStatus', 4);
  1454. }
  1455. uni.showToast({ title: '发送失败', icon: 'none' });
  1456. }
  1457. },
  1458. // 其他功能方法
  1459. switchInputType() {
  1460. this.inputType = this.inputType === 'text' ? 'voice' : 'text';
  1461. },
  1462. /**
  1463. * 开始录音
  1464. */
  1465. startVoiceRecord(e) {
  1466. console.log('🎤 [按住说话] startVoiceRecord 方法被调用');
  1467. // 记录触摸起始位置
  1468. this.voiceTouchStartY = e.touches[0].clientY;
  1469. this.voiceCanceling = false;
  1470. // 检查是否被拉黑
  1471. if (this.isBlockedByTarget) {
  1472. uni.showToast({
  1473. title: '对方已将你拉黑',
  1474. icon: 'none'
  1475. });
  1476. return;
  1477. }
  1478. // 🔥 每次都重新获取录音管理器(确保状态干净)
  1479. console.log('📱 获取录音管理器');
  1480. this.recorderManager = uni.getRecorderManager();
  1481. // 🔥 每次录音前都重新注册回调(确保回调有效)
  1482. console.log('📝 注册录音回调');
  1483. // 录音开始回调(可能延迟或不触发,所以状态已在 start() 后立即设置)
  1484. this.recorderManager.onStart(() => {
  1485. console.log('✅ 录音开始回调触发(延迟触发)');
  1486. });
  1487. // 录音结束回调
  1488. this.recorderManager.onStop((res) => {
  1489. console.log('🎤 录音结束:', res, ', voiceCanceling:', this.voiceCanceling);
  1490. this.isRecording = false;
  1491. this.showVoiceRecording = false;
  1492. // 清除计时器
  1493. if (this.voiceRecordingTimer) {
  1494. clearInterval(this.voiceRecordingTimer);
  1495. this.voiceRecordingTimer = null;
  1496. }
  1497. // 如果是取消状态,不发送
  1498. if (this.voiceCanceling) {
  1499. console.log('❌ 录音已取消,不发送');
  1500. this.voiceCanceling = false;
  1501. return;
  1502. }
  1503. this.voiceTempPath = res.tempFilePath;
  1504. this.voiceDuration = Math.floor(res.duration / 1000); // 转换为秒
  1505. console.log(' - 文件路径:', this.voiceTempPath);
  1506. console.log(' - 时长:', this.voiceDuration, '秒');
  1507. // 时长验证
  1508. if (this.voiceDuration < 1) {
  1509. uni.showToast({
  1510. title: '录音时间太短',
  1511. icon: 'none'
  1512. });
  1513. return;
  1514. }
  1515. if (this.voiceDuration > 60) {
  1516. uni.showToast({
  1517. title: '录音时间不能超过60秒',
  1518. icon: 'none'
  1519. });
  1520. return;
  1521. }
  1522. // 发送语音消息
  1523. this.sendVoiceMessage();
  1524. });
  1525. // 录音错误回调
  1526. this.recorderManager.onError((err) => {
  1527. console.error('❌ 录音错误:', err);
  1528. // 立即清理录音状态和界面
  1529. this.isRecording = false;
  1530. this.showVoiceRecording = false;
  1531. this.voiceCanceling = true;
  1532. // 清除计时器
  1533. if (this.voiceRecordingTimer) {
  1534. clearInterval(this.voiceRecordingTimer);
  1535. this.voiceRecordingTimer = null;
  1536. }
  1537. // 如果是权限错误,不显示任何提示(用户会看到系统权限弹窗)
  1538. // 其他错误才显示提示
  1539. if (err.errCode !== 'authorize' && err.errMsg && !err.errMsg.includes('authorize')) {
  1540. uni.showToast({
  1541. title: '录音失败',
  1542. icon: 'none'
  1543. });
  1544. }
  1545. console.log('✅ 已清理录音状态,隐藏录音界面');
  1546. });
  1547. // 🔥 先检查录音权限
  1548. console.log('🔐 检查录音权限...');
  1549. uni.getSetting({
  1550. success: (res) => {
  1551. console.log('📋 权限设置:', res.authSetting);
  1552. if (res.authSetting['scope.record'] === false) {
  1553. console.warn('⚠️ 录音权限被拒绝');
  1554. uni.showModal({
  1555. title: '需要录音权限',
  1556. content: '请在设置中开启录音权限',
  1557. success: (modalRes) => {
  1558. if (modalRes.confirm) {
  1559. uni.openSetting();
  1560. }
  1561. }
  1562. });
  1563. return;
  1564. }
  1565. }
  1566. });
  1567. // 开始录音
  1568. console.log('🎙️ 调用 recorderManager.start()');
  1569. try {
  1570. this.recorderManager.start({
  1571. format: 'mp3',
  1572. sampleRate: 16000,
  1573. numberOfChannels: 1,
  1574. encodeBitRate: 48000
  1575. });
  1576. console.log('✅ recorderManager.start() 调用成功');
  1577. // 🔥 立即显示录音界面(不等待 onStart 回调)
  1578. // 因为微信小程序的 onStart 可能延迟或不触发
  1579. this.isRecording = true;
  1580. this.showVoiceRecording = true;
  1581. this.voiceStartTime = Date.now();
  1582. this.voiceRecordingTime = 0;
  1583. this.voiceVolume = 0.3;
  1584. console.log('🎬 立即显示录音界面');
  1585. console.log(' - isRecording:', this.isRecording);
  1586. console.log(' - showVoiceRecording:', this.showVoiceRecording);
  1587. // 启动计时器
  1588. let volumeDirection = 1;
  1589. let currentVolume = 0.3;
  1590. this.voiceRecordingTimer = setInterval(() => {
  1591. this.voiceRecordingTime = Math.floor((Date.now() - this.voiceStartTime) / 1000);
  1592. // 检查是否达到60秒,自动停止录音
  1593. if (this.voiceRecordingTime >= 60) {
  1594. console.log('⏰ 录音时长达到60秒,自动停止');
  1595. clearInterval(this.voiceRecordingTimer);
  1596. this.voiceRecordingTimer = null;
  1597. this.voiceCanceling = false;
  1598. if (this.recorderManager) {
  1599. this.recorderManager.stop();
  1600. }
  1601. return;
  1602. }
  1603. // 模拟音量波动
  1604. if (Math.random() > 0.2) {
  1605. currentVolume += volumeDirection * (0.1 + Math.random() * 0.2);
  1606. if (currentVolume > 1.0) {
  1607. currentVolume = 1.0;
  1608. volumeDirection = -1;
  1609. } else if (currentVolume < 0.4) {
  1610. currentVolume = 0.4;
  1611. volumeDirection = 1;
  1612. }
  1613. this.voiceVolume = currentVolume;
  1614. } else {
  1615. this.voiceVolume = Math.max(0.2, this.voiceVolume * 0.8);
  1616. }
  1617. }, 100);
  1618. } catch (err) {
  1619. console.error('❌ recorderManager.start() 调用失败:', err);
  1620. this.isRecording = false;
  1621. this.showVoiceRecording = false;
  1622. }
  1623. },
  1624. /**
  1625. * 停止录音
  1626. */
  1627. stopVoiceRecord() {
  1628. console.log('🎤 [松开] stopVoiceRecord 方法被调用, isRecording:', this.isRecording, ', voiceCanceling:', this.voiceCanceling);
  1629. // 清除计时器
  1630. if (this.voiceRecordingTimer) {
  1631. clearInterval(this.voiceRecordingTimer);
  1632. this.voiceRecordingTimer = null;
  1633. }
  1634. // 如果正在取消,则取消录音
  1635. if (this.voiceCanceling) {
  1636. console.log('🚫 检测到取消状态,调用 cancelVoiceRecord');
  1637. this.cancelVoiceRecord();
  1638. return;
  1639. }
  1640. if (this.isRecording && this.recorderManager) {
  1641. const duration = Date.now() - this.voiceStartTime;
  1642. // 录音时间太短
  1643. if (duration < 1000) {
  1644. this.recorderManager.stop();
  1645. this.isRecording = false;
  1646. this.showVoiceRecording = false;
  1647. uni.showToast({
  1648. title: '录音时间太短',
  1649. icon: 'none'
  1650. });
  1651. return;
  1652. }
  1653. this.recorderManager.stop();
  1654. }
  1655. },
  1656. /**
  1657. * 触摸移动 - 检测上滑取消
  1658. */
  1659. onVoiceTouchMove(e) {
  1660. if (!this.isRecording) return;
  1661. const currentY = e.touches[0].clientY;
  1662. const deltaY = this.voiceTouchStartY - currentY;
  1663. // 上滑超过100px,显示取消提示
  1664. if (deltaY > 100) {
  1665. this.voiceCanceling = true;
  1666. console.log('⬆️ 上滑取消录音');
  1667. } else {
  1668. this.voiceCanceling = false;
  1669. }
  1670. },
  1671. /**
  1672. * 取消录音
  1673. */
  1674. cancelVoiceRecord() {
  1675. console.log('❌ 取消录音, voiceCanceling:', this.voiceCanceling);
  1676. // 清除计时器
  1677. if (this.voiceRecordingTimer) {
  1678. clearInterval(this.voiceRecordingTimer);
  1679. this.voiceRecordingTimer = null;
  1680. }
  1681. // 先设置取消状态,再停止录音
  1682. // 这样onStop回调中能正确判断
  1683. if (!this.voiceCanceling) {
  1684. this.voiceCanceling = true;
  1685. }
  1686. if (this.recorderManager && this.isRecording) {
  1687. this.recorderManager.stop(); // 这会触发onStop回调
  1688. } else {
  1689. // 如果没有在录音,直接重置状态
  1690. this.isRecording = false;
  1691. this.showVoiceRecording = false;
  1692. this.voiceCanceling = false;
  1693. }
  1694. uni.showToast({
  1695. title: '已取消录音',
  1696. icon: 'none'
  1697. });
  1698. },
  1699. /**
  1700. * 发送语音消息
  1701. */
  1702. async sendVoiceMessage() {
  1703. // 检查是否被拉黑
  1704. const isBlocked = await this.checkIsBlockedByTarget();
  1705. if (isBlocked) {
  1706. uni.showToast({
  1707. title: '你已被对方拉黑,无法发送消息',
  1708. icon: 'none'
  1709. });
  1710. return;
  1711. }
  1712. try {
  1713. uni.showLoading({ title: '上传中...' });
  1714. // 第一步:上传语音文件到MinIO
  1715. const uploadResult = await this.uploadVoiceToMinIO();
  1716. if (!uploadResult.success) {
  1717. throw new Error(uploadResult.message || '上传失败');
  1718. }
  1719. console.log('✅ 语音文件上传成功:', uploadResult.fileUrl);
  1720. uni.showLoading({ title: '发送中...' });
  1721. // 第二步:通过腾讯IM发送语音消息(携带MinIO URL)
  1722. const message = await timManager.sendVoiceMessage(
  1723. this.targetUserId,
  1724. uploadResult.fileUrl,
  1725. this.voiceDuration,
  1726. uploadResult.fileSize
  1727. );
  1728. // 添加到消息列表
  1729. this.messages.push(this.convertMessage(message));
  1730. this.scrollToBottom();
  1731. uni.hideLoading();
  1732. console.log('✅ 语音消息发送成功');
  1733. // 同步到MySQL
  1734. this.syncMessageToMySQL(message);
  1735. // 更新消息计数
  1736. if (!this.isVip) {
  1737. await this.updateMessageCount();
  1738. }
  1739. } catch (error) {
  1740. uni.hideLoading();
  1741. console.error('❌ 语音消息发送失败:', error);
  1742. uni.showToast({
  1743. title: '发送失败: ' + error.message,
  1744. icon: 'none'
  1745. });
  1746. }
  1747. },
  1748. /**
  1749. * 上传语音文件到MinIO
  1750. */
  1751. async uploadVoiceToMinIO() {
  1752. try {
  1753. console.log('📤 开始上传语音文件到MinIO...');
  1754. console.log(' - 文件路径:', this.voiceTempPath);
  1755. console.log(' - 时长:', this.voiceDuration, '秒');
  1756. // 使用uni.uploadFile上传到后端MinIO接口
  1757. const [err, res] = await uni.uploadFile({
  1758. url: 'http://localhost:1004/api/voice/upload',
  1759. filePath: this.voiceTempPath,
  1760. name: 'file',
  1761. header: {
  1762. 'Content-Type': 'multipart/form-data'
  1763. }
  1764. });
  1765. if (err) {
  1766. console.error('❌ 上传请求失败:', err);
  1767. return {
  1768. success: false,
  1769. message: '网络请求失败'
  1770. };
  1771. }
  1772. // 解析响应
  1773. const result = JSON.parse(res.data);
  1774. console.log('📥 MinIO上传响应:', result);
  1775. if (result.success) {
  1776. return {
  1777. success: true,
  1778. fileUrl: result.fileUrl,
  1779. fileSize: result.fileSize
  1780. };
  1781. } else {
  1782. return {
  1783. success: false,
  1784. message: result.message || '上传失败'
  1785. };
  1786. }
  1787. } catch (error) {
  1788. console.error('❌ 上传语音文件失败:', error);
  1789. return {
  1790. success: false,
  1791. message: error.message || '上传异常'
  1792. };
  1793. }
  1794. },
  1795. insertEmoji(emoji) {
  1796. this.inputText += emoji;
  1797. this.showEmojiPanel = false;
  1798. },
  1799. chooseVideo() {
  1800. uni.showToast({
  1801. title: '视频功能开发中',
  1802. icon: 'none'
  1803. });
  1804. },
  1805. chooseFile() {
  1806. uni.showToast({
  1807. title: '文件功能开发中',
  1808. icon: 'none'
  1809. });
  1810. },
  1811. /**
  1812. * 切换语音播放/暂停
  1813. */
  1814. toggleVoicePlay(msg) {
  1815. // 如果正在播放这条语音,则暂停
  1816. if (this.playingVoiceId === msg.messageId) {
  1817. this.pauseVoice(msg);
  1818. } else {
  1819. // 否则开始播放
  1820. this.playVoice(msg);
  1821. }
  1822. },
  1823. /**
  1824. * 播放语音
  1825. */
  1826. playVoice(msg) {
  1827. console.log('📢 [播放语音] 开始 - messageId:', msg.messageId);
  1828. if (!msg.mediaUrl) {
  1829. // 如果是TIM消息,从payload中获取URL
  1830. const audioUrl = msg.payload?.url || msg.payload?.remoteAudioUrl;
  1831. if (!audioUrl) {
  1832. uni.showToast({
  1833. title: '语音文件不存在',
  1834. icon: 'none'
  1835. });
  1836. return;
  1837. }
  1838. msg.mediaUrl = audioUrl;
  1839. }
  1840. // 如果有其他语音正在播放,先停止
  1841. if (this.currentAudioContext) {
  1842. console.log('⏹️ 停止之前的语音');
  1843. this.currentAudioContext.stop();
  1844. this.currentAudioContext.destroy();
  1845. this.currentAudioContext = null;
  1846. }
  1847. // 清除暂停状态
  1848. this.pausedVoiceId = null;
  1849. // 设置当前播放的语音ID,触发动画
  1850. this.playingVoiceId = msg.messageId;
  1851. console.log('🎬 [动画开始] playingVoiceId =', this.playingVoiceId);
  1852. // 创建音频上下文
  1853. const innerAudioContext = uni.createInnerAudioContext();
  1854. innerAudioContext.src = msg.mediaUrl;
  1855. innerAudioContext.loop = false; // 不循环播放
  1856. this.currentAudioContext = innerAudioContext;
  1857. innerAudioContext.onPlay(() => {
  1858. console.log('🔊 开始播放语音');
  1859. });
  1860. innerAudioContext.onEnded(() => {
  1861. console.log('✅ 语音播放完成');
  1862. this.playingVoiceId = null; // 停止动画
  1863. this.pausedVoiceId = null;
  1864. this.currentAudioContext = null;
  1865. console.log('🛑 [动画停止] playingVoiceId =', this.playingVoiceId);
  1866. innerAudioContext.destroy();
  1867. });
  1868. innerAudioContext.onError((err) => {
  1869. console.error('❌ 语音播放失败:', err);
  1870. this.playingVoiceId = null; // 停止动画
  1871. this.pausedVoiceId = null;
  1872. this.currentAudioContext = null;
  1873. console.log('🛑 [动画停止-错误] playingVoiceId =', this.playingVoiceId);
  1874. uni.showToast({
  1875. title: '播放失败',
  1876. icon: 'none'
  1877. });
  1878. innerAudioContext.destroy();
  1879. });
  1880. innerAudioContext.play();
  1881. },
  1882. /**
  1883. * 暂停语音
  1884. */
  1885. pauseVoice(msg) {
  1886. if (this.currentAudioContext) {
  1887. this.currentAudioContext.pause();
  1888. this.playingVoiceId = null; // 停止动画
  1889. this.pausedVoiceId = msg.messageId; // 设置暂停状态
  1890. console.log('⏸️ [暂停] playingVoiceId =', this.playingVoiceId, ', pausedVoiceId =', this.pausedVoiceId);
  1891. }
  1892. },
  1893. /**
  1894. * 继续播放语音
  1895. */
  1896. resumeVoice() {
  1897. if (this.currentAudioContext && this.pausedVoiceId) {
  1898. this.currentAudioContext.play();
  1899. this.playingVoiceId = this.pausedVoiceId; // 恢复动画
  1900. const resumedId = this.pausedVoiceId;
  1901. this.pausedVoiceId = null; // 清除暂停状态
  1902. console.log('▶️ [继续播放] playingVoiceId =', this.playingVoiceId, ', pausedVoiceId =', this.pausedVoiceId);
  1903. }
  1904. },
  1905. showMoreOptions() {
  1906. this.showMoreOptionsModal = true;
  1907. },
  1908. closeMoreOptions() {
  1909. this.showMoreOptionsModal = false;
  1910. },
  1911. /**
  1912. * 查看用户资料(跳转到原有more页面)
  1913. */
  1914. goToUserProfile() {
  1915. this.closeMoreOptions();
  1916. uni.navigateTo({
  1917. url: `/pages/message/more?userid=${this.targetUserId}`,
  1918. fail: (err) => {
  1919. console.error('跳转失败:', err);
  1920. uni.showToast({
  1921. title: '页面不存在',
  1922. icon: 'none'
  1923. });
  1924. }
  1925. });
  1926. },
  1927. /**
  1928. * 显示拉黑确认弹窗
  1929. */
  1930. blockFriend() {
  1931. this.closeMoreOptions();
  1932. this.showBlockConfirmModal = true;
  1933. },
  1934. /**
  1935. * 关闭拉黑确认弹窗
  1936. */
  1937. closeBlockConfirm() {
  1938. this.showBlockConfirmModal = false;
  1939. },
  1940. /**
  1941. * 从后端获取VIP状态和今日剩余发送次数
  1942. */
  1943. async getUserMessageLimit() {
  1944. try {
  1945. const [err, res] = await uni.request({
  1946. url: 'http://localhost:1004/api/chat/getUserMessageLimit',
  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) throw new Error(res.data.message || '获取限制信息失败');
  1958. const { isVip, remainingCount, hasMessageLimit } = res.data.data;
  1959. this.isVip = isVip;
  1960. this.remainingCount = remainingCount;
  1961. this.hasMessageLimit = hasMessageLimit;
  1962. console.log('✅ 用户消息限制信息:', { isVip, remainingCount, hasMessageLimit });
  1963. } catch (error) {
  1964. console.error('❌ 获取消息限制失败:', error);
  1965. // 异常降级:默认非VIP,剩余5次
  1966. this.isVip = false;
  1967. this.remainingCount = 5;
  1968. this.hasMessageLimit = true;
  1969. }
  1970. },
  1971. /**
  1972. * 发送成功后,更新后端计数并同步前端剩余次数
  1973. */
  1974. async updateMessageCount() {
  1975. try {
  1976. const [err, res] = await uni.request({
  1977. url: 'http://localhost:8083/api/chat/updateMessageCount',
  1978. method: 'get',
  1979. data: {
  1980. userId: this.userId ,// 已在onLoad中初始化的当前用户ID
  1981. targetUserId: this.targetUserId
  1982. },
  1983. header: {
  1984. 'Content-Type': 'application/json'
  1985. }
  1986. });
  1987. if (err) throw new Error('更新计数失败');
  1988. if (res.data.code === 200) {
  1989. this.remainingCount = res.data.data.remainingCount; // 同步后端返回的剩余次数
  1990. }
  1991. } catch (error) {
  1992. console.error('❌ 更新发送次数失败:', error);
  1993. // 前端本地降级:避免影响用户体验,本地暂减1(刷新页面后同步真实数据)
  1994. if (this.remainingCount > 0) {
  1995. this.remainingCount--;
  1996. }
  1997. }
  1998. },
  1999. /**
  2000. * 确认拉黑好友
  2001. */
  2002. async confirmBlockFriend() {
  2003. try {
  2004. uni.showLoading({
  2005. title: '处理中...'
  2006. });
  2007. // 调用后端拉黑接口(根据实际接口调整)
  2008. const [err, res] = await uni.request({
  2009. url: 'http://localhost:8083/api/chatfriend/block',
  2010. method: 'POST',
  2011. data: {
  2012. userId: this.userId,
  2013. targetUserId: this.targetUserId,
  2014. targetUserName: this.targetUserName,
  2015. targetUserAvatar: this.targetUserAvatar
  2016. },
  2017. header: {
  2018. 'Content-Type': 'application/json',
  2019. // 'Authorization': 'Bearer ' + uni.getStorageSync('token')
  2020. }
  2021. });
  2022. uni.hideLoading();
  2023. if (err) throw new Error('网络请求失败');
  2024. if (res.data && res.data.code === 200) {
  2025. uni.showToast({ title: '拉黑成功', icon: 'success' });
  2026. this.closeBlockConfirm();
  2027. // 触发拉黑列表更新事件,通知消息页面实时刷新
  2028. uni.$emit('blacklistUpdated');
  2029. // 拉黑成功后立即返回消息列表页面(优化体验)
  2030. setTimeout(() => {
  2031. uni.navigateBack({
  2032. delta: 1,
  2033. success: () => {
  2034. // 返回成功后再次触发一次刷新,确保万无一失
  2035. uni.$emit('blacklistUpdated');
  2036. }
  2037. });
  2038. }, 1500);
  2039. } else {
  2040. throw new Error(res.data?.message || '拉黑失败');
  2041. }
  2042. } catch (error) {
  2043. console.error('拉黑失败:', error);
  2044. uni.showToast({ title: error.message || '拉黑失败', icon: 'none' });
  2045. }
  2046. },
  2047. /**
  2048. * 初始化在线状态监听(WebSocket 实时推送 + HTTP 轮询)
  2049. */
  2050. async initOnlineStatusPolling() {
  2051. console.log('🔄 初始化在线状态监听(WebSocket + HTTP)');
  2052. const timPresenceManager = require('@/utils/tim-presence-manager.js').default;
  2053. // 1. 立即查询一次
  2054. await this.checkOnlineStatus();
  2055. // 2. 监听 WebSocket 实时推送(实时性强)
  2056. this.onlineStatusCallback = (status) => {
  2057. console.log(`⚡ 实时收到用户 ${this.targetUserId} 状态变更: ${status}`);
  2058. this.isTargetOnline = (status === 'online');
  2059. };
  2060. timPresenceManager.onStatusChange(this.targetUserId, this.onlineStatusCallback);
  2061. // 3. 启动 HTTP 轮询作为补充(30秒间隔)
  2062. this.onlineStatusTimer = setInterval(() => {
  2063. this.checkOnlineStatus();
  2064. }, 30000);
  2065. console.log('✅ 在线状态监听已启动(WebSocket 实时 + HTTP 轮询)');
  2066. },
  2067. /**
  2068. * 查询在线状态
  2069. */
  2070. async checkOnlineStatus() {
  2071. try {
  2072. const [err, res] = await uni.request({
  2073. url: 'http://localhost:8083/api/online/checkStatus',
  2074. method: 'GET',
  2075. data: {
  2076. userId: this.targetUserId
  2077. }
  2078. });
  2079. if (!err && res.data && res.data.code === 200) {
  2080. this.isTargetOnline = res.data.data.online || false;
  2081. console.log(`� 用户 ${this.targetUserId} 在线状态:`, this.isTargetOnline);
  2082. }
  2083. } catch (error) {
  2084. console.error('❌ 查询在线状态失败:', error);
  2085. }
  2086. }
  2087. },
  2088. /**
  2089. * 页面卸载时清理
  2090. */
  2091. onUnload() {
  2092. console.log('=== 聊天页面卸载 ===');
  2093. // 清理在线状态轮询
  2094. if (this.onlineStatusTimer) {
  2095. clearInterval(this.onlineStatusTimer);
  2096. this.onlineStatusTimer = null;
  2097. console.log('✅ 已停止在线状态轮询');
  2098. }
  2099. // 清理 WebSocket 监听
  2100. if (this.onlineStatusCallback) {
  2101. const timPresenceManager = require('@/utils/tim-presence-manager.js').default;
  2102. timPresenceManager.offStatusChange(this.targetUserId, this.onlineStatusCallback);
  2103. console.log('✅ 已清理 WebSocket 监听');
  2104. }
  2105. // 清理已读回执监听
  2106. if (this.handleMessageReadByPeer) {
  2107. timManager.offMessageRead(this.handleMessageReadByPeer);
  2108. console.log('✅ 已通过 timManager 清理已读回执监听');
  2109. }
  2110. // 清理新消息监听
  2111. if (this.handleNewMessage) {
  2112. timManager.offMessage(this.handleNewMessage);
  2113. console.log('✅ 已清理新消息监听');
  2114. }
  2115. }
  2116. };
  2117. </script>
  2118. <style scoped>
  2119. /* 弹窗遮罩 */
  2120. .modal-mask {
  2121. position: fixed;
  2122. top: 0;
  2123. left: 0;
  2124. right: 0;
  2125. bottom: 0;
  2126. background-color: rgba(0, 0, 0, 0.5);
  2127. z-index: 10000;
  2128. display: flex;
  2129. align-items: center;
  2130. justify-content: center;
  2131. }
  2132. /* 更多选项弹窗内容 */
  2133. .modal-content {
  2134. width: 70%;
  2135. background-color: #fff;
  2136. border-radius: 20rpx;
  2137. overflow: hidden;
  2138. }
  2139. .modal-header {
  2140. padding: 30rpx;
  2141. text-align: center;
  2142. border-bottom: 1px solid #eee;
  2143. }
  2144. .modal-title {
  2145. font-size: 32rpx;
  2146. font-weight: bold;
  2147. display: block;
  2148. }
  2149. .modal-subtitle {
  2150. font-size: 24rpx;
  2151. color: #999;
  2152. display: block;
  2153. margin-top: 10rpx;
  2154. }
  2155. .modal-body {
  2156. padding: 20rpx 0;
  2157. }
  2158. .modal-item {
  2159. display: flex;
  2160. align-items: center;
  2161. padding: 25rpx 40rpx;
  2162. font-size: 30rpx;
  2163. }
  2164. .modal-item.danger {
  2165. color: #fa5151;
  2166. }
  2167. .item-icon {
  2168. font-size: 32rpx;
  2169. margin-right: 20rpx;
  2170. }
  2171. .modal-footer {
  2172. padding: 20rpx;
  2173. border-top: 1px solid #eee;
  2174. }
  2175. .modal-close-btn {
  2176. width: 94%;
  2177. background-color: #f5f5f5;
  2178. border: none;
  2179. border-radius: 10rpx;
  2180. padding: 20rpx;
  2181. font-size: 30rpx;
  2182. }
  2183. /* 确认弹窗样式 */
  2184. .confirm-modal {
  2185. width: 60%;
  2186. background-color: #fff;
  2187. border-radius: 20rpx;
  2188. padding: 40rpx;
  2189. text-align: center;
  2190. }
  2191. .confirm-title {
  2192. font-size: 32rpx;
  2193. font-weight: bold;
  2194. margin-bottom: 30rpx;
  2195. }
  2196. .confirm-content {
  2197. font-size: 28rpx;
  2198. color: #666;
  2199. margin-bottom: 40rpx;
  2200. line-height: 1.5;
  2201. }
  2202. .confirm-buttons {
  2203. display: flex;
  2204. justify-content: space-between;
  2205. }
  2206. .confirm-btn {
  2207. flex: 1;
  2208. margin: 0 10rpx;
  2209. padding: 20rpx;
  2210. border-radius: 10rpx;
  2211. border: none;
  2212. font-size: 28rpx;
  2213. }
  2214. .confirm-btn.cancel {
  2215. background-color: #f5f5f5;
  2216. }
  2217. .confirm-btn.confirm {
  2218. background-color: #fa5151;
  2219. color: #fff;
  2220. }
  2221. .chat-page {
  2222. display: flex;
  2223. flex-direction: column;
  2224. height: 100vh;
  2225. background-color: #f5f5f5;
  2226. }
  2227. /* 顶部导航 */
  2228. .chat-header {
  2229. display: flex;
  2230. align-items: center;
  2231. justify-content: space-between;
  2232. padding: 20rpx 30rpx;
  2233. background-color: #fff;
  2234. border-bottom: 1px solid #e5e5e5;
  2235. }
  2236. .header-left, .header-right {
  2237. width: 80rpx;
  2238. }
  2239. .icon-back, .icon-more {
  2240. font-size: 40rpx;
  2241. }
  2242. .header-center {
  2243. flex: 1;
  2244. text-align: center;
  2245. }
  2246. .chat-title {
  2247. display: block;
  2248. font-size: 36rpx;
  2249. font-weight: bold;
  2250. }
  2251. .online-status {
  2252. display: block;
  2253. font-size: 24rpx;
  2254. color: #999;
  2255. margin-top: 5rpx;
  2256. }
  2257. .online-status.online {
  2258. color: #07c160;
  2259. }
  2260. /* 消息列表 */
  2261. .message-list {
  2262. flex: 1;
  2263. padding: 20rpx;
  2264. overflow-y: scroll;
  2265. }
  2266. .loading-tip {
  2267. text-align: center;
  2268. padding: 20rpx;
  2269. color: #999;
  2270. font-size: 28rpx;
  2271. }
  2272. .message-item {
  2273. display: flex;
  2274. margin-bottom: 30rpx;
  2275. }
  2276. .message-item.message-self {
  2277. flex-direction: row-reverse;
  2278. }
  2279. .avatar {
  2280. width: 80rpx;
  2281. height: 80rpx;
  2282. border-radius: 8rpx;
  2283. margin: 0 20rpx;
  2284. }
  2285. .message-content-wrapper {
  2286. max-width: 70%;
  2287. display: inline-block;
  2288. }
  2289. .message-item.message-self .message-content-wrapper {
  2290. text-align: right; /* 关键:让气泡和状态提示整体右对齐 */
  2291. }
  2292. .message-name {
  2293. display: block;
  2294. font-size: 24rpx;
  2295. color: #999;
  2296. margin-bottom: 10rpx;
  2297. }
  2298. .message-bubble {
  2299. padding: 20rpx;
  2300. border-radius: 8rpx;
  2301. background-color: #fff;
  2302. word-wrap: break-word;
  2303. display: inline-block; /* 关键:气泡宽度由内容决定 */
  2304. max-width: 100%; /* 防止内容过长超出容器 */
  2305. position: relative;
  2306. }
  2307. .message-self .message-bubble {
  2308. background-color: #95ec69;
  2309. border-top-right-radius: 4rpx;
  2310. }
  2311. .message-bubble.bubble-self {
  2312. background-color: #95ec69;
  2313. }
  2314. .message-text {
  2315. font-size: 30rpx;
  2316. line-height: 1.5;
  2317. }
  2318. .message-image {
  2319. max-width: 400rpx;
  2320. border-radius: 8rpx;
  2321. }
  2322. .message-voice {
  2323. display: flex;
  2324. align-items: center;
  2325. gap: 12rpx;
  2326. padding: 0rpx 0;
  2327. min-width: 30rpx;
  2328. max-width: 400rpx;
  2329. cursor: pointer;
  2330. -webkit-tap-highlight-color: transparent;
  2331. outline: none;
  2332. border: none;
  2333. position: relative;
  2334. }
  2335. .voice-duration {
  2336. font-size: 27rpx;
  2337. color: #333;
  2338. flex-shrink: 0;
  2339. line-height: 1;
  2340. }
  2341. .voice-icon-wrapper {
  2342. display: flex;
  2343. flex-shrink: 0;
  2344. line-height: 0;
  2345. position: relative;
  2346. top: 1rpx;
  2347. }
  2348. .voice-icon {
  2349. width: 22rpx;
  2350. height: 22rpx;
  2351. display: block;
  2352. transform: none;
  2353. animation: none;
  2354. }
  2355. .voice-icon-wrapper.playing .voice-icon {
  2356. animation: voice-bounce 0.6s ease-in-out infinite;
  2357. }
  2358. .voice-resume-btn {
  2359. position: absolute;
  2360. top: 50%;
  2361. transform: translateY(-50%);
  2362. width: 32rpx;
  2363. height: 32rpx;
  2364. background: #07c160;
  2365. border-radius: 50%;
  2366. display: flex;
  2367. align-items: center;
  2368. justify-content: center;
  2369. box-shadow: 0 2rpx 8rpx rgba(7, 193, 96, 0.3);
  2370. }
  2371. .voice-resume-btn.resume-btn-left {
  2372. left: -40rpx;
  2373. }
  2374. .voice-resume-btn.resume-btn-right {
  2375. right: -40rpx;
  2376. }
  2377. .resume-icon {
  2378. color: #fff;
  2379. font-size: 16rpx;
  2380. margin-left: 2rpx;
  2381. }
  2382. @keyframes voice-bounce {
  2383. 0%, 100% {
  2384. transform: scale(1);
  2385. }
  2386. 50% {
  2387. transform: scale(1.2);
  2388. }
  2389. }
  2390. .message-video {
  2391. width: 400rpx;
  2392. height: 300rpx;
  2393. }
  2394. .message-recalled {
  2395. color: #999;
  2396. font-size: 28rpx;
  2397. }
  2398. .message-status {
  2399. text-align: right;
  2400. font-size: 22rpx;
  2401. color: #999;
  2402. margin-top: 8rpx;
  2403. }
  2404. .message-status .status-unread {
  2405. color: #999;
  2406. }
  2407. .message-status .status-read {
  2408. color: #07c160;
  2409. }
  2410. .message-status .status-failed {
  2411. color: #fa5151;
  2412. }
  2413. .message-time {
  2414. display: block;
  2415. text-align: right;
  2416. font-size: 22rpx;
  2417. color: #ccc;
  2418. margin-top: 5rpx;
  2419. }
  2420. /* 输入框 */
  2421. .input-bar {
  2422. display: flex;
  2423. align-items: center;
  2424. padding: 20rpx;
  2425. background-color: #fff;
  2426. border-top: 1px solid #e5e5e5;
  2427. }
  2428. .input-icon {
  2429. width: 80rpx;
  2430. height: 80rpx;
  2431. display: flex;
  2432. align-items: center;
  2433. justify-content: center;
  2434. font-size: 50rpx;
  2435. }
  2436. .input-icon .icon-image {
  2437. width: 50rpx;
  2438. height: 50rpx;
  2439. }
  2440. .send-button {
  2441. padding: 0 30rpx;
  2442. height: 70rpx;
  2443. line-height: 70rpx;
  2444. background-color: #07c160;
  2445. color: #fff;
  2446. border-radius: 8rpx;
  2447. text-align: center;
  2448. font-size: 28rpx;
  2449. margin-left: 10rpx;
  2450. transition: opacity 0.3s;
  2451. }
  2452. .send-button.disabled {
  2453. opacity: 0.5;
  2454. background-color: #95ec69;
  2455. }
  2456. .input-field {
  2457. flex: 1;
  2458. height: 70rpx;
  2459. padding: 0 20rpx;
  2460. background-color: #f5f5f5;
  2461. border-radius: 8rpx;
  2462. font-size: 30rpx;
  2463. }
  2464. .voice-button {
  2465. flex: 1;
  2466. height: 70rpx;
  2467. line-height: 70rpx;
  2468. background-color: #f5f5f5;
  2469. border-radius: 8rpx;
  2470. text-align: center;
  2471. font-size: 30rpx;
  2472. border: none;
  2473. }
  2474. /* 表情面板 */
  2475. .emoji-panel {
  2476. display: flex;
  2477. flex-wrap: wrap;
  2478. padding: 20rpx;
  2479. background-color: #fff;
  2480. border-top: 1px solid #e5e5e5;
  2481. }
  2482. .emoji-item {
  2483. width: 80rpx;
  2484. height: 80rpx;
  2485. display: flex;
  2486. align-items: center;
  2487. justify-content: center;
  2488. font-size: 60rpx;
  2489. }
  2490. /* 更多功能面板 */
  2491. .more-panel {
  2492. display: flex;
  2493. padding: 40rpx;
  2494. background-color: #fff;
  2495. border-top: 1px solid #e5e5e5;
  2496. }
  2497. .more-item {
  2498. display: flex;
  2499. flex-direction: column;
  2500. align-items: center;
  2501. margin: 0 40rpx;
  2502. }
  2503. .more-icon {
  2504. width: 100rpx;
  2505. height: 100rpx;
  2506. display: flex;
  2507. align-items: center;
  2508. justify-content: center;
  2509. font-size: 60rpx;
  2510. background-color: #f5f5f5;
  2511. border-radius: 16rpx;
  2512. margin-bottom: 10rpx;
  2513. }
  2514. .more-text {
  2515. font-size: 24rpx;
  2516. color: #666;
  2517. }
  2518. /* 时间分隔线 */
  2519. .time-divider {
  2520. text-align: center;
  2521. padding: 20rpx 0;
  2522. }
  2523. .time-text {
  2524. display: inline-block;
  2525. padding: 8rpx 20rpx;
  2526. background-color: rgba(0, 0, 0, 0.1);
  2527. border-radius: 8rpx;
  2528. font-size: 22rpx;
  2529. color: #999;
  2530. }
  2531. /* 消息气泡失败状态 */
  2532. .bubble-failed {
  2533. background-color: #95ec69;
  2534. opacity: 0.6;
  2535. border: 2rpx solid #fa5151;
  2536. }
  2537. /* 消息状态优化 */
  2538. .message-status .sending {
  2539. color: #576b95;
  2540. }
  2541. .message-status .failed-group {
  2542. display: flex;
  2543. align-items: center;
  2544. gap: 10rpx;
  2545. }
  2546. .message-status .retry-btn {
  2547. color: #576b95;
  2548. text-decoration: underline;
  2549. cursor: pointer;
  2550. }
  2551. /* 消息操作菜单遮罩 */
  2552. .message-action-mask {
  2553. position: fixed;
  2554. top: 0;
  2555. left: 0;
  2556. right: 0;
  2557. bottom: 0;
  2558. background-color: rgba(0, 0, 0, 0.4);
  2559. z-index: 9999;
  2560. display: flex;
  2561. align-items: center;
  2562. justify-content: center;
  2563. }
  2564. /* 消息操作菜单 */
  2565. .message-action-menu {
  2566. width: 600rpx;
  2567. background-color: #fff;
  2568. border-radius: 20rpx;
  2569. overflow: hidden;
  2570. }
  2571. .message-action-menu .menu-item {
  2572. display: flex;
  2573. align-items: center;
  2574. justify-content: center;
  2575. gap: 15rpx;
  2576. padding: 30rpx;
  2577. font-size: 32rpx;
  2578. color: #333;
  2579. border-bottom: 1rpx solid #f0f0f0;
  2580. transition: background-color 0.2s;
  2581. }
  2582. .message-action-menu .menu-item:active {
  2583. background-color: #f5f5f5;
  2584. }
  2585. .message-action-menu .menu-item.cancel {
  2586. color: #999;
  2587. border-bottom: none;
  2588. margin-top: 20rpx;
  2589. border-top: 10rpx solid #f5f5f5;
  2590. }
  2591. .message-action-menu .menu-icon {
  2592. font-size: 36rpx;
  2593. }
  2594. /* 消息发送限制提示 */
  2595. .message-limit-tip {
  2596. padding: 10rpx 20rpx;
  2597. font-size: 24rpx;
  2598. text-align: center;
  2599. background-color: #fff;
  2600. border-bottom: 1px solid #f5f5f5;
  2601. }
  2602. .vip-tip {
  2603. color: #ff9500; /* VIP橙色提示 */
  2604. }
  2605. .limit-tip {
  2606. color: #666; /* 普通灰色提示 */
  2607. }
  2608. .vip-link {
  2609. color: #2c9fff; /* 蓝色文字 */
  2610. text-decoration: underline; /* 下划线 */
  2611. cursor: pointer; /* 鼠标悬浮时显示手型 */
  2612. margin-left: 5rpx;
  2613. }
  2614. /* 点击时添加轻微反馈 */
  2615. .vip-link:active {
  2616. opacity: 0.7; /* 点击时透明度降低 */
  2617. }
  2618. /* 录音中提示遮罩 */
  2619. .voice-recording-mask {
  2620. position: fixed;
  2621. top: 0;
  2622. left: 0;
  2623. right: 0;
  2624. bottom: 0;
  2625. background-color: rgba(0, 0, 0, 0.6);
  2626. z-index: 10000;
  2627. display: flex;
  2628. align-items: center;
  2629. justify-content: center;
  2630. }
  2631. /* 录音提示框 */
  2632. .voice-recording-box {
  2633. width: 300rpx;
  2634. height: 300rpx;
  2635. background-color: rgba(0, 0, 0, 0.8);
  2636. border-radius: 20rpx;
  2637. display: flex;
  2638. flex-direction: column;
  2639. align-items: center;
  2640. justify-content: center;
  2641. color: #fff;
  2642. transition: background-color 0.3s;
  2643. }
  2644. .voice-recording-box.canceling {
  2645. background-color: rgba(220, 38, 38, 0.9);
  2646. }
  2647. .voice-wave-container {
  2648. display: flex;
  2649. align-items: center;
  2650. justify-content: center;
  2651. gap: 8rpx;
  2652. height: 100rpx;
  2653. margin-bottom: 20rpx;
  2654. }
  2655. .voice-wave-bar {
  2656. width: 6rpx;
  2657. background: #fff;
  2658. border-radius: 3rpx;
  2659. transition: transform 0.1s ease-out;
  2660. transform-origin: center;
  2661. }
  2662. .voice-wave-bar.bar1 {
  2663. height: 30rpx;
  2664. }
  2665. .voice-wave-bar.bar2 {
  2666. height: 45rpx;
  2667. }
  2668. .voice-wave-bar.bar3 {
  2669. height: 60rpx;
  2670. }
  2671. .voice-wave-bar.bar4 {
  2672. height: 50rpx;
  2673. }
  2674. .voice-wave-bar.bar5 {
  2675. height: 35rpx;
  2676. }
  2677. .voice-text {
  2678. font-size: 32rpx;
  2679. margin-bottom: 10rpx;
  2680. }
  2681. .voice-time {
  2682. font-size: 48rpx;
  2683. font-weight: bold;
  2684. color: #07c160;
  2685. margin: 10rpx 0;
  2686. }
  2687. .voice-tip {
  2688. font-size: 24rpx;
  2689. color: #ccc;
  2690. }
  2691. </style>