Browse Source

feat:1.聊天模快群聊设置的接口对接调试

suwenjiang 2 months ago
parent
commit
fd3f7a8956
5 changed files with 206 additions and 124 deletions
  1. 1 1
      .env.development
  2. 40 28
      src/pages/chat/announcement.vue
  3. 69 33
      src/pages/chat/set.vue
  4. 4 2
      src/pages/profile/my-news/index.vue
  5. 92 60
      src/stores/chat.js

+ 1 - 1
.env.development

@@ -6,7 +6,7 @@ VITE_APP_ENV=development
 # 黄文
 # VITE_APP_BASE_URL=http://192.168.1.44:8082/
 # 畅哥
-# VITE_APP_BASE_URL=http://192.168.1.38:8082//
+# VITE_APP_BASE_URL=http://192.168.1.38:8082/
 
 # 张维
 VITE_APP_BASE_URL=http://192.168.1.73:8082/

+ 40 - 28
src/pages/chat/announcement.vue

@@ -1,5 +1,5 @@
 <template>
-  <div class="w-full h-[100vh] border">
+  <div class="w-full h-[100vh]">
     <van-nav-bar title="群公告" fixed @click-left="getBack">
       <template #left>
         <div>
@@ -9,19 +9,19 @@
       <template v-if="isRankAndFiler(queryDataName?.groupRole)" #right>
         <div
           :class="`font-semibold text-xl ${showBottom ? 'text-[#FF9300]' : 'text-black-9'} `"
-          @click="showBottom ? getUpdAnnouncement : () => {}"
+          @click="getUpdAnnouncement"
         >
+          <!--   -->
           确认
         </div>
       </template>
     </van-nav-bar>
     <div class="h-60"></div>
-
     <template v-if="isRankAndFiler(queryDataName?.groupRole)">
       <van-cell-group inset>
         <van-field
           style="background-color: #f7f8fa"
-          v-model="queryDataName.announcement"
+          v-model="queryDataName.groupNotice"
           required
           size="large"
           rows="5"
@@ -45,7 +45,7 @@
       <van-cell
         @click="
           () => {
-            queryDataName.announcement = groupBulletinTemplate
+            queryDataName.groupNotice = groupBulletinTemplate
             showBottom = true
           }
         "
@@ -57,10 +57,12 @@
       </van-cell>
     </template>
     <template v-else>
-      <div class="w-full px-16">
-        <div class="w-full mb-10" v-html="queryDataName?.announcement"></div>
+      <div style="height: calc(100vh - 60px)" class="w-full relative">
+        <div class="w-full px-16 mb-10" v-html="queryDataName?.groupNotice"></div>
 
-        <p class="text-sm text-black-9 text-center">仅群主及群管理员可编辑</p>
+        <p class="w-full text-sm text-black-9 text-center absolute bottom-52 left-0">
+          仅群主及群管理员可编辑
+        </p>
       </div>
     </template>
   </div>
@@ -69,7 +71,11 @@
 <script setup>
 const router = useRouter()
 const route = useRoute()
