index.vue 17 KB

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