group-chat.vue 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. <template>
  2. <div class="single-page h-full w-full" style="height: 100vh">
  3. <van-nav-bar @click-left="router.back()" @click-right="onClickRight">
  4. <template #left>
  5. <div>
  6. <van-icon name="arrow-left" color="black" size="18"/>
  7. </div>
  8. </template>
  9. <template #title>
  10. <div class="text-2xl text-black-3 text-semibold">
  11. <div class="inline-block w-220 line-clamp-1">
  12. {{ title }}
  13. </div>
  14. <!-- <span class="ml-7 iconfont icon-close-remind text-black-9" style="font-size: 16px"></span> -->
  15. </div>
  16. </template>
  17. <template #right>
  18. <van-icon name="ellipsis" color="black" size="18"/>
  19. </template>
  20. </van-nav-bar>
  21. <template v-if="showPage">
  22. <van-list
  23. ref="chatListRef"
  24. class="flex-1 overflow-y-auto px-12 flex flex-col"
  25. :finished="true"
  26. finished-text=""
  27. >
  28. <template v-for="(message, index) in currConversationChatList" :key="index">
  29. <ChatMessage :show-name="true" :message="message" ></ChatMessage>
  30. </template>
  31. </van-list>
  32. <!-- <van-pull-refresh v-model="refreshing" @refresh="loadMore" class="flex-1">
  33. </van-pull-refresh>-->
  34. <!-- <div class="fixed bottom-0 left-0 right-0 w-full">-->
  35. <ChatInput :operates="['image', 'share-group']" @focus="scrollToBottom" @send="handleSendMessage"></ChatInput>
  36. <!-- </div>-->
  37. </template>
  38. <template v-else>
  39. <div class="flex-1 grid place-items-center text-black-9">
  40. <div v-if="pageLoading">创建会话中...</div>
  41. <div v-else class="grid place-items-center">
  42. <div v-if="groupId">创建成功</div>
  43. <div v-else class="grid place-items-center">
  44. <div class="mb-10">创建会话失败</div>
  45. <van-button size="small" @click="initGroupId">点击重试</van-button>
  46. </div>
  47. </div>
  48. </div>
  49. </template>
  50. </div>
  51. </template>
  52. <script setup>
  53. import ChatMessage from './chat-message'
  54. import ChatInput from "./chat-input";
  55. import {findHyperlinks} from "~/pages/chat/chat-message/link-message/handle";
  56. import {XYWebSocket} from "~/utils/XYWebSocket";
  57. import {isValidJson} from "~/utils";
  58. const route = useRoute()
  59. const router = useRouter()
  60. const chatsStore = useChatsStore();
  61. const userInfoStore = useUserInfoStore();
  62. const {userInfo} = storeToRefs(userInfoStore);
  63. // 单聊的标题
  64. const title = computed(() => route.query.groupRemark)
  65. // 聊天列表
  66. const chatListRef = ref(null);
  67. const pageLoading = ref(true);
  68. const getUserId = ref(null); // 消息接收者的用户id
  69. const sendUserId = computed(() => userInfo?.value.pass) // 消息发送者:当前登录用户的加密id
  70. const groupId = ref(route.query?.groupId); // 会话ID
  71. const showPage = computed(() => groupId.value)
  72. const initGroupId = async () => {
  73. try {
  74. /* if (!groupId.value) return;
  75. pageLoading.value = true;
  76. const res = await chatsStore.getCurrConversationId(getUserId.value)
  77. await handleResponse(res)
  78. groupId.value = res.data;*/
  79. await getChatList('init')
  80. } catch (e) {
  81. } finally {
  82. pageLoading.value = false;
  83. }
  84. }
  85. let pageNum = ref(0)
  86. const currConversationChatList = ref([]);
  87. /**
  88. * 加载当前聊天信息
  89. * @param type init|more
  90. * @returns {Promise<void>}
  91. */
  92. const getChatList = async (type = 'init') => {
  93. try {
  94. const page = type === 'init' ? 1 : pageNum.value + 1;
  95. const res = await chatsStore.getChatHistory({
  96. pageNum: page,
  97. pageSize: 100,
  98. groupId: groupId.value,
  99. })
  100. pageNum.value = page;
  101. await handleResponse(res);
  102. currConversationChatList.value = handleChatList(res.data?.data)
  103. console.log(currConversationChatList.value, 'currConversationChatList')
  104. if (type === 'init') await scrollToBottom()
  105. } catch (e) {
  106. console.error(e)
  107. } finally {
  108. }
  109. }
  110. const handleChatList = (list = []) => {
  111. return (list ?? []).filter(o => isValidJson(o.messageContent)).map(o => JSON.parse(o.messageContent));
  112. }
  113. // 发送文本消息
  114. const sendTextMessage = async (text) => {
  115. try {
  116. console.log(text, 'sendTextMessage')
  117. if (!text) return
  118. let msg = {
  119. groupId: groupId.value,
  120. getUserId: getUserId.value,
  121. sendUserId: sendUserId.value,
  122. specialUserId: '',
  123. messageContent: text,
  124. messageType: 0,
  125. noticeType: 2,
  126. object: {
  127. id: getLocalId()
  128. }
  129. }
  130. const isLink = !!findHyperlinks(text)
  131. if (isLink) msg.messageType = 4;
  132. currConversationChatList.value.push(msg)
  133. await scrollToBottom()
  134. const res = await chatsStore.sendSocketMessage(msg)
  135. console.log('luck:', res)
  136. } catch (e) {
  137. console.log(e, '2')
  138. } finally {
  139. }
  140. }
  141. // 选择发送图片
  142. const sendImageMessage = async (file) => {
  143. try {
  144. const formData = new FormData()
  145. formData.append('uploadFile', file)
  146. formData.append('asImage', true)
  147. formData.append('fieldName', 'messageContent')
  148. const {data} = await request('/website/tourMessage/upload', {
  149. method: 'post',
  150. body: formData
  151. })
  152. let msg = {
  153. groupId: groupId.value,
  154. getUserId: getUserId.value,
  155. sendUserId: sendUserId.value,
  156. specialUserId: '',
  157. messageContent: data.fileUrl,
  158. messageType: 1,
  159. noticeType: 2,
  160. object: {
  161. id: getLocalId()
  162. }
  163. }
  164. currConversationChatList.value.push(msg)
  165. await scrollToBottom()
  166. await chatsStore.sendSocketMessage(msg)
  167. } catch (e) {
  168. console.error(e, '??')
  169. } finally {
  170. }
  171. }
  172. const handleSendMessage = async ({type, messageContent}) => {
  173. try {
  174. switch (type) {
  175. case 'text':
  176. await sendTextMessage(messageContent)
  177. break;
  178. case 'image':
  179. await sendImageMessage(messageContent)
  180. break;
  181. default:
  182. break;
  183. }
  184. } catch (e) {
  185. } finally {
  186. }
  187. }
  188. const scrollToBottom = async () => {
  189. setTimeout(async () => {
  190. await nextTick(); // 确保DOM已经更新
  191. const listElement = chatListRef.value?.$el;
  192. if (listElement) {
  193. const scrollContainer = listElement;
  194. scrollContainer.scrollTop = scrollContainer.scrollHeight;
  195. }
  196. }, 200)
  197. };
  198. // 加载更多
  199. const refreshing = ref(false)
  200. const loadMore = async () => {
  201. try {
  202. refreshing.value = true
  203. await getChatList('more')
  204. } catch (e) { } finally {
  205. refreshing.value = false
  206. }
  207. }
  208. const onClickRight = () => {
  209. groupId.value && navigateTo({
  210. path: '/chat/set',
  211. query: {groupId: groupId.value}
  212. })
  213. }
  214. // 本地生成一个唯一消息id
  215. function getLocalId() {
  216. const random = Math.floor(Math.random() * 10000)
  217. return Date.now() + '' + random
  218. }
  219. onMounted(() => {
  220. initGroupId()
  221. XYWebSocket.SocketEventsBus.on(XYWebSocket.SocketEvents.chatEvent, async (chat) => {
  222. const isCurrGroupId = chat.groupId && chat.groupId === groupId.value;
  223. const isOtherUserMessage = chat.sendUserId && chatsStore.isRealMessage(chat.sendUserId);
  224. if (isCurrGroupId && isOtherUserMessage) {
  225. currConversationChatList.value.push(chat)
  226. await scrollToBottom()
  227. }
  228. })
  229. })
  230. // 用户删除消息
  231. const delMessage = (messageId) => {
  232. showConfirmDialog({
  233. width: 260,
  234. message: '是否删除这条消息?',
  235. confirmButtonColor: '#FF9300'
  236. })
  237. .then(async () => {
  238. const res = await request('/website/tourMessage/delMessage', {
  239. method: 'post',
  240. body: {
  241. messageId: [messageId]
  242. }
  243. })
  244. if (res && res?.success) {
  245. }
  246. })
  247. .catch(() => {
  248. })
  249. }
  250. definePageMeta({
  251. layout: false
  252. })
  253. </script>
  254. <style lang="scss" scoped>
  255. .single-page {
  256. height: 100vh;
  257. display: flex;
  258. flex-direction: column;
  259. min-height: 0;
  260. }
  261. </style>