Browse Source

移动端调整

chenrong 11 tháng trước cách đây
mục cha
commit
88616f62a6
2 tập tin đã thay đổi với 900 bổ sung56 xóa
  1. 3 0
      src/main.js
  2. 897 56
      src/views/chat/ChatH5.vue

+ 3 - 0
src/main.js

@@ -32,6 +32,9 @@ import Icon from 'vue-awesome/components/Icon'
 
 Vue.component('v-icon', Icon)
 
+// import Button from 'vant/lib/button';
+// import 'vant/lib/button/style';
+
 // 分页组件
 import Pagination from "@/components/Pagination";
 // 自定义表格工具组件

+ 897 - 56
src/views/chat/ChatH5.vue

@@ -18,7 +18,7 @@
           
         </div>
       </div>
-      
+      <audio ref="audio" muted v-show="false" :src="audioUrl" autoplay="" @ended="audioEnd" controls></audio>
       <div class="chatContent"> 
         <!-- <div class="leftImg">
           <img :src="baseApi + info.picture" alt="">
@@ -95,23 +95,107 @@
 </template>
 
 <script>
-import { streamChatWithWebApi } from "@/api/chat.js"
-// import { Message, MessageBox, Notification, Loading } from 'element-ui'
+import {
+  streamChatWithWebApi,
+  getGuidanceApi,
+  getModelListApi,
+  addChatApi,
+  getChatCharacterRecordsApi,
+  getChatRecordApi,
+  updateTitleApi,
+  clearRecordApi,
+  queryVoiceListApi,
+  updateRecordApi,
+  deleteRecordApi
+} from "@/api/chat.js"
 import { detailApi } from "@/api/detail.js"
