index.vue 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628
  1. <template>
  2. <view class="chat-page">
  3. <view class="chat-header">
  4. <view class="chat-header-main">
  5. <view class="back" @click="goBack">
  6. <image class="header-icon-img" src="/static/icons/back.svg" mode="aspectFit" />
  7. </view>
  8. <view class="chat-title-wrap" @click="onTitleClick">
  9. <view class="chat-title-texts">
  10. <text class="chat-title">{{ contactTitle }}</text>
  11. </view>
  12. </view>
  13. <view class="header-actions">
  14. <view class="header-icon" @click="onMore">
  15. <image class="header-icon-img" src="/static/icons/more.svg" mode="aspectFit" />
  16. </view>
  17. </view>
  18. </view>
  19. </view>
  20. <scroll-view
  21. class="message-list"
  22. scroll-y
  23. :scroll-into-view="scrollIntoView"
  24. scroll-with-animation
  25. @scrolltoupper="onLoadMore"
  26. >
  27. <view v-if="loadingMoreForContact" class="load-more">加载更多...</view>
  28. <view v-else-if="!messageList.length" class="empty-messages">
  29. <text class="empty-text">暂无消息,发一句打个招呼吧</text>
  30. </view>
  31. <view
  32. v-for="(msg, index) in messageList"
  33. :key="msg.id || msg.tempId || index"
  34. :id="'msg-' + (msg.id || msg.tempId)"
  35. >
  36. <PrivateMessageBubble
  37. v-if="msg.type === 'MESSAGE' || msg.type === 'PRIVATE' || !msg.type"
  38. :msg="msg"
  39. :sender-name="getSenderName(msg)"
  40. :sender-id="otherUserId"
  41. :sender-avatar="contactAvatar"
  42. :me-name="currentUserName"
  43. :me-id="currentUserId"
  44. :me-avatar="currentUserAvatar"
  45. :show-date-label="shouldShowDateLabel(index)"
  46. :remind-loading="remindingNotificationId === String(msg.id)"
  47. @preview-image="previewImage"
  48. @open-notification-url="openNotificationUrl"
  49. @retry="onRetry"
  50. @remind-user-notification="onRemindUserNotification"
  51. />
  52. <NotificationBubble
  53. v-else
  54. :msg="msg"
  55. :sender-name="getSenderName(msg)"
  56. :show-date-label="shouldShowDateLabel(index)"
  57. @open-notification-url="openNotificationUrl"
  58. />
  59. </view>
  60. </scroll-view>
  61. <view class="input-bar">
  62. <view class="input-row">
  63. <view class="input-wrap">
  64. <input
  65. v-model="inputValue"
  66. class="input"
  67. :placeholder="'发送给 ' + contactTitle"
  68. confirm-type="send"
  69. @confirm="onSend"
  70. @focus="onInputFocus"
  71. />
  72. </view>
  73. <view class="input-icon input-icon-plus" @click="onPlus">
  74. <image class="input-plus-img" src="/static/icons/add.svg" mode="aspectFit" />
  75. </view>
  76. </view>
  77. <view v-if="showPlusPanel" class="plus-panel">
  78. <view class="plus-item" @click="onChooseImage">
  79. <view class="plus-icon">
  80. <image class="plus-inner-icon" src="/static/icons/image.svg" mode="aspectFit" />
  81. </view>
  82. <text class="plus-label-title">图片</text>
  83. </view>
  84. <view class="plus-item" @click="onChooseVideo">
  85. <view class="plus-icon">
  86. <image class="plus-inner-icon" src="/static/icons/video.svg" mode="aspectFit" />
  87. </view>
  88. <text class="plus-label-title">视频</text>
  89. </view>
  90. <view class="plus-item" @click="onChooseFile">
  91. <view class="plus-icon">
  92. <image class="plus-inner-icon" src="/static/icons/file.svg" mode="aspectFit" />
  93. </view>
  94. <text class="plus-label-title">文件</text>
  95. </view>
  96. </view>
  97. </view>
  98. </view>
  99. </template>
  100. <script setup>
  101. import { ref, computed, watch, nextTick } from 'vue'
  102. import { onLoad, onUnload, onShow } from '@dcloudio/uni-app'
  103. import PrivateMessageBubble from '../../components/chat/PrivateMessageBubble.vue'
  104. import NotificationBubble from '../../components/chat/NotificationBubble.vue'
  105. import { useMessages } from '../../composables/useMessages'
  106. import { useContacts } from '../../composables/useContacts'
  107. import { chatStore } from '../../store/chat'
  108. import { getMessageCallbackUrl, getToken } from '../../utils/api'
  109. const otherUserId = ref('')
  110. const contactTitle = ref('会话')
  111. const fallbackContactName = ref('')
  112. const inputValue = ref('')
  113. const scrollIntoView = ref('')
  114. /** 从消息搜索进入时滚动到指定消息 id,定位后清空 */
  115. const scrollToMessageId = ref('')
  116. /** 用于区分「底部最后一条是否变化」:加载更多只 prepend 时不变,避免误滚到底 */
  117. const lastBottomMsgKey = ref('')
  118. const showPlusPanel = ref(false)
  119. /** 正在对哪条 USER_NOTIFICATION 执行「再次提醒」(用于按钮 loading,并防并发连点) */
  120. const remindingNotificationId = ref('')
  121. const { messages, loadingMore, fetchMessages, fetchMoreMessages, sendMessage, retrySendMessage, sendFileMessage, retrySendFileMessage, remindUserNotification } = useMessages()
  122. const { fetchContacts } = useContacts()
  123. function syncContactTitle() {
  124. const contact = (chatStore.contacts || []).find((c) => String(c.user_id || c.id) === String(otherUserId.value))
  125. if (contact) {
  126. contactTitle.value = (contact.app_name || contact.title || '会话')
  127. return
  128. }
  129. // 若会话列表未命中(例如从联系人详情进入,此时 chatStore.contacts 未包含该用户)
  130. contactTitle.value = fallbackContactName.value || '会话'
  131. }
  132. const messageList = computed(() => {
  133. const id = String(otherUserId.value)
  134. return (messages[id] || [])
  135. })
  136. const loadingMoreForContact = computed(() => !!loadingMore[String(otherUserId.value)])
  137. /** 滚到列表底部;先清空 scroll-into-view 再设锚点,避免同 id 时不滚动 */
  138. function scrollToBottom() {
  139. if (scrollToMessageId.value) return
  140. const list = messageList.value
  141. if (!list.length) return
  142. const last = list[list.length - 1]
  143. const anchor = 'msg-' + (last.id || last.tempId)
  144. scrollIntoView.value = ''
  145. nextTick(() => {
  146. scrollIntoView.value = anchor
  147. setTimeout(() => {
  148. scrollIntoView.value = anchor
  149. }, 50)
  150. })
  151. }
  152. onLoad((options) => {
  153. lastBottomMsgKey.value = ''
  154. otherUserId.value = String(
  155. (options && (options.otherUserId || options.userId || options.contactId)) || '0'
  156. )
  157. // 用联系人详情传参兜底:保证从联系人详情进来仍能显示名字
  158. try {
  159. const raw = options && options.contactName != null ? String(options.contactName) : ''
  160. const s = raw
  161. // 若未自动解码,可能是 %E5...,这里做一次安全解码
  162. if (/%[0-9A-Fa-f]{2}/.test(s)) fallbackContactName.value = decodeURIComponent(s)
  163. else fallbackContactName.value = s
  164. } catch (e) {
  165. fallbackContactName.value = ''
  166. }
  167. try {
  168. const mid = options && (options.scrollToMessageId || options.messageId)
  169. if (mid != null && String(mid).trim() !== '') scrollToMessageId.value = String(mid).trim()
  170. } catch (e) {
  171. scrollToMessageId.value = ''
  172. }
  173. chatStore.setActiveContact(otherUserId.value)
  174. chatStore.clearUnread(otherUserId.value)
  175. chatStore.updateTabBarUnreadBadge()
  176. syncContactTitle()
  177. try {
  178. const u = uni.getStorageSync('current_user')
  179. if (u && typeof u === 'object') {
  180. if (u.name) currentUserName.value = u.name
  181. currentUserId.value = String(u.id ?? u.user_id ?? '')
  182. currentUserAvatar.value = u.avatar || u.avatar_url || ''
  183. }
  184. } catch (e) {}
  185. // 进入聊天时,确保会话列表已就绪:联系人详情页跳转时可能还没加载 chatStore.contacts
  186. if (!chatStore.contacts || !chatStore.contacts.length) {
  187. Promise.resolve()
  188. .then(() => fetchContacts())
  189. .then(() => syncContactTitle())
  190. .catch(() => {})
  191. } else {
  192. // contacts 已有数据时也做一次兜底(例如 otherUserId 刚好没命中但后续会更新)
  193. syncContactTitle()
  194. }
  195. })
  196. /** 每次显示页面都拉最新一页(含从子页返回),并在数据就绪后滚到底 */
  197. onShow(async () => {
  198. const id = otherUserId.value
  199. if (!id || id === '0') return
  200. await fetchMessages(id)
  201. scrollToBottom()
  202. })
  203. onUnload(() => {
  204. chatStore.setActiveContact('')
  205. })
  206. watch(messageList, (list) => {
  207. if (!list.length) return
  208. const target = scrollToMessageId.value
  209. if (target) {
  210. const hit = list.find((m) => String(m.id) === String(target) || String(m.tempId) === String(target))
  211. if (hit) {
  212. const anchor = 'msg-' + (hit.id || hit.tempId)
  213. scrollIntoView.value = ''
  214. nextTick(() => {
  215. scrollIntoView.value = anchor
  216. })
  217. scrollToMessageId.value = ''
  218. return
  219. }
  220. return
  221. }
  222. const last = list[list.length - 1]
  223. const key = String(last.id || last.tempId)
  224. if (lastBottomMsgKey.value === key) return
  225. lastBottomMsgKey.value = key
  226. scrollToBottom()
  227. }, { deep: true })
  228. // contacts 更新后同步聊天标题(避免从联系人详情进入仍显示“会话”)
  229. watch(
  230. () => chatStore.contacts,
  231. () => {
  232. if (otherUserId.value) syncContactTitle()
  233. },
  234. { deep: true }
  235. )
  236. function goBack() {
  237. uni.navigateBack()
  238. }
  239. function onSend() {
  240. const text = inputValue.value.trim()
  241. if (!text) return
  242. sendMessage(otherUserId.value, text)
  243. inputValue.value = ''
  244. showPlusPanel.value = false
  245. }
  246. function onLoadMore() {
  247. fetchMoreMessages(otherUserId.value)
  248. }
  249. function basenameFromPath(p) {
  250. if (!p) return ''
  251. const s = String(p).replace(/\\/g, '/')
  252. const i = s.lastIndexOf('/')
  253. return i >= 0 ? s.slice(i + 1) : s
  254. }
  255. function onRetry(msg) {
  256. if (!msg || msg.status !== 'failed') return
  257. if (msg.contentType === 'TEXT') {
  258. retrySendMessage(otherUserId.value, msg)
  259. return
  260. }
  261. retrySendFileMessage(otherUserId.value, msg)
  262. }
  263. async function onRemindUserNotification(msg) {
  264. if (remindingNotificationId.value) return
  265. if (!msg || msg.tempId) return
  266. remindingNotificationId.value = String(msg.id)
  267. try {
  268. await remindUserNotification(otherUserId.value, msg)
  269. } finally {
  270. remindingNotificationId.value = ''
  271. }
  272. }
  273. function getSenderName(msg) {
  274. return msg.isMe ? (currentUserName.value || '我') : contactTitle.value
  275. }
  276. function shouldShowDateLabel(index) {
  277. const list = messageList.value
  278. if (index <= 0) return true
  279. const prev = list[index - 1]
  280. const curr = list[index]
  281. if (!prev || !curr || !prev.createdAt || !curr.createdAt) return true
  282. const prevDay = new Date(prev.createdAt).toDateString()
  283. const currDay = new Date(curr.createdAt).toDateString()
  284. return prevDay !== currDay
  285. }
  286. const currentUserName = ref('')
  287. const currentUserId = ref('')
  288. const currentUserAvatar = ref('')
  289. const contactAvatar = computed(() => {
  290. const contact = (chatStore.contacts || []).find((c) => String(c.user_id || c.id) === String(otherUserId.value))
  291. return (contact && contact.avatar) ? contact.avatar : ''
  292. })
  293. function previewImage(url) {
  294. if (!url) return
  295. uni.previewImage({ urls: [url] })
  296. }
  297. async function openNotificationUrl(msg) {
  298. const token = getToken()
  299. try {
  300. const res = await getMessageCallbackUrl(token, msg.id)
  301. const url = res.callback_url || res.callbackUrl || msg.actionUrl
  302. if (url) {
  303. const pageUrl =
  304. '/pages/webview/index?url=' +
  305. encodeURIComponent(url) +
  306. '&title=' +
  307. encodeURIComponent(msg.title || '详情')
  308. uni.navigateTo({ url: pageUrl })
  309. }
  310. } catch (e) {
  311. if (msg.actionUrl) {
  312. const pageUrl =
  313. '/pages/webview/index?url=' +
  314. encodeURIComponent(msg.actionUrl) +
  315. '&title=' +
  316. encodeURIComponent(msg.title || '详情')
  317. uni.navigateTo({ url: pageUrl })
  318. } else {
  319. uni.showToast({ title: '打开失败', icon: 'none' })
  320. }
  321. }
  322. }
  323. function onTitleClick() {
  324. // 可扩展:进入联系人详情或下拉菜单
  325. }
  326. function onMore() {
  327. uni.showActionSheet({
  328. itemList: ['聊天信息', '查找聊天内容', '清空聊天记录'],
  329. success: (res) => {}
  330. })
  331. }
  332. function onInputFocus() {
  333. showPlusPanel.value = false
  334. }
  335. function onChooseImage() {
  336. uni.hideKeyboard()
  337. uni.chooseImage({
  338. count: 1,
  339. success: (res) => {
  340. const path = res.tempFilePaths[0]
  341. const name = basenameFromPath(path) || 'image.jpg'
  342. sendFileMessage(otherUserId.value, path, 'IMAGE', name)
  343. }
  344. })
  345. }
  346. function onChooseVideo() {
  347. uni.hideKeyboard()
  348. uni.chooseVideo({
  349. sourceType: ['album', 'camera'],
  350. success: (res) => {
  351. const path = res.tempFilePath || (res.tempFilePaths && res.tempFilePaths[0])
  352. if (path) {
  353. const name = basenameFromPath(path) || 'video.mp4'
  354. sendFileMessage(otherUserId.value, path, 'VIDEO', name)
  355. }
  356. }
  357. })
  358. }
  359. function onChooseFile() {
  360. uni.hideKeyboard()
  361. const pick = (path, name) => {
  362. const n = (name && String(name).trim()) || basenameFromPath(path) || '文件'
  363. sendFileMessage(otherUserId.value, path, 'FILE', n)
  364. }
  365. if (typeof uni.chooseMessageFile === 'function') {
  366. uni.chooseMessageFile({
  367. count: 1,
  368. type: 'file',
  369. success: (res) => {
  370. const file = res.tempFiles && res.tempFiles[0]
  371. if (file && file.path) pick(file.path, file.name)
  372. }
  373. })
  374. } else if (typeof uni.chooseFile === 'function') {
  375. uni.chooseFile({
  376. count: 1,
  377. success: (res) => {
  378. const path = (res.tempFilePaths && res.tempFilePaths[0]) || ''
  379. if (path) pick(path)
  380. }
  381. })
  382. } else {
  383. uni.showToast({ title: '当前端暂不支持选文件', icon: 'none' })
  384. }
  385. }
  386. function onPlus() {
  387. uni.hideKeyboard()
  388. showPlusPanel.value = !showPlusPanel.value
  389. }
  390. </script>
  391. <style scoped>
  392. .chat-page {
  393. height: 100vh;
  394. display: flex;
  395. flex-direction: column;
  396. background: #f3f4f6;
  397. overflow-x: hidden;
  398. /* 顶部安全区由 header 自己处理 */
  399. padding-bottom: constant(safe-area-inset-bottom);
  400. padding-bottom: env(safe-area-inset-bottom);
  401. }
  402. .chat-header {
  403. /* 只负责安全区和背景,与会话列表页 custom-header 对齐 */
  404. padding: 0 24rpx 24rpx 32rpx;
  405. padding-top: 88rpx;
  406. padding-top: max(88rpx, calc(24rpx + constant(safe-area-inset-top)));
  407. padding-top: max(88rpx, calc(24rpx + env(safe-area-inset-top)));
  408. background: #ffffff;
  409. box-shadow: 0 1px 0 rgba(15, 23, 42, 0.06);
  410. }
  411. .chat-header-main {
  412. height: 88rpx;
  413. display: flex;
  414. align-items: center;
  415. justify-content: space-between;
  416. position: relative;
  417. }
  418. .back {
  419. width: 64rpx;
  420. height: 64rpx;
  421. display: flex;
  422. align-items: center;
  423. justify-content: center;
  424. margin-right: 8rpx;
  425. }
  426. .header-icon-img {
  427. width: 44rpx;
  428. height: 44rpx;
  429. opacity: 0.9;
  430. }
  431. .chat-title-wrap {
  432. position: absolute;
  433. left: 50%;
  434. transform: translateX(-50%);
  435. display: flex;
  436. align-items: center;
  437. justify-content: center;
  438. }
  439. .chat-title-texts {
  440. display: flex;
  441. flex-direction: column;
  442. justify-content: center;
  443. }
  444. .chat-title {
  445. font-size: 34rpx;
  446. font-weight: 600;
  447. color: #111827;
  448. }
  449. .header-actions {
  450. display: flex;
  451. align-items: center;
  452. gap: 16rpx;
  453. }
  454. .header-icon {
  455. width: 56rpx;
  456. height: 56rpx;
  457. display: flex;
  458. align-items: center;
  459. justify-content: center;
  460. }
  461. .message-list {
  462. flex: 1;
  463. min-height: 0;
  464. height: 0;
  465. /* 去掉顶部内边距,使第一条消息与列表页首行对齐 */
  466. padding: 0 24rpx 16rpx;
  467. }
  468. .load-more {
  469. text-align: center;
  470. padding: 16rpx;
  471. font-size: 24rpx;
  472. color: #999;
  473. }
  474. .empty-messages {
  475. flex: 1;
  476. display: flex;
  477. align-items: center;
  478. justify-content: center;
  479. min-height: 200rpx;
  480. padding: 48rpx;
  481. }
  482. .empty-text {
  483. font-size: 28rpx;
  484. color: #999;
  485. }
  486. .input-bar {
  487. display: flex;
  488. flex-direction: column;
  489. gap: 16rpx;
  490. padding: 10rpx 16rpx;
  491. background: #f5f5f7;
  492. border-top: 1rpx solid #e5e7eb;
  493. padding-bottom: max(10rpx, constant(safe-area-inset-bottom));
  494. padding-bottom: max(10rpx, env(safe-area-inset-bottom));
  495. }
  496. .input-row {
  497. display: flex;
  498. align-items: center;
  499. }
  500. .input-wrap {
  501. position: relative;
  502. min-height: 60rpx;
  503. max-height: 140rpx;
  504. padding: 6rpx 18rpx;
  505. background: #ffffff;
  506. border-radius: 999rpx;
  507. flex: 1;
  508. display: flex;
  509. align-items: center;
  510. }
  511. .input {
  512. min-height: 40rpx;
  513. font-size: 26rpx;
  514. height: 44rpx;
  515. line-height: 44rpx;
  516. padding: 0;
  517. width: 100%;
  518. box-sizing: border-box;
  519. }
  520. .input-icons {
  521. display: flex;
  522. align-items: center;
  523. justify-content: flex-start;
  524. gap: 24rpx;
  525. }
  526. .input-icon {
  527. width: 64rpx;
  528. height: 64rpx;
  529. display: flex;
  530. align-items: center;
  531. justify-content: center;
  532. }
  533. .input-icon .icon-emoji,
  534. .input-icon .icon-at,
  535. .input-icon .icon-mic,
  536. .input-icon .icon-pic,
  537. .input-icon .icon-aa {
  538. font-size: 40rpx;
  539. color: #6b7280;
  540. }
  541. .input-icon-plus {
  542. margin-left: 12rpx;
  543. border-radius: 999rpx;
  544. border: 2rpx solid #111827;
  545. background: #ffffff;
  546. }
  547. .input-plus-img {
  548. width: 36rpx;
  549. height: 36rpx;
  550. opacity: 0.9;
  551. }
  552. .plus-panel {
  553. margin-top: 12rpx;
  554. padding: 24rpx 16rpx 12rpx;
  555. background: #f5f5f7;
  556. border-radius: 24rpx;
  557. display: flex;
  558. justify-content: space-between;
  559. }
  560. .plus-item {
  561. flex: 1;
  562. display: flex;
  563. flex-direction: column;
  564. align-items: center;
  565. justify-content: flex-start;
  566. }
  567. .plus-icon {
  568. width: 120rpx;
  569. height: 120rpx;
  570. border-radius: 32rpx;
  571. background: #ffffff;
  572. display: flex;
  573. align-items: center;
  574. justify-content: center;
  575. margin-bottom: 8rpx;
  576. }
  577. .plus-inner-icon {
  578. width: 56rpx;
  579. height: 56rpx;
  580. }
  581. .plus-label-title {
  582. font-size: 26rpx;
  583. color: #111111;
  584. }
  585. .plus-label-desc {
  586. margin-top: 2rpx;
  587. font-size: 22rpx;
  588. color: #999999;
  589. }
  590. </style>