-console.log(route?.query?.groupId)
+
+// 是否是普通成员
+const isRankAndFiler = (role) => {
+  return role == 1 || role == 2 ? true : false
+}
 
 onMounted(() => {
   getAnnouncement()
@@ -82,17 +88,12 @@ const queryDataName = reactive({
   groupId: computed(() => route?.query?.groupId ?? ''),
   userId: computed(() => route?.query?.userId ?? ''),
   groupRole: computed(() => route?.query?.groupRole ?? ''),
-  announcement: ''
+  groupNotice: ''
 })
 
 //
 const showBottom = ref(false)
 
-// 是否是普通成员
-const isRankAndFiler = (role) => {
-  return role == 1 || role == 2 ? true : false
-}
-
 const getBack = () => {
   router.back()
   showBottom.value = false
@@ -103,30 +104,41 @@ definePageMeta({
 
 // 修改的接口
 const getUpdAnnouncement = async () => {
-  let { data } = await request('/website/tourism/visa/list/page', {
-    ...queryDataName
-  })
-  if (data) {
-    queryDataName.announcement = data
-    showBottom.value = false
-  } else {
-    showBottom.value = false
-  }
+  if (!showBottom.value) return
+
+  try {
+    let { data } = await request('/website/tourMessage/updateAnnouncement', {
+      method: 'post',
+      body: {
+        groupId: queryDataName.groupId,
+        messageContent: queryDataName.groupNotice
+      }
+    })
+    if (data) {
+      showBottom.value = false
+      showSuccessToast('群公告发布成功')
+      router.back()
+    } else {
+      showBottom.value = false
+    }
+  } catch (error) {}
 }
 
 // 获取公告
 const getAnnouncement = async () => {
-  let { data } = await request('/website/tourism/visa/list/page', {
-    ...queryDataName
+  const { data } = await request('/website/tourGroup/getGroupInfoAndMemberByGroupId', {
+    query: {
+      groupId: route.query.groupId
+    }
   })
   if (data) {
-    queryDataName.announcement = data
+    queryDataName.groupNotice = data.groupNotice
   } else {
   }
 }
 
 useSeoMeta({
-  title: '群公告'
+  title: '群'
 })
 </script>
 

+ 69 - 33
src/pages/chat/set.vue

@@ -313,7 +313,10 @@
       </van-cell-group>
 
       <div class="w-full pt-10 pb-40 px-16 box-border">
-        <van-button @click="handleExitGroupChat" color="#FF9300" round block>退出群聊</van-button>
+        <van-button @click="handleExitGroupChat" color="#FF9300" round block>
+          <template v-if="isRankAndFiler(userGroupData?.groupRole)">解散群聊</template>
+          <template v-else>退出群聊</template>
+        </van-button>
       </div>
     </div>
 
@@ -350,7 +353,7 @@ definePageMeta({
 })
 
 useSeoMeta({
-  title: '我的消息'
+  title: '群聊'
 })
 
 onMounted(() => {
@@ -435,6 +438,29 @@ const changeGroupName = async () => {
     }
   } catch (error) {}
 }
+// 修改群名称
+const changeGroup2 = async () => {
+  let body = { isNeedConfirm: changeStateBoolean(isNeedConfirm.value) }
+  // changeGroupName()
+}
+
+// async function changeGroupName(params) {
+//   try {
+//     const { data } = await request('/website/tourGroup/updateGroup', {
+//       method: 'post',
+//       body: {
+//         groupId: setData.id,
+//         ...params
+//       }
+//     })
+
+//     if (data) {
+//       showSuccessToast('修改成功')
+//     } else {
+//       showFailToast('修改失败')
+//     }
+//   } catch (error) {}
+// }
 
 // 修改备注名 和修改自己在群里的备注
 const changeTourMember = async (body) => {
@@ -571,41 +597,51 @@ const handleAnnouncement = () => {
   console.log(userGroupData.value?.groupRole, 'userGroupData?.groupRole')
   console.log(!isRankAndFiler(3))
   //  && !setData?.groupNotice
-  if (isRankAndFiler(userGroupData.value?.groupRole)) {
-    // navigateTo({
-    //   path: '/chat/announcement',
-    //   query: {
-    //     groupId: setData?.id,
-    //     userId: userInfo.value.userId,
-    //     groupRole: userGroupData.value?.groupRole
-    //   }
-    // })
-  }
-
-  if (!isRankAndFiler(userGroupData.value?.groupRole)) {
-    showConfirmDialog({
-      width: 260,
-      message: `只有群主${setData?.groupName ? setData?.groupName : ''}或群管理员才能修改公告`,
-      showCancelButton: false,
-      confirmButtonColor: '#FF9300',
-      confirmButtonText: '我知道了'
-    }).then(() => {})
-    return
-  }
-}
-
-// 退出群聊
-async function handleExitGroupChat() {
-  let { data } = await request('/website/tourGroup/exitGroup', {
+  // if (isRankAndFiler(userGroupData.value?.groupRole)) {
+  navigateTo({
+    path: '/chat/announcement',
     query: {
-      groupId: setData.groupId,
-      userId: user
+      groupId: setData?.id,
+      userId: userInfo.value.userId,
+      groupRole: userGroupData.value?.groupRole
     }
   })
-  navigateTo({
-    path: '/profile/my-news',
-    replace: true
+  // } else {
+  // showConfirmDialog({
+  //   width: 260,
+  //   message: `只有群主${setData?.groupName ? setData?.groupName : ''}或群管理员才能修改公告`,
+  //   showCancelButton: false,
+  //   confirmButtonColor: '#FF9300',
+  //   confirmButtonText: '我知道了'
+  // }).then(() => {})
+  // return
+  // }
+}
+
+// 退出群聊
+function handleExitGroupChat() {
+  showConfirmDialog({
+    width: 260,
+    title: '提示',
+    message: `是否${isRankAndFiler(userGroupData?.groupRole) ? '解散' : '退出'}当前群聊${setData?.groupName ? `"${setData?.groupName}"` : ''}`,
+    // showCancelButton: false,
+    confirmButtonColor: '#FF9300'
+    // confirmButtonText: '我知道了'
   })
+    .then(async () => {
+      const res = await request('/website/tourGroup/exitGroup', {
+        query: {
+          groupId: setData.id
+        }
+      })
+      if (res && res?.success) {
+        navigateTo({
+          path: '/profile/my-news',
+          replace: true
+        })
+      }
+    })
+    .catch(() => {})
 }
 </script>
 <style lang="scss" scoped>

+ 4 - 2
src/pages/profile/my-news/index.vue

@@ -156,7 +156,9 @@
       </div>
 
       <ProfileNewsGroupChat
-        @on-chat-page="onChatPage('/chat/group', { userId: userInfo.userId, groupId: 111 })"
+        @on-chat-page="
+          onChatPage('/chat/group', { userId: userInfo.userId, groupId: '1877349481146540033' })
+        "
         @on-no-bother="noBother()"
         @on-conv-delete="convDelete()"
       />
@@ -286,7 +288,7 @@ const onChatPage = (path, query) => {
 const onSelect = (action) => {
   if (action.text == '创建群聊') onChatPage('/chat/create-group', {})
   if (action.text == '群聊广场') onChatPage('/chat/group-square', {})
-  if (action.text == '加入群聊') onChatPage('/chat/sweep', {})
+  if (action.text == '加入群聊') onChatPage('/scan', {})
   if (action.text == '添加用户') onChatPage('/chat/user-add', {})
 }
 

+ 92 - 60
src/stores/chat.js

@@ -1,80 +1,112 @@
-import { defineStore } from 'pinia'
-import { useStorage } from '@vueuse/core'
-import { skipHydrate } from 'pinia'
-// const userInfoStore = useUserInfoStore()
-// const { userInfo } = storeToRefs(userInfoStore)
-// userInfoStore.getUserInfo()
 export const useChatStore = defineStore('chat', () => {
-  const startUrl = ref('wss://your-websocket-url')
+  const config = useRuntimeConfig()
+  const baseIM = config.public.baseIM
 
-  const message = ref(null)
+  const isConnect = ref(false)
+  // 连接状态 0: 未连接 1: 连接中 2: 已连接 3: 已断开
+  const connectSta = ref(0)
 
-  // WebSocket 服务的实例
-  const wsService = ref(null)
+  const receive = ref([])
+  const receiveGetter = computed(() => receive.value)
+  const onNewMessage = ref(Date.now())
 
-  // 使用 `useStorage` 来持久化 WebSocket 的连接状态
-  const isConnected = useStorage('isConnected', false)
+  // 当前会话
+  const curConversiton = ref({})
 
-  // 连接 WebSocket
-  const connect = (url) => {
-    if (wsService.value) {
-      // 如果 WebSocket 已连接,不需要重新连接
-      return
-    }
+  // 创建webboteSocket连接
+  const ws = ref(null)
+  function createConnection(token) {
+    return new Promise((resolve, reject) => {
+      if (connectSta.value == 2) {
+        console.log('连接已存在,请不要重复连接')
+        reject('连接已存在,请不要重复连接')
+        return
+      }
+      console.log('创建连接')
+      connectSta.value = 1
+      ws.value = new WebSocket(baseIM + '?token=' + token)
 
-    wsService.value = new WebSocket(`${startUrl.value}${url}`)
+      ws.value.onopen = () => {
+        console.log('聊天连接成功')
+        isConnect.value = true
+        connectSta.value = 2
+        resolve()
+      }
 
-    wsService.value.connect()
+      ws.value.onmessage = (e) => {
+        onNewMessage.value = Date.now() + '' + Math.random() * 10000
+        reqChatList()
+        try {
+          const messageBody = JSON.parse(e.data)
+          console.log('messageBody:', messageBody)
+          console.log('curConversiton:', curConversiton)
+          // 判断该条消息是否属于当前会话
+          if (messageBody.groupId == curConversiton.value.groupId) {
+            let isReceive = true // 判断该条消息是收到的还是发出的
 
-    // 当连接成功时
-    wsService.value.onopen = () => {
-      isConnected.value = true
-      console.log('WebSocket连接已打开')
-    }
+            for (let i = 0; i < receive.value.length; i++) {
+              if (receive.value[i]?.object?.id == messageBody?.object?.id) {
+                //如果是发出的消息,则设置消息的发送成功状态
+                messageBody.sendSuccess = true
+                receive.value[i] = messageBody
+                isReceive = false
+                break
+              }
+            }
 
-    // 当连接关闭时
-    wsService.value.onclose = () => {
-      isConnected.value = false
-      console.log('WebSocket连接已关闭')
-    }
-
-    // 监听错误事件
-    wsService.value.onerror = (error) => {
-      console.error('WebSocket错误:', error)
-      isConnected.value = false
-    }
+            // 如果是收到的消息,则将消息push到receive数组中
+            if (isReceive) {
+              receive.value.push(messageBody)
+            }
+          }
+        } catch (error) {
+          console.log('消息解析出错::', error)
+        }
+      }
 
-    // 监听消息
-    wsService.value.onMessage((message) => {
-      console.log('收到消息:', message)
+      ws.value.onclose = () => {
+        console.log('聊天连接已关闭')
+        isConnect.value = false
+        connectSta.value = 3
+      }
     })
   }
 
-  // 发送消息
-  const sendMessage = (message) => {
-    if (wsService.value && wsService.value.readyState === WebSocket.OPEN) {
-      wsService.value.sendMessage(message)
-    } else {
-      console.error('WebSocket未连接,无法发送消息')
-    }
-  }
+  // const curConversiton = computed(()=>conversiton.value)
 
-  // 断开 WebSocket 连接
-  const disconnect = () => {
-    if (wsService.value) {
-      wsService.value.close()
-      wsService.value = null
-      isConnected.value = false
-      console.log('WebSocket已关闭')
+  // 会话列表
+  const chatList = ref([])
+  const conversations = computed(() => chatList.value)
+  // 请求聊天会话列表
+  async function reqChatList() {
+    console.log('请求聊天会话列表')
+    const { data } = await request('/website/tourism/fans/getTourMemberList')
+    const { list } = data || {}
+    if (Array.isArray(list)) {
+      chatList.value = list
     }
+    console.log('会话列表:', data)
+    console.log('fuck:', receive.value)
   }
 
-  // 返回 Pinia store 中的数据和方法
+  const messages = ref('first message')
+
+  // 当前登录用户信息
+  const user = ref({})
+
   return {
-    isConnected: skipHydrate(isConnected), // 保证在服务器端渲染时不与客户端同步
-    wsService,
-    connect,
-    sendMessage,
-    disconnect
+    messages,
+    reqChatList,
+    createConnection,
+    ws,
+    conversations,
+    curConversiton,
+    receive,
+    receiveGetter,
+    user,
+    chatList,
+    isConnect,
+    connectSta,
+    onNewMessage
   }
 })