+import { queryUserBalanceApi } from "@/api/user.js"
+import { Message, MessageBox, Notification, Loading } from 'element-ui'
+import 'vue-awesome/icons/paper-plane'
+import 'vue-awesome/icons/fire'
+
 export default {
+  components: {
+  },
   data() {
     return {
+      // 聊天等待
+      chatLoading: false,
+      // 是否全屏
+      fullScreen: false,
+      // 角色所有聊天列表
+      allRecords: [],
+      // 聊天记录id
+      recordId: null,
+      // 选中的角色聊天记录
+      historyRes: [],
+      recordsIndex: null,
+      showDetail: true,
+      showConfig: false,
+      messageOptions: [],
       info: {},
       messageLoading: false,
       returnMessage: [],
-      content: ''
+      content: '',
+      audioPlayIndex: null,
+      configForm: {
+        radio1: null,
+        radio2: null,
+        radio3: null,
+      },
+      // 对话接口是否返回错误状态
+      resError: false,
+      // 模型列表
+      modelList: [],
+      setting: {
+        value1: false,
+        value2: false,
+      },
+      //音频相关↓
+      //音频地址
+      audioUrl: '',
+      audioUrlArr: [],
+      audioUrlArrIndx: 0,
+      videoLoop: null,
+      videoLoopTime: 0,
+      loopPlay: false,
+      //场景下拉菜单
+      dropdown3Show: false,
+      // 场景对话相关
+      sceneId: null,
+      sceneInfo: {},
     }
   },
-  mounted() {
-    if (this.$route.query.characterId) {
-      this.getDetail(this.$route.query.characterId)
+  computed: {
+    canChat() {
+      console.log(this.info, 'this.info');
+      if (!this.sceneId) {
+        if (this.info.isDelete == 1) {
+          console.log(1);
+          return false
+        } else {
+          console.log(2);
+          return true
+        }
+      } else {
+        if (this.sceneInfo.isDelete == 1) {
+          return false
+        } else {
+          return true
+        }
+      }
+    },
+    notChatSend() {
+      console.log(this.audioPlayIndex, 'this.audioPlayIndex>>>>>>>>>>>');
+      return this.chatLoading != false || this.audioPlayIndex != null
+    },
+    showNodata() {
+      return this.allRecords.length == 0 && !this.$route.query.characterId
     }
   },
+  mounted() {
+    this.init()
+  },
   watch: {
     returnMessage: {
       handler(newVal, lodVal) {
@@ -124,38 +208,556 @@ export default {
     }
   },
   methods: {
-    getDetail(id) {
-      detailApi(id).then(res => {
-        console.log(res, '角色详情');
-        this.info = res.data
-        let HistoryMessage = JSON.parse(localStorage.getItem(`[userId:${123},aiId:${this.info.id}]`));
-        if (HistoryMessage) {
-          this.returnMessage = HistoryMessage
-        } else {
-          this.returnMessage.push({
-            role: 'assistant',
-            content: this.info.firstContent
+    async init() {
+      // 获取模型列表
+      this.getModelList()
+      // 获取用户所有聊天记录
+      await this.getChatCharacterRecords()
+      // 如果用角色id获取角色详情
+      if (this.$route.query.characterId) {
+        if (this.$route.query.sceneId) {
+          this.sceneId = this.$route.query.sceneId
+        }
+        await this.getDetail(this.$route.query.characterId)
+      } else {
+        this.allRecords[0].open = true
+        await this.getDetail(this.allRecords[0].id)
+      }
+      // 查找当前角色是否有对话记录
+      this.searchHistory(this.info.id)
+    },
+    // 全屏
+    clickFullScreen() {
+      this.fullScreen = !this.fullScreen
+    },
+    // 点击聊天记录切换聊天
+    async clickDialogue(value1, value2, index) {
+      console.log(value2, 'value2');
+      let _this = this
+      this.audioUrl = ""
+      this.messageOptions = []
+      this.returnMessage = []
+      if (this.$route.query.characterId) {
+        this.$route.query.characterId = value1.id
+      }
+      if (!value2) {
+        return
+      }
+      // 如果点击的是场景聊天
+      if (value2.sceneId) {
+        this.sceneId = value2.sceneId
+        await this.getDetail(value1.id)
+        // 从角色详情中获取场景列表
+        let sceneList = this.info.sceneList
+        // 获取当前聊天对应的场景
+        for (let i = 0; i < sceneList.length; i++) {
+          const element = sceneList[i];
+          if (element.sceneId == value2.sceneId) {
+            _this.sceneInfo = element
+          }
+        }
+      } else {
+        this.sceneId = null
+        this.sceneInfo = {}
+        await this.getDetail(value1.id)
+      }
+
+      this.recordId = value2.id
+      this.getChatRecord(value2.id)
+      this.recordsIndex = index
+    },
+    // 场景下拉菜单
+    handleCommand3(value) {
+      if (value == 1) {
+      } else if (value == 2) {
+        // 情况聊天记录
+        this.returnMessage = []
+        // 新建场景对话
+        this.newStart()
+        // 增加开场白
+        this.returnMessage.push({
+          role: 'assistant',
+          content: this.sceneInfo.sceneWelcome
+        })
+      } else if (value == 3) {
+        // 回到常规对话
+        // 遍历当前聊天记录是否有常规对话
+        let messages = null
+        for (let i = 0; i < this.allRecords.length; i++) {
+          const element = this.allRecords[i];
+          if (element.id == this.info.id) {
+            messages = element
+          }
+        }
+        console.log(messages, 'messages');
+        let flag = false
+        for (let i = 0; i < messages.chatCharacterList.length; i++) {
+          const element = messages.chatCharacterList[i];
+          console.log(element, 'element');
+          if (!element.sceneId) {
+            flag = true
+            this.clickDialogue(messages, element, i)
+            break
+          }
+        }
+        // 如果聊天记录里没有常规对话,则新增一个常规对话
+        if (!flag) {
+          this.sceneId = null
+          this.sceneInfo = {}
+          this.newStart()
+        }
+      }
+    },
+    // 聊天记录列表-角色下拉菜单
+    handleCommand2(value, value1) {
+      if (value == 2) {
+        this.$confirm('此操作将永久删除该角色所有聊天记录, 是否继续?', '提示', {
+          confirmButtonText: '确定',
+          cancelButtonText: '取消',
+          type: 'warning'
+        }).then(() => {
+          this.clearRecord(value1)
+        })
+      }
+    },
+    // 聊天记录列表-角色-聊天记录下拉菜单
+    handleCommand(value, value1, value2) {
+      console.log(value, 'value');
+      if (value == 1) {
+        this.editDialogueTitle(value1, value2)
+      } else if (value == 2) {
+        this.$confirm('此操作将永久删除该聊天记录, 是否继续?', '提示', {
+          confirmButtonText: '确定',
+          cancelButtonText: '取消',
+          type: 'warning'
+        }).then(() => {
+          this.clearRecord(value1, value2)
+        })
+      }
+    },
+    // 聊天记录操作相关↓
+    handleCommand4(value1, value2, value3) {
+      console.log(value1, 'value1');
+      console.log(value2, 'value2');
+      if (value1 == 1) {
+        // 编辑
+        let height = this.$refs[`message${value3}`][0].offsetHeight
+        let width = this.$refs[`message${value3}`][0].offsetWidth
+        
+        value2.edit = true
+        this.$nextTick(() => {
+          this.$refs[`messageEditInput${value3}`][0].$el.children[0].style.height = height + 'px'
+          this.$refs[`messageEdit${value3}`][0].style.width = width + 'px'
+        })
+      } else if (value1 == 2) {
+        // 删除
+        this.$confirm('此操作将永久删除该聊天记录, 是否继续?', '提示', {
+          confirmButtonText: '确定',
+          cancelButtonText: '取消',
+          type: 'warning'
+        }).then(() => {
+          this.deleteRecord(value2, value3)
+        })
+      } else if (value1 == 3) {
+        // 重新生成最后一句对话
+        this.resetChat(value2, value3)
+      }
+    },
+    // 重新生成最后一条聊天记录
+    resetChat(value, index) {
+      let params = {
+        recordId: value.id,
+        role: value.role,
+      }
+      deleteRecordApi(params).then(res => {
+        this.returnMessage.splice(index, 1)
+        this.getStreamChatWithWeb()
+      })
+    },
+    // 编辑单条聊天记录-取消
+    editCancel(value, index) {
+      value.edit = false
+      value.editContent = value.content
+    },
+    // 编辑单条聊天记录-保存
+    editSave(value, index) {
+      console.log(value, 'value');
+      let params = {
+        content: value.editContent,
+        recordId: value.id,
+        role: value.role,
+      }
+      updateRecordApi(params).then(res => {
+        console.log(res, 'ressss');
+        value.edit = false
+        this.getChatRecord(this.recordId)
+      })
+      
+    },
+    // 删除单条聊天记录
+    deleteRecord(value, index) {
+      let params = {
+        recordId: value.id,
+        role: value.role,
+      }
+      deleteRecordApi(params).then(res => {
+        this.$message({
+          message: '删除成功',
+          type: 'success'
+        });
+        this.getChatRecord(this.recordId)
+      })
+    },
+    
+    // 聊天记录新增对话
+    async newStart_juese(value) {
+      console.log(value, 'value');
+      this.audioUrl = ""
+      this.sceneId = null
+      this.sceneInfo = {}
+      this.messageOptions = []
+      this.returnMessage = []
+      // 点击聊天记录切换聊天
+      if (this.$route.query.characterId) {
+        this.$route.query.characterId = value.id
+      }
+      await this.getDetail(value.id)
+      this.recordId = await this.addChat()
+      for (let i = 0; i < this.allRecords.length; i++) {
+        const element = this.allRecords[i];
+        if (element.id == this.info.id) {
+          element.chatCharacterList.push({
+            chatTitle: "常规聊天",
+            createTime: '',
+            id: this.recordId
           })
-          localStorage.setItem(`[userId:${123},aiId:${this.info.id}]`, JSON.stringify(this.returnMessage));
+          this.recordsIndex = element.chatCharacterList.length - 1
+        }
+      }
+    },
+    // 修改聊天记录标题
+    editDialogueTitle(value1, value2) {
+      this.$prompt('新标题名称', '修改标题', {
+        confirmButtonText: '确定',
+        cancelButtonText: '取消',
+      }).then(({ value }) => {
+        let params = {
+          chatTitle: value,
+          id: value2.id
         }
+        updateTitleApi(params).then(res => {
+          console.log(res, '修改标题');
+          this.$message({
+            type: 'success',
+            message: '修改成功!'
+          });
+          this.getChatCharacterRecords()
+        })
+      })
+    },
+    clearRecord(value1, value2) {
+      let params = {
+        characterId: value1.id,
+      }
+      if (value2) {
+        params.recordId = value2.id
+      }
+      clearRecordApi(params).then(res => {
+        this.$message({
+          type: 'success',
+          message: '删除成功!'
+        });
+        this.getChatCharacterRecords()
+      })
+    },
+    async getChatRecord(recordId) {
+      let params = {
+        characterId: this.info.id,
+        recordId: recordId
+      }
+      getChatRecordApi(params).then(res => {
+        console.log(res, '查询到的聊天记录');
+        let array = res.data
+        // this.returnMessage
+        this.historyRes = res.data
+        if (this.returnMessage.length > 1) {
+          this.returnMessage = this.returnMessage.splice(0, 1)
+        }
+        for (let i = 0; i < array.length; i++) {
+          const element = array[i];
+          let history = JSON.parse(element.history)
+          history.map(item => {
+            item.id = element.id
+            item.uuid = element.uuid
+            item.edit = false
+            item.editContent = item.content
+            if (item.role == 'assistant') {
+              item.voiceFilePosition = element.voiceFilePosition
+            }
+          })
+          this.returnMessage = [...this.returnMessage, ...history]
+        }
+        this.configForm.radio2 = this.modelList[0].id
+        this.modelList.map(item => {
+          if (item.id == array[array.length - 1].modelId) {
+            this.configForm.radio2 = item.id
+          }
+        })
+      })
+    },
+    searchHistory(characterId) {
+      // 查看对话记录是否有选中的角色
+      // console.log('查看对话记录是否有选中的角色');
+      let flg = false
+      for (let i = 0; i < this.allRecords.length; i++) {
+        const element = this.allRecords[i];
+        // 如果有则选中角色的最新一条记录并获取对话聊天记录
+        if (element.id == characterId) {
+          console.log(element, '查看对话记录是否有选中的角色');
+          flg = true
+          element.open = true
+          // 二级对话判断当前是普通对话还是场景对话
+          // 取对应的最后一条消息记录
+          let chatCharacterList = element.chatCharacterList
+          let chatCharacter = null
+          let index = null
+          for (let i = 0; i < chatCharacterList.length; i++) {
+            const element2 = chatCharacterList[i];
+            if (this.$route.query.sceneId == element2.sceneId) {
+              chatCharacter = element2
+              index = i
+              break;
+            } else if (!this.$route.query.sceneId && !element2.sceneId) {
+              chatCharacter = element2
+              index = i
+              break;
+            }
+          }
+          // 如果有聊天记录则点击
+          if (chatCharacter) {
+            this.clickDialogue(element, chatCharacter, index)
+          } else {
+            // 如果没有场景聊天记录则新增场景聊天
+            // 从角色详情中获取场景列表
+            let sceneList = this.info.sceneList
+            // 获取当前聊天对应的场景
+            for (let i = 0; i < sceneList.length; i++) {
+              const element = sceneList[i];
+              if (element.sceneId == this.$route.query.sceneId) {
+                this.sceneInfo = element
+              }
+            }
+          }
+          // this.recordsIndex = element.chatCharacterList.length - 1
+          // let recordId = element.chatCharacterList[element.chatCharacterList.length - 1].id
+          // this.recordId = recordId
+          // this.getChatRecord(recordId)
+        }
+      }
+      // 如果没有聊天记录,则增加开场聊天引导
+      if (!flg) {
+        this.getGuidance(this.info.id)
+      }
+    },
+    async getChatCharacterRecords() {
+      let res = await getChatCharacterRecordsApi()
+      console.log(res, '聊天记录');
+      if (res.data) {
+        for (let i = 0; i < res.data.length; i++) {
+          const element = res.data[i];
+          if(this.info.id == element.id) {
+            element.open = true
+          } else {
+            element.open = false
+          }
+        }
+        this.allRecords = res.data
+      }
+    },
+    // 新增对话记录
+    async addChat() {
+      let params = {
+        characterId: this.info.id,
+        chatTitle: ""
+      }
+      if (this.sceneId) {
+        params.sceneId = this.sceneId
+      }
+      let res = await addChatApi(params)
+      console.log(res, '新增对话记录');
+      return res.data
+    },
+    getModelList() {
+      getModelListApi().then(res => {
+        console.log(res, '模型列表');
+        this.modelList = res.data
+      })
+    },
+    inputBoxClick() {
+      this.$refs.input.focus()
+    },
+    async getDetail(id) {
+      let res = await detailApi(id)
+      console.log(res, '角色详情');
+      this.info = res.data
+      this.configForm.radio2 = this.info.modelId
+      // let HistoryMessage = JSON.parse(localStorage.getItem(`[userId:${123},aiId:${this.info.id}]`));
+      // if (HistoryMessage) {
+      //   this.returnMessage = HistoryMessage
+      // } else {
+      //   this.returnMessage.push({
+      //     role: 'assistant',
+      //     content: this.info.firstContent
+      //   })
+      //   localStorage.setItem(`[userId:${123},aiId:${this.info.id}]`, JSON.stringify(this.returnMessage));
+      // }
+      if (this.sceneId) {
+        console.log(this.sceneId);
+        let sceneList = this.info.sceneList
+        for (let i = 0; i < sceneList.length; i++) {
+          const element = sceneList[i];
+          if (element.sceneId == this.sceneId) {
+            this.sceneInfo = element
+            this.configForm.radio2 = element.modelId
+            this.returnMessage.push({
+              role: 'assistant',
+              content: element.sceneWelcome
+            })
+          }
+        }
+      } else {
+        this.returnMessage.push({
+          role: 'assistant',
+          content: this.info.firstContent
+        })
+      }
+    },
+    getGuidance(id) {
+      getGuidanceApi(id).then(res => {
+        console.log(res, '聊天引导');
+        this.messageOptions = res.data
       })
     },
     goBack() {
       this.$router.back()
     },
-    newStart() {
-      // 清空历史数据
-      localStorage.removeItem(`[userId:${123},aiId:${this.info.id}]`);
+    async newStart() {
+      // 新业务,创建一个新的对话记录
+      this.recordId = await this.addChat()
+      for (let i = 0; i < this.allRecords.length; i++) {
+        const element = this.allRecords[i];
+        if (element.id == this.info.id) {
+          if (this.sceneId) {
+            element.chatCharacterList.push({
+              chatTitle: "场景聊天",
+              createTime: '',
+              id: this.recordId,
+              sceneIcon: true
+            })
+          } else {
+            element.chatCharacterList.push({
+              chatTitle: "常规聊天",
+              createTime: '',
+              id: this.recordId
+            })
+          }
+          this.recordsIndex = element.chatCharacterList.length - 1
+        }
+      }
+
       this.returnMessage = []
       this.getDetail(this.info.id)
+      // 废弃》》
+      // 清空历史数据
+      // localStorage.removeItem(`[userId:${123},aiId:${this.info.id}]`);
+      // this.returnMessage = []
+      // this.getDetail(this.info.id)
     },
     Enterkey(e) {
       if (e.keyCode == 13) {
+        console.log(this.notChatSend, 'this.notChatSend');
+        if (this.notChatSend) {
+          return
+        }
+        if (!this.content) {
+          return
+        }
         this.getStreamChatWithWeb()
       }
     },
+    // 前往创建场景
+    toCreateScene() {
+      this.$router.push({
+        name: 'CreateScene',
+        query: {
+          characterId: this.info.id,
+        }
+      })
+    },
+    async getStreamChatWithWeb_old() {
+      this.messageLoading = true
+      if (!this.content) {
+        return
+      }
+      this.returnMessage.push({
+        role: 'user',
+        content: this.content
+      })
+      let HistoryMessage = JSON.parse(localStorage.getItem(`[userId:${123},aiId:${this.info.id}]`));
+      // 历史记录取最新的20条传给后端
+      if (HistoryMessage && HistoryMessage.length > 20) {
+        HistoryMessage = HistoryMessage.slice(HistoryMessage.length - 1, 20)
+      }
+      let params = {
+        historyMessage: HistoryMessage || [],
+        characterId: this.info.id,
+        prompt: JSON.parse(JSON.stringify(this.content))
+      }
+      // 清空输入框的值
+      this.content = ''
+      // 新增一条ai信息
+      this.returnMessage.push({
+        role: 'assistant',
+        content: ''
+      })
+      let res = await streamChatWithWebApi(params)
+      console.log(res.data.message.content, 'res');
+      let content = res.data.message.content
+      let index = 0
+      let xing = 1
+      let messageInterval = setInterval(() => {
+        if (index > content.length - 1) {
+          console.log('结束');
+          // 消息全部显示后存到历史localStorage
+          let HistoryMessage = []
+          // 历史只存100条,长度超出截取最新的
+          if (this.returnMessage.length > 100) {
+            HistoryMessage = JSON.stringify(this.returnMessage.slice(this.returnMessage.length - 100, 100))
+          } else {
+            HistoryMessage = JSON.stringify(this.returnMessage)
+          }
+          localStorage.setItem(`[userId:${123},aiId:${this.info.id}]`, HistoryMessage);
+
+          clearInterval(messageInterval)
+          return
+        }
+        console.log(content[index], 'content[index]');
+        if (content[index] == "*") {
+          if (xing == 1) {
+            xing = 2
+            this.returnMessage[this.returnMessage.length - 1].content += "("
+          } else if (xing == 2) {
+            xing = 1
+            this.returnMessage[this.returnMessage.length - 1].content += ")"
+          }
+        } else {
+          this.returnMessage[this.returnMessage.length - 1].content += content[index]
+        }
+        index += 1
+      }, 50)
+    },
     async getStreamChatWithWeb() {
-      this.audioUrlArr = []
+      this.audioUrl = []
       this.audioUrlArrIndx = 0
       this.textCache = ''
       this.resError = false
@@ -204,8 +806,10 @@ export default {
         content: '',
         voiceFilePosition: '',
       })
+
       // 清空输入框的值
       this.content = ''
+
       let res = await streamChatWithWebApi(params)
       console.log(res, 'res');
       this.messageLoading = false
@@ -224,6 +828,10 @@ export default {
         if(done){
           console.log(value, '结束value');
           this.chatLoading = false
+          // if (typeof(value) == "undefined") {
+          //   this.$message.error('错误')
+          //   this.returnMessage.splice(this.returnMessage.length - 1, 1)
+          // }
           // 每次对话完刷新聊天记录
           this.getChatCharacterRecords()
           let params = {
@@ -233,6 +841,10 @@ export default {
           let historyRes = await getChatRecordApi(params)
           this.historyRes = historyRes.data
           // 如果开启自动播放,则查询并播放语音
+          // this.audioUrl = ""
+          // if (!this.resError) {
+          
+          // }
           console.log('结束');
           break;
         }
@@ -241,65 +853,294 @@ export default {
         const txt = decoder.decode(value).split('data:')
         // const txt = decoder.decode(value)
         this.addMessage(txt)
+        // let data = JSON.parse(txt).message.content
+        // console.log(txt, 'txt');
+        // if (this.isJSON(txt) && JSON.parse(txt).code != 200) {
+        //   let data = JSON.parse(txt)
+        //   this.$message.error(data.msg)
+        //   this.returnMessage.splice(this.returnMessage.length - 1, 1)
+        //   break;
+        // }
       }
     },
     addMessage(value) {
+      // console.log(value, 'value');
       for (let i = 0; i < value.length; i++) {
         const element = value[i];
+        
         if (this.isJSON(element)) {
-          if(JSON.parse(element).code == 401) {
+          let value = JSON.parse(element)
+          if(value.code == 401) {
             this.returnMessage.splice(this.returnMessage.length - 1, 1)
             this.noLogin(element)
+            this.chatLoading = false
             break;
           }
-          if(JSON.parse(element).code == 500) {
-            this.returnMessage.splice(this.returnMessage.length - 1, 1)
-            this.$message.error('系统错误请联系管理员')
+          if(value.code == 500) {
+            console.log(value, 'JSON.parse(element)');
+            this.returnMessage.splice(this.returnMessage.length - 2, 2)
+            this.$message.error(value.content || '系统错误请联系管理员')
+            this.resError = true
+            this.chatLoading = false
+            break;
+          }
+          // 获取语音id
+          if (value.code == -1) {
+            this.returnMessage[this.returnMessage.length - 1].uuid = value.content
+            // 如果开启了自动播放开始轮巡查询语音
+            if (this.setting.value1) {
+              this.audioUrlArrIndx = 0
+              this.videoLoopTime = 0
+              this.audioUrlArr = []
+              this.loopPlay = false
+              this.audioPlayIndex = this.returnMessage.length - 1
+              this.loopGetVoice(value.content, this.returnMessage.length - 1)
+            }
             break;
           }
-          let txt = JSON.parse(element).content
-          this.returnMessage[this.returnMessage.length - 1].content += txt
+          if (!value.done) {
+            let txt = value.content
+            this.returnMessage[this.returnMessage.length - 1].content += txt
+          } else {
+            // 对话流结束
+            // 临时插入的ai对话记录和用户记录插入聊天id
+            this.returnMessage[this.returnMessage.length - 1].id = value.content
+            this.returnMessage[this.returnMessage.length - 2].id = value.content
+          }
         }
       }
     },
     noLogin(value) {
-      this.$message.error(value.content)
-      this.$store.dispatch("LogOut").then(() => {
-        this.$router.push({ path: "/loginH5" });
+      let _this = this
+      MessageBox.confirm(
+        value.content,
+        "系统提示",
+        {
+          confirmButtonText: "前往登录",
+          cancelButtonText: "取消",
+          type: "warning",
+        }
+      )
+      .then(() => {
+        // isRelogin.show = false;
+        this.$store.dispatch("LogOut").then(() => {
+          // location.href = "/";
+
+          _this.$refs.Header.showLogin()
+        });
+      })
+      .catch(() => {
+        // isRelogin.show = false;
       });
-      // let _this = this
-      // MessageBox.confirm(
-      //   value.content,
-      //   "系统提示",
-      //   {
-      //     confirmButtonText: "前往登录",
-      //     cancelButtonText: "取消",
-      //     type: "warning",
-      //   }
-      // )
-      // .then(() => {
-      //   // isRelogin.show = false;
-        
-      // })
-      // .catch(() => {
-      //   // isRelogin.show = false;
-      // });
     },
     isJSON(str) {
       if (typeof str == 'string') {
-          try {
-              JSON.parse(str);
-              return true;
-          } catch(e) {
-              // console.log(e);
-              return false;
+        try {
+          JSON.parse(str);
+          return true;
+        } catch(e) {
+          // console.log(e);
+          return false;
+        }
+      }
+    },
+    messageOptionClick(value) {
+      this.content = value
+      this.getStreamChatWithWeb()
+    },
+    // 播放聊天语音
+    initAudio(index) {
+      // 从聊天记录获取id
+      console.log(this.returnMessage[index], 'swssssssss');
+      let id = this.returnMessage[index].id
+      let history = this.historyRes.map((item) => {
+        if (item.id == id) {
+          return item
+        }
+      })
+      console.log(history, 'history');
+      return
+
+      this.loopGetVoice(history.id, index)
+    },
+    playAudio(index) {
+      if (index) {
+        this.audioPlayIndex = index
+      }
+      // this.audioUrlArrIndx = 0
+      console.log(this.audioUrlArrIndx, 'this.audioUrlArrIndx');
+      console.log(this.audioUrlArr, 'this.audioUrlArr');
+      // console.log(audioUrlArr[this.audioUrlArrIndx].voiceAddress, 'audioUrlArr[this.audioUrlArrIndx].voiceAddress');
+      // 如果当前播放的语音地址为空,则等待2秒后重新获取
+      if (!this.audioUrlArr[this.audioUrlArrIndx].voiceAddress && this.videoLoopTime <= 50) {
+        setTimeout(() => {
+          this.playAudio(index)
+        }, 2000)
+        return
+      }
+      // 如果当前播放的语音地址为false,则跳过当前语音
+      if (this.audioUrlArr[this.audioUrlArrIndx].voiceAddress == 'false' && this.audioUrlArrIndx < this.audioUrlArr.length - 1) {
+        this.audioUrlArrIndx += 1
+        this.playAudio(index)
+        return
+      } else if (this.audioUrlArrIndx > this.audioUrlArr.length - 1) {
+        this.audioUrl = ''
+        this.audioUrlArrIndx = 0
+        this.videoLoopTime = 0
+        this.audioUrlArr = []
+        return
+      }
+      this.audioUrl = this.audioUrlArr[this.audioUrlArrIndx].voiceAddress
+      console.log(this.audioUrl, 'this.audioUrl');
+      setTimeout(() => {
+        
+        if (this.audioUrl) {
+          this.$refs.audio.play()
+        }
+      }, 1000)
+    },
+    async historyGetVoice(value, index) {
+      console.log(value, 'value');
+      if (!value.uuid) {
+        return
+      }
+      let params = {
+        uuid: value.uuid
+      }
+      let fileRes = await queryVoiceListApi(params)
+      console.log(fileRes.data, 'file>>>');
+      this.audioUrlArr = fileRes.data.voices
+      this.audioUrlArrIndx = 0
+      this.videoLoopTime = 0
+      this.loopPlay = false
+      this.playAudio(index)
+    },
+    async loopGetVoice(id, index) {
+      this.videoLoopTime += 1
+      // 获取语音文件
+      let params = {
+        uuid: id
+      }
+      let fileRes = await queryVoiceListApi(params)
+      console.log(fileRes.data, 'file>>>');
+      let voices = fileRes.data.voices
+      let _continue = fileRes.data.continue
+      this.apiHaveVideo = _continue
+      // 判断语音文件是否获取完毕
+      let trueLength = 0
+      for (let i = 0; i < voices.length; i++) {
+        const element = voices[i];
+        if (element.voiceAddress) {
+          trueLength += 1
+        }
+      }
+      if (!_continue && trueLength == voices.length) {
+        if (this.videoLoop) {
+          clearTimeout(this.videoLoop)
+          this.videoLoop = null
+        }
+        // this.returnMessage[index].voiceFilePosition = fileRes.data.voiceFilePosition
+        // 有语音文件则开始播放
+        if (voices.length > 0) {
+          this.audioUrlArr = voices
+          console.log(this.audioUrlArr, '进入播放流程1');
+          if (this.$refs.audio.paused || this.audioUrlArrIndx > this.audioUrlArr.length - 1) {
+            if (this.loopPlay == false) {
+              this.playAudio(index)
+              this.loopPlay = true
+            }
+          }
+        }
+      } else {
+        if (voices.length > 0) {
+          this.audioUrlArr = voices
+          console.log(this.audioUrlArr, '进入播放流程2');
+          if (this.$refs.audio.paused || this.audioUrlArrIndx > this.audioUrlArr.length - 1) {
+            if (this.loopPlay == false) {
+              this.playAudio(index)
+              this.loopPlay = true
+            }
           }
+        }
+        // 没有语音文件则开启定时器每两秒查询一次
+        if (this.videoLoopTime > 50) {
+          // 如果调用次数超过30次则停止
+          return
+        }
+        this.videoLoop = setTimeout(() => {
+          this.loopGetVoice(id, index)
+        }, 2000)
       }
     },
+    audioEnd() {
+      this.audioUrlArrIndx += 1
+      console.log(this.audioUrlArrIndx, 'audioUrlArrIndx');
+      if (this.audioUrlArrIndx < this.audioUrlArr.length && this.videoLoopTime <= 50) {
+        // 如果当前播放的语音地址为空,则等待2秒后重新获取
+        if (!this.audioUrlArr[this.audioUrlArrIndx].voiceAddress) {
+          setTimeout(() => {
+            this.playAudio()
+          }, 2000)
+          return
+        }
+        // 如果当前播放的语音地址为false,则跳过当前语音
+        if (this.audioUrlArr[this.audioUrlArrIndx].voiceAddress == 'false' && this.audioUrlArrIndx < this.audioUrlArr.length - 1) {
+          this.audioUrlArrIndx += 1
+          this.playAudio()
+          return
+        }
+        this.audioUrl = this.audioUrlArr[this.audioUrlArrIndx].voiceAddress
+        setTimeout(() => {
+          if (this.audioUrl) {
+            this.$refs.audio.play()
+          }
+        }, 100)
+      } else {
+        this.audioUrlArrIndx = []
+        this.audioUrlArrIndx = 0
+        console.log('播放结束');
+        this.audioPlayIndex = null
+      }
+    },
+    ChangeSettingValue1(value) {
+      console.log(value, 'value');
+      if (value) {
+        queryUserBalanceApi().then(res => {
+          console.log(res, '用户余额');
+          if (res.data <= 0 ) {
+            this.setting.value1 = false
+            this.$message({
+              message: '余额不足,无法开启次功能',
+              type: 'error'
+            });
+          }
+        })
+      }
+    },
+    // 场景业务相关↓
+    async sceneChange(item) {
+      console.log(item, 'item');
+      this.$message({
+        message: `已进入场景${item.sceneName}`,
+        type: 'success'
+      });
+      // 当用户选中场景
+      this.sceneInfo = item
+      // 切换当前场景id
+      this.sceneId = item.sceneId
+      // 情况聊天记录
+      this.returnMessage = []
+      // 新建场景对话
+      this.newStart()
+      // 增加开场白
+      // this.returnMessage.push({
+      //   role: 'assistant',
+      //   content: item.sceneWelcome
+      // })
+    }
   }
 }
 </script>
-
 <style lang="scss" scoped>
 
 .chat {