Im.vue 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. <script setup lang="ts">
  2. import dayjs from 'dayjs'
  3. import { computed, ref, watch } from 'vue'
  4. import { useI18n } from 'vue-i18n'
  5. import type { Conversation } from '@tencentcloud/lite-chat'
  6. import { useImPopup } from '~/composables/useImPopup'
  7. import TitleIcon from '~/assets/icons/tab-active.svg'
  8. import CloseListIcon from '~/assets/icons/im/close-list.svg'
  9. import { IM_ADMIN } from '~/constants'
  10. const { state, close, clearTarget } = useImPopup()
  11. const { t, locale } = useI18n()
  12. const {
  13. ready,
  14. conversationList,
  15. conversationLoading,
  16. conversationError,
  17. getConversationList,
  18. bizUserInfoMap,
  19. ensureBizUserInfos,
  20. bizUserOnlineStateMap,
  21. ensureBizUserOnlineStates,
  22. login: loginIm,
  23. logout: logoutIm,
  24. destroy: destroyIm,
  25. } = useChat()
  26. const route = useRoute()
  27. const { isAuthenticated, isInitialized, userProfile } = useAuth()
  28. type ViewMode = 'list' | 'detail'
  29. const view = ref<ViewMode>('list')
  30. const activeConversationId = ref<string | null>(null)
  31. const placeholderConversation = ref<Conversation | null>(null)
  32. const list = computed(() => conversationList.value
  33. ? conversationList.value.filter((conv) => {
  34. return conv.userProfile?.userID !== IM_ADMIN
  35. })
  36. : [])
  37. const activeConversation = computed(() => {
  38. const id = activeConversationId.value
  39. if (!id) return null
  40. return list.value.find(c => c.conversationID === id) ?? placeholderConversation.value
  41. })
  42. const getPeerUserNo = (conv: Conversation) => {
  43. const rawUserId = conv?.userProfile?.userID ? String(conv.userProfile.userID) : ''
  44. if (rawUserId) {
  45. // Some SDK payloads may return "C2Cxxx" as userID; business uses plain userNo.
  46. if (rawUserId.toUpperCase().startsWith('C2C')) return rawUserId.slice(3)
  47. return rawUserId
  48. }
  49. const cid = conv?.conversationID ? String(conv.conversationID) : ''
  50. return cid.toUpperCase().startsWith('C2C') ? cid.slice(3) : ''
  51. }
  52. const getConversationName = (conv: Conversation) => {
  53. const userNo = getPeerUserNo(conv)
  54. const biz = userNo ? bizUserInfoMap.value?.[userNo] : undefined
  55. return biz?.nickname || conv?.remark || conv?.userProfile?.nick || conv?.groupProfile?.name || conv?.conversationID || ''
  56. }
  57. const getConversationAvatar = (conv: Conversation) => {
  58. const userNo = getPeerUserNo(conv)
  59. const biz = userNo ? bizUserInfoMap.value?.[userNo] : undefined
  60. return biz?.avatar || conv?.userProfile?.avatar || conv?.groupProfile?.avatar || '/avatar.png'
  61. }
  62. const getConversationOnline = (conv: Conversation) => {
  63. const userNo = getPeerUserNo(conv)
  64. if (!userNo) return undefined
  65. if (!Object.prototype.hasOwnProperty.call(bizUserOnlineStateMap.value, userNo)) return undefined
  66. return bizUserOnlineStateMap.value[userNo] === true
  67. }
  68. const getConversationLastText = (conv: Conversation) => {
  69. // Ensure UI updates when locale changes.
  70. void locale.value
  71. const msg = conv?.lastMessage
  72. if (!msg) return ''
  73. const text = msg?.payload?.text
  74. if (typeof text === 'string' && text.trim()) return text
  75. const type = String(msg?.type || '').toLowerCase()
  76. if (type.includes('image')) return t('im.message.image')
  77. if (type.includes('video')) return t('im.message.video')
  78. if (type.includes('file')) return t('im.message.file')
  79. if (type.includes('audio')) return t('im.message.audio')
  80. return t('im.message.generic')
  81. }
  82. const getConversationTimeLabel = (conv: Conversation) => {
  83. // Ensure UI updates when locale changes.
  84. void locale.value
  85. const sec = Number(conv?.lastMessage?.lastTime)
  86. if (!Number.isFinite(sec) || sec <= 0) return ''
  87. const time = dayjs.unix(sec)
  88. if (dayjs().diff(time, 'second') < 60) return t('im.time.now')
  89. if (dayjs().isSame(time, 'day')) return time.tz().format('HH:mm')
  90. return time.tz().format('MM/DD')
  91. }
  92. const fetchConversations = async () => {
  93. if (!state.visible) return
  94. if (!ready.value) return
  95. await getConversationList()
  96. }
  97. const activeName = computed(() => activeConversation.value ? getConversationName(activeConversation.value) : '')
  98. const activeAvatar = computed(() => activeConversation.value ? getConversationAvatar(activeConversation.value) : '/avatar.png')
  99. const activeBizUserInfo = computed(() => {
  100. if (!activeConversation.value) return undefined
  101. const userNo = getPeerUserNo(activeConversation.value)
  102. if (!userNo) return undefined
  103. return bizUserInfoMap.value?.[userNo]
  104. })
  105. const activeOnline = computed(() => {
  106. if (!activeConversation.value) return undefined
  107. return getConversationOnline(activeConversation.value)
  108. })
  109. const openConversationDetail = (conv: Conversation) => {
  110. activeConversationId.value = conv.conversationID
  111. placeholderConversation.value = null
  112. view.value = 'detail'
  113. }
  114. const backToList = () => {
  115. view.value = 'list'
  116. activeConversationId.value = null
  117. placeholderConversation.value = null
  118. clearTarget()
  119. }
  120. watch(
  121. () => [state.visible, ready.value] as const,
  122. ([visible, isReady]) => {
  123. if (visible && isReady) fetchConversations()
  124. },
  125. { immediate: true },
  126. )
  127. async function openConversationByUserId(userIdRaw: unknown) {
  128. const userId = userIdRaw ? String(userIdRaw).trim() : ''
  129. if (!userId) return
  130. if (!state.visible) return
  131. if (!ready.value) return
  132. try {
  133. await ensureBizUserInfos([userId])
  134. await ensureBizUserOnlineStates([userId])
  135. await getConversationList()
  136. }
  137. catch {
  138. // ignore; we will still open a placeholder conversation
  139. }
  140. const convFromList = list.value.find((c) => {
  141. const uid = getPeerUserNo(c)
  142. return uid === userId || String(c?.conversationID ?? '') === `C2C${userId}`
  143. })
  144. if (convFromList) {
  145. placeholderConversation.value = null
  146. activeConversationId.value = String(convFromList.conversationID)
  147. view.value = 'detail'
  148. clearTarget()
  149. return
  150. }
  151. // Fallback: open detail with a minimal placeholder conversation.
  152. placeholderConversation.value = {
  153. conversationID: `C2C${userId}`,
  154. userProfile: { userID: userId },
  155. } as unknown as Conversation
  156. activeConversationId.value = `C2C${userId}`
  157. view.value = 'detail'
  158. clearTarget()
  159. }
  160. watch(
  161. () => [state.visible, ready.value, state.targetUserId] as const,
  162. ([visible, isReady, target]) => {
  163. if (!visible || !isReady || !target) return
  164. void openConversationByUserId(target)
  165. },
  166. { immediate: true },
  167. )
  168. const handleUpdateShow = (value: boolean) => {
  169. if (!value) close()
  170. }
  171. watch(
  172. () => state.visible,
  173. (visible) => {
  174. if (!visible) {
  175. view.value = 'list'
  176. activeConversationId.value = null
  177. placeholderConversation.value = null
  178. }
  179. },
  180. )
  181. watch(
  182. () => route.fullPath,
  183. () => {
  184. if (state.visible) {
  185. close()
  186. }
  187. },
  188. )
  189. onMounted(async () => {
  190. watch(
  191. () => [isAuthenticated.value, isInitialized.value, userProfile.value?.userNo] as const,
  192. async ([_isAuthenticated, _isInitialized, userNo]) => {
  193. if (_isInitialized && _isAuthenticated && userNo) {
  194. await loginIm({ userId: userNo })
  195. }
  196. },
  197. { immediate: true },
  198. )
  199. watch(
  200. () => isAuthenticated.value,
  201. async (_isAuthenticated, _prevIsAuthenticated) => {
  202. if (_prevIsAuthenticated && !_isAuthenticated) {
  203. await logoutIm()
  204. }
  205. },
  206. )
  207. })
  208. onBeforeUnmount(async () => {
  209. await destroyIm()
  210. })
  211. </script>
  212. <template>
  213. <van-popup
  214. :show="state.visible"
  215. position="bottom"
  216. teleport="body"
  217. @update:show="handleUpdateShow"
  218. >
  219. <ImConversationDetail
  220. v-if="view === 'detail'"
  221. :conversation="activeConversation"
  222. :name="activeName"
  223. :avatar="activeAvatar"
  224. :online="activeOnline"
  225. :biz-user-info="activeBizUserInfo"
  226. @back="backToList"
  227. @close="close"
  228. />
  229. <div
  230. v-else
  231. class="im-popup"
  232. >
  233. <div class="im-popup__bg" />
  234. <div class="im-popup__header">
  235. <div class="im-popup__title">
  236. <TitleIcon class="im-popup__title-icon" />
  237. <span class="im-popup__title-text">
  238. {{ t('im.title') }}
  239. </span>
  240. </div>
  241. <button
  242. class="im-popup__close"
  243. type="button"
  244. @click="close"
  245. >
  246. <CloseListIcon />
  247. </button>
  248. </div>
  249. <div class="im-popup__content">
  250. <div
  251. v-if="!ready"
  252. class="im-popup__placeholder"
  253. >
  254. {{ t('im.placeholder.notReady') }}
  255. </div>
  256. <div
  257. v-else-if="conversationLoading"
  258. class="im-popup__placeholder"
  259. >
  260. {{ t('common.loading') }}
  261. </div>
  262. <div
  263. v-else-if="conversationError"
  264. class="im-popup__placeholder"
  265. >
  266. {{ conversationError }}
  267. </div>
  268. <div
  269. v-else-if="list.length === 0"
  270. class="im-popup__placeholder"
  271. >
  272. <img
  273. src="~/assets/images/common/empty.png"
  274. :alt="t('im.placeholder.emptyAlt')"
  275. >
  276. {{ t('im.placeholder.empty') }}
  277. </div>
  278. <div
  279. v-else
  280. class="im-popup__list"
  281. >
  282. <ImChatItem
  283. v-for="conv in list"
  284. :key="conv.conversationID"
  285. :avatar="getConversationAvatar(conv)"
  286. :online="getConversationOnline(conv)"
  287. :name="getConversationName(conv)"
  288. :time="getConversationTimeLabel(conv)"
  289. :message="getConversationLastText(conv)"
  290. :unread="conv.unreadCount"
  291. @click="openConversationDetail(conv)"
  292. />
  293. </div>
  294. </div>
  295. </div>
  296. </van-popup>
  297. </template>
  298. <style scoped lang="scss">
  299. .im-popup {
  300. height: 100vh;
  301. height: 100dvh;
  302. height: calc(var(--app-vh, 1vh) * 100);
  303. padding: 16px 16px 20px;
  304. position: relative;
  305. display: flex;
  306. flex-direction: column;
  307. &__bg {
  308. @include size(100%, 173px);
  309. @include bg('~/assets/images/home/header-bg.png', 100% 173px);
  310. position: absolute;
  311. inset: 0;
  312. z-index: 0;
  313. }
  314. &__header {
  315. display: flex;
  316. align-items: center;
  317. justify-content: space-between;
  318. position: relative;
  319. z-index: 1;
  320. }
  321. &__title {
  322. font-size: 24px;
  323. font-family: var(--font-title);
  324. font-weight: 600;
  325. color: #000;
  326. display: flex;
  327. align-items: center;
  328. justify-content: center;
  329. min-width: 0;
  330. &-icon {
  331. position: absolute;
  332. z-index: 0;
  333. }
  334. &-text {
  335. position: relative;
  336. z-index: 1;
  337. }
  338. }
  339. &__close {
  340. border: none;
  341. background: transparent;
  342. }
  343. &__content {
  344. display: flex;
  345. flex-direction: column;
  346. gap: 10px;
  347. position: relative;
  348. z-index: 1;
  349. flex: 1 1 auto;
  350. min-height: 0;
  351. overflow: auto;
  352. }
  353. &__list {
  354. margin-top: 10px;
  355. display: flex;
  356. flex-direction: column;
  357. gap: 14px;
  358. }
  359. &__placeholder {
  360. margin-top: 40px;
  361. display: flex;
  362. flex-direction: column;
  363. align-items: center;
  364. justify-content: center;
  365. gap: 12px;
  366. font-size: 12px;
  367. color: rgba(0, 0, 0, 0.70);
  368. img {
  369. @include size(100px);
  370. }
  371. }
  372. }
  373. </style>