chat.vue 74 KB

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