vue3+elementPlus pc和小程序ai聊天文生图

websocket封装可以看上一篇文章
在这里插入图片描述

//pc端
<template>
  <div class="common-layout theme-white">
    <el-container>
      <el-aside>
        <div class="title-box">
          <span>AI Chat</span>
        </div>
        <div class="chat-list">
          <!-- <div class="search-box">
            <el-input v-model="chatName" class="w-50 m-2" size="small" placeholder="搜索会话" @keyup="searchChat">
              <template #prefix>
                <el-icon class="el-input__icon">
                  <Search />
                </el-icon>
              </template>
            </el-input>
          </div> -->

          <div class="content" :style="{ height: leftBoxHeight + 'px' }">
            <el-row v-for="chat in chatList" :key="chat.chat_id">
              <div :class="chat.chat_id === activeChat.chat_id ? 'chat-list-item active' : 'chat-list-item'"
                @click="changeChat(chat)">
                <el-image :src="chat.icon" class="avatar" />
                <span class="chat-title-input" v-if="chat.edit">
                  <el-input v-model="tmpChatTitle" size="small" @keydown="titleKeydown($event, chat)"
                    placeholder="请输入会话标题" />
                </span>
                <span v-else class="chat-title">{{ chat.title }}</span>
                <span class="btn btn-check" v-if="chat.edit || chat.removing">
                  <el-icon @click="confirm($event, chat)">
                    <Check />
                  </el-icon>
                  <el-icon @click="cancel($event, chat)">
                    <Close />
                  </el-icon>
                </span>
                <span class="btn" v-else>
                  <el-icon title="编辑" @click="editChatTitle($event, chat)">
                    <Edit />
                  </el-icon>
                  <el-icon title="删除会话" @click="removeChat($event, chat)">
                    <Delete />
                  </el-icon>
                </span>
              </div>
            </el-row>
          </div>
        </div>

        <div class="tool-box">
          <el-dropdown :hide-on-click="true" class="user-info" trigger="click">
            <span class="el-dropdown-link">
              <el-image src="/images/logo.png" />
              <span class="username">{{ phoneNumber }}</span>
              <el-icon>
                <ArrowDown />
              </el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu style="width: 296px;">
                <el-dropdown-item @click="showConfig">
                  <el-icon>
                    <Tools />
                  </el-icon>
                  <span>修改密码</span>
                </el-dropdown-item>

                <!-- <el-dropdown-item @click="clearAllChats">
                  <el-icon>
                    <Delete />
                  </el-icon>
                  <span>清除所有会话</span>
                </el-dropdown-item> -->

                <el-dropdown-item @click="logout">
                  <i class="iconfont icon-logout"></i>
                  <span>注销</span>
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </el-aside>
      <el-main v-loading="loading" element-loading-background="rgba(122, 122, 122, 0.3)"
        element-loading-text="正在生成...">
        <div class="chat-head">
          <div class="chat-config">
            <span class="role-select-label">选择类型:</span>
            <el-select v-model="roleId" filterable placeholder="类型" class="role-select" @change="newChat">
              <el-option v-for="item in roles" :key="item.id" :label="item.name" :value="item.id">
                <div class="role-option">
                  <el-image :src="item.icon"></el-image>
                  <span>{{ item.name }}</span>
                </div>
              </el-option>
            </el-select>
            <!-- <el-select v-model="modelID" placeholder="模型" @change="newChat">
              <el-option v-for="item in models" :key="item.id" :label="item.name" :value="item.id" />
            </el-select> -->
            <el-button type="primary" @click="newChat">
              <el-icon>
                <Plus />
              </el-icon>
              新建对话
            </el-button>

            <!-- <el-button type="success" @click="exportChat" plain>
              <i class="iconfont icon-export"></i>
              <span>导出会话</span>
            </el-button> -->

            <!-- <el-button type="warning" @click="showFeedbackDialog = true">
              <el-icon>
                <Promotion />
              </el-icon>
              <span>意见反馈</span>
            </el-button> -->
          </div>
        </div>

        <div class="right-box" :style="{ height: mainWinHeight + 'px' }">
          <div>
            <div id="container">
              <div class="chat-box" id="chat-box" :style="{ height: chatBoxHeight + 'px' }">
                <!-- <div v-if="showHello"> -->
                <!-- <welcome @send="autofillPrompt" /> -->
                <!-- </div> -->
                <div v-for="item in chatData" :key="item.id">
                  <chat-prompt v-if="item.type === 'prompt'" :icon="item.icon"
                    :created-at="dateFormat(item['created_at'])" :tokens="item['tokens']" :model="getModelValue(modelID)"
                    :content="item.content" />
                  <chat-reply v-else-if="item.type === 'reply'" :icon="item.icon" :org-content="item.orgContent"
                    :created-at="dateFormat(item['created_at'])" :tokens="item['tokens']" :content="item.content" />
                  <chat-mid-journey v-else-if="item.type === 'mj'" :content="item.content" :role-id="item.role_id"
                    :chat-id="item.chat_id" :icon="item.icon" @disable-input="disableInput(true)"
                    @enable-input="enableInput" :created-at="dateFormat(item['created_at'])" />
                </div>
              </div>

              <div class="re-generate">
                <div class="btn-box">
                  <el-button type="info" v-if="showStopGenerate" @click="stopGenerate" plain>
                    <el-icon>
                      <VideoPause />
                    </el-icon>
                    停止生成
                  </el-button>

                  <el-button type="primary" v-if="showReGenerate" @click="reGenerate" plain>
                    <el-icon>
                      <RefreshRight />
                    </el-icon>
                    重新生成
                  </el-button>
                </div>
              </div>

              <div class="input-box">
                <div class="input-container">
                  <el-input ref="textInput" v-model="prompt" v-on:keydown="inputKeyDown" autofocus type="textarea"
                    :rows="2" placeholder="按 Enter 键发送消息,使用 Ctrl + Enter 换行" />
                  <!-- <span class="send-btn" style="right: 50px;">
                    <el-button @click="sendImage">
                      <el-icon>
                        <PictureFilled />
                      </el-icon>
                    </el-button>
                  </span> -->
                  <span class="send-btn">
                    <el-button @click="sendMessage">
                      <el-icon>
                        <Promotion />
                      </el-icon>
                    </el-button>
                  </span>
                </div>
              </div><!-- end input box -->

            </div><!-- end container -->
          </div><!-- end loading -->
        </div>
      </el-main>
    </el-container>




    <!--账户信息 -->
    <PasswordDialog :show="showConfigDialog" @hide="showConfigDialog = false" />
    <!-- 上传图片 -->
    <el-dialog class="config-dialog" v-model="showimgUpload" :close-on-click-modal="true" :before-close="close"
      style="width:60%" title="上传图片">
      <el-upload class="avatar-uploader" :auto-upload="true" :before-upload="beforeUpload" :show-file-list="false"
        :http-request="afterRead" accept="image/png, image/jpeg,image/jpg">
        <img v-if="imageUrl" :src="imageUrl" class="avatar" />
        <el-icon v-else class="avatar-uploader-icon">
          <Plus />
        </el-icon>
      </el-upload>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="handleConfirm">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

  </div>
</template>
<script setup>
import { nextTick, onMounted, ref } from 'vue'
import ChatPrompt from "@/components/ChatPrompt.vue";
import ChatReply from "@/components/ChatReply.vue";
import {
  ArrowDown,
  Check,
  Close,
  Delete,
  Edit,
  Plus,
  Promotion,
  RefreshRight,
  Search,
  Tools,
  VideoPause,
  PictureFilled
} from '@element-plus/icons-vue'
import 'highlight.js/styles/a11y-dark.css'
import { dateFormat, isMobile, randString, removeArrayItem, UUID } from "@/utils/libs";
import { ElMessage, ElMessageBox } from "element-plus";
import hl from "highlight.js";
import { getSessionId, getUserToken, removeUserToken } from "@/store/session";
import { httpGet, httpPost } from "@/utils/http";
import { useRouter } from "vue-router";
import Clipboard from "clipboard";
import PasswordDialog from "@/components/PasswordDialog.vue";
import imgUpload from "@/components/imgUpload.vue";
import { checkSession } from "@/action/session";
import Welcome from "@/components/Welcome.vue";
import ChatMidJourney from "@/components/ChatMidJourney.vue";
import { createWebscoket, onSend, closeWs, start, onMessage } from '@/utils/socket.js'
import { chineseChar2englishChar } from "@/utils/validate";
import Compressor from "compressorjs";

const title = ref('ChatGPT-智能助手');
const models = ref([])
const modelID = ref(0)
const chatData = ref([]);
const allChats = ref([]); // 会话列表
const chatList = ref(allChats.value);
const activeChat = ref({});
const mainWinHeight = ref(0); // 主窗口高度
const chatBoxHeight = ref(0); // 聊天内容框高度
const leftBoxHeight = ref(0);
const loading = ref(false);
const loginUser = ref(null);
const roles = ref([{
  "id": 1,
  "created_at": 0,
  "updated_at": 0,
  "key": "gpt",
  "name": "文生图",
  "context": null,
  "hello_msg": "您好,我是您的AI智能助手,我会尽力回答您的问题或提供有用的建议。",
  "icon": "/images/avatar/gpt.png",
  "enable": true,
  "sort": 1
}]);
const roleId = ref(1)
const newChatItem = ref(null);
const router = useRouter();
const showConfigDialog = ref(false);
const showimgUpload = ref(false);
const isLogin = ref(false)
const showHello = ref(true)
const textInput = ref(null)
const showFeedbackDialog = ref(false)
const showDemoNotice = ref(false)
const showNoticeKey = ref("SHOW_DEMO_NOTICE_")
const socketMsg = ref(null)
const imageUrl = ref(null)
const token = ref("")
const openId = ref("")
const phoneNumber = ref('')
const password = ref('')
if (isMobile()) {
  router.replace("/mobile")
}

onMounted(() => {
  resizeElement();
  token.value = localStorage.getItem('token')
  openId.value = localStorage.getItem('openId')
  phoneNumber.value = localStorage.getItem('phoneNumber')
  password.value = localStorage.getItem('password')
  models.value = {
    phoneNumber: phoneNumber.value,
    password: password.value
  }


  const clipboard = new Clipboard('.copy-reply, .copy-code-btn');
  clipboard.on('success', () => {
    ElMessage.success('复制成功!');
  })

  clipboard.on('error', () => {
    ElMessage.error('复制失败!');
  })
  if (token.value) {
    let host = process.env.VUE_APP_WS_HOST
    createWebscoket(host + token.value, messagesCallBack)
    chatData.value = []; // 初始化聊天数据
    previousText.value = '';//上一次提问
    enableInput()
    activelyClose.value = false;//主动关闭
    chatData.value.push({
      content: '您好,我是您的AI智能助手,我会尽力回答您的问题或提供有用的建议。',
      type: "reply",
      id: randString(32),
      icon: '/images/logo.png',
      orgContent: '您好,我是您的AI智能助手,我会尽力回答您的问题或提供有用的建议。',
    })
    window.onresize = () => resizeElement();
  } else {
    router.push('/login')
  }

});
const getRoleById = function (rid) {
  for (let i = 0; i < roles.value.length; i++) {
    if (roles.value[i]['id'] === rid) {
      return roles.value[i];
    }
  }
  return null;
}
//新消息监听
const messagesCallBack = (msg) => {
  let socketMsg = msg.msg.replace(/\ufeff/g, "");
  let socketMsgTwo = JSON.parse(socketMsg)
  if (socketMsgTwo.msgType != -1 || socketMsgTwo.msgType == 200) {
    loading.value = true
    if (socketMsgTwo.contentUrl) {
      chatData.value.push({
        type: "mj",
        key: randString(32),
        icon: '/images/logo.png',
        content: socketMsgTwo.contentUrl
      })
      loading.value = false
    }
    // 将聊天框的滚动条滑动到最底部
    nextTick(() => {
      document.getElementById('chat-box').scrollTo(0, document.getElementById('chat-box').scrollHeight)
    })
    enableInput()
  }
}
//发送socket消息到服务器
const sendMessagext = (data) => {
  onSend(JSON.stringify(data))
}
//断开socket
const closeWsTxt = () => {
  closeWs()
}



const prompt = ref('');
const showStopGenerate = ref(false); // 停止生成
const showReGenerate = ref(false); // 重新生成
const previousText = ref(''); // 上一次提问
const lineBuffer = ref(''); // 输出缓冲行
const activelyClose = ref(false); // 主动关闭
const canSend = ref(true);


// 发送消息
const sendMessage = function () {
  console.log(prompt.value)
  start()
  if (canSend.value === false) {
    ElMessage.warning("AI 正在作答中,请稍后...");
    return
  }
  if (prompt.value.trim().length === 0 || canSend.value === false) {
    return false;
  }else{
    loading.value = true
  }
  // 追加消息
  chatData.value.push({
    content: md.render(prompt.value),
    type: "prompt",
    id: randString(32),
    icon: '',
    created_at: new Date().getTime(),
  });

  nextTick(() => {
    document.getElementById('chat-box').scrollTo(0, document.getElementById('chat-box').scrollHeight)
  })

  showHello.value = false
  disableInput(false)
  // socket.value.send(prompt.value);
  var data = {
    userId: openId.value,
    toUserId: openId.value,
    content: chineseChar2englishChar(prompt.value),
    msgType: 2
  }
  //websocket 发送
  sendMessagext(data)
  previousText.value = prompt.value;//上一次tiwen
  prompt.value = '';
  return true;
}


//发送图片
const sendImage = function () {
  showimgUpload.value = true
}
//上传前
const beforeUpload = (file) => {
  if (file.type.indexOf("image") < 0) {
    ElMessage.error('请上传正确的图片格式')
    return false;
  }
};
//上传后
const afterRead = (file) => {
  // 压缩图片并上传
  new Compressor(file.file, {
    quality: 0.6,
    success(result) {
      const formData = new FormData();
      formData.append('file', result, result.name);
      // 执行上传操作
      httpPost('/api/upload', formData).then((res) => {
        user.value.avatar = res.data
        ElMessage.success({ message: "上传成功", duration: 500 })
      }).catch((e) => {
        ElMessage.error('图片上传失败:' + e.message)
      })
    },
    error(err) {
      console.log(err.message);
    },
  });
};
//图片确定
const handleConfirm = () => {
  showimgUpload.value = false
}
const resizeElement = function () {
  chatBoxHeight.value = window.innerHeight - 51 - 82 - 38;
  mainWinHeight.value = window.innerHeight - 51;
  leftBoxHeight.value = window.innerHeight - 43 - 47 - 45;
};

// 新建会话
const newChat = function () {
  // 获取当前聊天角色图标
  let icon = '';
  roles.value.forEach(item => {
    if (item['id'] === roleId.value) {
      icon = item['icon']
    }
  })
  newChatItem.value = {
    chat_id: "",
    icon: icon,
    role_id: roleId.value,
    model_id: modelID.value,
    title: '',
    edit: false,
    removing: false,
  };
  activeChat.value = {} //取消激活的会话高亮
  showStopGenerate.value = false;
  showReGenerate.value = false;
  connect(null, roleId.value)
}


const titleKeydown = (e, chat) => {
  if (e.keyCode === 13) {
    e.stopPropagation();
    confirm(e, chat)
  }
}


const md = require('markdown-it')({
  breaks: true,
  highlight: function (str, lang) {
    const codeIndex = parseInt(Date.now()) + Math.floor(Math.random() * 10000000)
    // 显示复制代码按钮
    const copyBtn = `<span class="copy-code-btn" data-clipboard-action="copy" data-clipboard-target="#copy-target-${codeIndex}">复制</span>
<textarea style="position: absolute;top: -9999px;left: -9999px;z-index: -9999;" id="copy-target-${codeIndex}">${str.replace(/<\/textarea>/g, '&lt;/textarea>')}</textarea>`
    if (lang && hl.getLanguage(lang)) {
      const langHtml = `<span class="lang-name">${lang}</span>`
      // 处理代码高亮
      const preCode = hl.highlight(lang, str, true).value
      // 将代码包裹在 pre 中
      return `<pre class="code-container"><code class="language-${lang} hljs">${preCode}</code>${copyBtn} ${langHtml}</pre>`
    }

    // 处理代码高亮
    const preCode = md.utils.escapeHtml(str)
    // 将代码包裹在 pre 中
    return `<pre class="code-container"><code class="language-${lang} hljs">${preCode}</code>${copyBtn}</pre>`
  }
});
// 取消修改
const cancel = function (event, chat) {
  event.stopPropagation();
  chat.edit = false;
  chat.removing = false;
}


const disableInput = (force) => {
  canSend.value = false;
  showReGenerate.value = false;
  showStopGenerate.value = !force;
}

const enableInput = () => {
  canSend.value = true;
  showReGenerate.value = previousText.value !== "";
  showStopGenerate.value = false;
}
// 自动填充 prompt
const autofillPrompt = (text) => {
  prompt.value = text
  textInput.value.focus()
  // sendMessage()
}
// 登录输入框输入事件处理
const inputKeyDown = function (e) {
  if (e.keyCode === 13) {
    if (e.ctrlKey) { // Ctrl + Enter 换行
      prompt.value += "\n";
      return;
    }
    e.preventDefault();
    sendMessage();
  }
}

//账户信息
const showConfig = function () {
  showConfigDialog.value = true;
}



const logout = function () {
  activelyClose.value = true;
  localStorage.clear();
  router.push('/login');
  ElMessage.success('退出成功');
}

const stopGenerate = function () {
  showStopGenerate.value = false;
  httpGet("/api/chat/stop?session_id=" + getSessionId()).then(() => {
    enableInput()
  })
}

// 重新生成
const reGenerate = function () {
  disableInput(false)
  const text = '重新生成上述问题的答案:' + previousText.value;
  // 追加消息
  loading.value=true
  chatData.value.push({
    type: "prompt",
    id: randString(32),
    icon: '/images/avatar/mid_journey.png',
    content: md.render(text)
  });
  var data = {
    userId: openId.value,
    toUserId: openId.value,
    content: chineseChar2englishChar(prompt.value),
    msgType: 2
  }

  sendMessagext(data)

}






</script>

<style scoped lang="stylus">
@import "@/assets/css/chat-plus.styl"
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}</style>

在这里插入图片描述

//移动端
<template>
  <div class="app-background">
    <van-config-provider theme="dark">
      <div class="mobile-chat">
        <van-sticky ref="navBarRef" :offset-top="0" position="top">
          <!-- <van-nav-bar left-arrow left-text="返回" @click-left="router.back()"> -->
          <!-- <template #title>
              <van-dropdown-menu>
                <van-dropdown-item :title="title">
                  <van-cell center title="角色"> {{ role.name }}</van-cell>
                  <van-cell center title="模型">{{ modelValue }}</van-cell>
                </van-dropdown-item>
              </van-dropdown-menu>
            </template> -->

          <!-- <template #right>
              <van-icon name="share-o" @click="showShare = true"/>
            </template> -->

          <!-- </van-nav-bar> -->
        </van-sticky>

        <!-- <van-share-sheet v-model:show="showShare" title="立即分享给好友" :options="shareOptions" @select="shareChat" /> -->

        <div class="chat-list-wrapper">
          <div id="message-list-box" :style="{ height: winHeight + 'px' }" class="message-list-box">
            <van-list v-model:error="error" :finished="finished" error-text="请求失败,点击重新加载" @load="onLoad">
              <van-cell v-for="item in chatData" :key="item" :border="false" class="message-line">
                <chat-prompt v-if="item.type === 'prompt'" :content="item.content"
                  :created-at="dateFormat(item['created_at'])" :icon="item.icon" :model="model"
                  :tokens="item['tokens']" />
                <chat-reply v-else-if="item.type === 'reply'" :content="item.content"
                  :created-at="dateFormat(item['created_at'])" :icon="item.icon" :org-content="item.orgContent"
                  :tokens="item['tokens']" />
                <chat-mid-journey v-else-if="item.type === 'mj'" :content="item.content" :icon="item.icon" :role-id="role"
                  :chat-id="chatId" @disable-input="disableInput(true)" @enable-input="enableInput"
                  :created-at="dateFormat(item['created_at'])" />
              </van-cell>
            </van-list>
          </div>
        </div>
        <div class="chat-box-wrapper">
          <van-sticky ref="bottomBarRef" :offset-bottom="0" position="bottom">

            <van-cell-group inset>
              <van-field v-model="prompt" center clearable placeholder="输入你的问题">
                <template #button>
                  <van-button size="small" type="primary" @click="sendMessage">发送</van-button>
                </template>
                <template #extra>
                  <div class="icon-box" style="margin-left: 10rpx;">
                    <van-icon v-if="showStopGenerate" name="stop-circle-o" @click="stopGenerate" />
                    <van-icon v-if="showReGenerate" name="play-circle-o" @click="reGenerate" />
                  </div>
                </template>
              </van-field>
            </van-cell-group>

          </van-sticky>
        </div>

      </div>
    </van-config-provider>
    <van-overlay z-index="100" :show="loading" class="wrapper">
        <van-loading vertical class="block">
          <template #icon>
            <van-icon name="star-o" size="30" />
          </template>
          正在生成...
        </van-loading>
      </van-overlay>
  </div>
</template>

<script setup>
import { nextTick, onMounted, ref } from "vue";
import { showToast } from "vant";
import { useRouter } from "vue-router";
import { dateFormat, randString, renderInputText, UUID } from "@/utils/libs";
import { getChatConfig } from "@/store/chat";
import { httpGet } from "@/utils/http";
import hl from "highlight.js";
import 'highlight.js/styles/a11y-dark.css'
import ChatPrompt from "@/components/mobile/ChatPrompt.vue";
import ChatReply from "@/components/mobile/ChatReply.vue";
import { getSessionId, getUserToken } from "@/store/session";
import { checkSession } from "@/action/session";
import { getMobileTheme } from "@/store/system";
import ChatMidJourney from "@/components/mobile/ChatMidJourney.vue";

import QRCode from "qrcode";
import { ElMessage } from "element-plus";
import Clipboard from "clipboard";
import InviteList from "@/components/InviteList.vue";

import { createWebscoket, onSend, closeWs, start, onMessage } from '@/utils/socket.js'
import { chineseChar2englishChar } from "@/utils/validate";

const winHeight = ref(0)
const navBarRef = ref(null)
const bottomBarRef = ref(null)
const router = useRouter()

const chatConfig = getChatConfig()
const role = chatConfig ? chatConfig.role : ''
const model = chatConfig ? chatConfig.model : ''
const modelValue = chatConfig ? chatConfig.modelValue : ""
const title = chatConfig ? chatConfig.title : ''
const chatId = chatConfig ? chatConfig.chatId : ''
const loginUser = ref(null)

const listBoxHeight = window.innerHeight
const inviteURL = ref("")
const qrImg = ref("")
const inviteChatCalls = ref(0)
const inviteImgCalls = ref(0)
const hits = ref(0)
const regNum = ref(0)
const rate = ref(0)
const isLogin = ref(false)
const token = ref("")
const openId = ref("")
const overlayshow = ref(false)


onMounted(() => {
  var url = window.location.href;
  console.log(url)
  var regex = /[?&]token=([^&#]+)/; // 匹配 ? 或 & 后面跟 token= 开头的部分
  var regexId = /[?&]openId=([^&#]+)/; // 匹配 ? 或 & 后面跟 token= 开头的部分
  var match = url.match(regex);
  token.value = decodeURIComponent(match[1]);
  openId.value = decodeURIComponent(url.match(regexId)[1]);
  localStorage.setItem('token', token.value)
  localStorage.setItem('openId', openId.value)
  winHeight.value = document.body.offsetHeight - navBarRef.value.$el.offsetHeight - bottomBarRef.value.$el.offsetHeight
  let host = process.env.VUE_APP_WS_HOST
  createWebscoket(host + token.value, messagesCallBack)
  loading.value = false
  previousText.value = '';
  canSend.value = true;
  activelyClose.value = false;
  chatData.value.push({
    content: '您好,我是您的AI智能助手,我会尽力回答您的问题或提供有用的建议。',
    type: "reply",
    id: randString(32),
    icon: '/images/logo.png',
    orgContent: '您好,我是您的AI智能助手,我会尽力回答您的问题或提供有用的建议。',
  })
})

const chatData = ref([])
const loading = ref(false)
const finished = ref(false)
const error = ref(false)

checkSession().then(user => {
  loginUser.value = user
}).catch(() => {
  router.push('/mobile')
})
//取url中的参数值
const getQuery = (name) => {
  // 正则:[找寻'&' + 'url参数名字' = '值' + '&']('&'可以不存在)
  let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
  let r = window.location
  console.log(r);
  if (r != null) {
    // 对参数值进行解码
    return decodeURIComponent(r[2]);
  }
  return null;
}



//新消息监听
const messagesCallBack = (msg) => {
  let socketMsg = msg.msg.replace(/\ufeff/g, "");
  let socketMsgTwo = socketMsg ? JSON.parse(socketMsg) : ''

  if (socketMsgTwo.msgType != -1 || socketMsgTwo.msgType == 200) {
    loading.value = true
    if (socketMsgTwo.contentUrl) {
      chatData.value.push({
        type: "mj",
        key: randString(32),
        icon: '/images/logo.png',
        content: socketMsgTwo.contentUrl
      })
      loading.value = false
    }
    // 将聊天框的滚动条滑动到最底部
    nextTick(() => {
      document.getElementById('chat-box').scrollTo(0, document.getElementById('chat-box').scrollHeight)
      // localStorage.setItem("chat_id", chat_id)
    })
    enableInput()
  }
}

//发送socket消息到服务器
const sendMessagext = (data) => {
  onSend(JSON.stringify(data))
}
//断开socket
const closeWsTxt = () => {
  closeWs()
}

// 创建 socket 连接
const prompt = ref('');
const showStopGenerate = ref(false); // 停止生成
const showReGenerate = ref(false); // 重新生成
const previousText = ref(''); // 上一次提问
const lineBuffer = ref(''); // 输出缓冲行
const socket = ref(null);
const activelyClose = ref(false); // 主动关闭
const canSend = ref(true);
const connect = function () {

  let host = process.env.VUE_APP_WS_HOST

  createWebscoket(host + token.value, messagesCallBack)

  loading.value = false
  previousText.value = '';
  canSend.value = true;
  activelyClose.value = false;

  chatData.value.push({
    content: '您好,我是您的AI智能助手,我会尽力回答您的问题或提供有用的建议。',
    type: "reply",
    id: randString(32),
    icon: '/images/logo.png',
    orgContent: '您好,我是您的AI智能助手,我会尽力回答您的问题或提供有用的建议。',
  })



}

const disableInput = (force) => {
  canSend.value = false;
  // loading.value = true;
  showReGenerate.value = false;
  showStopGenerate.value = !force;
}

const enableInput = () => {
  canSend.value = true;
  // loading.value = false;
  showReGenerate.value = previousText.value !== "";
  showStopGenerate.value = false;
}

// 将聊天框的滚动条滑动到最底部
const scrollListBox = () => {
  document.getElementById('message-list-box').scrollTo(0, document.getElementById('message-list-box').scrollHeight + 46)
}

const sendMessage = () => {
  
  if (canSend.value === false) {
    
    showToast("AI 正在作答中,请稍后...");
    return
  }

  if (prompt.value.trim().length === 0) {
    return false;
  }else{
    loading.value = true
  }
  
  // 追加消息
  chatData.value.push({
    type: "prompt",
    id: randString(32),
    icon: '',
    content: renderInputText(prompt.value),
    created_at: new Date().getTime(),
  });

  nextTick(() => {
    scrollListBox()
  })

  disableInput(false)
  // socket.value.send(prompt.value);
  var data = {
    userId: openId.value,
    toUserId: openId.value,
    content: chineseChar2englishChar(prompt.value),
    msgType: 2
  }
  //websocket 发送
  sendMessagext(data)
  previousText.value = prompt.value;
  prompt.value = '';
  return true;
}

const stopGenerate = () => {
  showStopGenerate.value = false;
  enableInput()

}

const reGenerate = () => {
  disableInput(false)
  const text = '重新生成上述问题的答案:' + previousText.value;
  // 追加消息
  chatData.value.push({
    type: "prompt",
    id: randString(32),
    icon: '',
    content: renderInputText(text)
  });
  var data = {
    userId: openId.value,
    toUserId: openId.value,
    content: chineseChar2englishChar(prompt.value),
    msgType: 1
  }
  // socket.value.send(text);
  sendMessagext(data)
}

const showShare = ref(false)
const shareOptions = [
  { name: '微信', icon: 'wechat' },
  { name: '微博', icon: 'weibo' },
  { name: '复制链接', icon: 'link' },
  { name: '分享海报', icon: 'poster' },
]
const shareChat = () => {
  showShare.value = false
  router.push('/mobile/Invitation');
}
</script>

<style lang="stylus" scoped>
@import "@/assets/css/mobile/chat-session.css"
</style>
<style>
 .wrapper {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
  }

  .block {
    width: 120px;
    height: 120px;
    font-size: 20px;
    color: #1989fa;
    /* background-color: #fff; */
  }
</style>
//uniapp
<template>
	<view class="main">
		<u-navbar :fixed="true" :autoBack="false" @leftClick="goBack"></u-navbar>
		<web-view :src="url" @message="message"></web-view>
	</view>
</template>
<script>
	export default {
		data() {
			return {
				url: '',
				token: '',
				canBack: false,
				openId: ''
			}
		},
		onLoad() {
			this.token = uni.getStorageSync('token');
			this.openId = uni.getStorageSync('openid');
			this.url = 'https://xxxxx.com/mobile?token=' + encodeURIComponent(this.token) + '&openId=' +
				encodeURIComponent(this.openId)
			console.log(this.url)
		},
		methods: {
			message(event) {
				console.log(event.detail.data);
			},


		},

	}
</script>
<style>
	.main {
		width: 100%;
		height: 100vh;
	}
</style>

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:/a/351570.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

VMware安装RHEL-磁盘划分和分区

本文探讨了在VMware虚拟机上安装RHEL时遇到的磁盘划分和分区问题。文章详细介绍了磁盘划分过程中可能出现的问题&#xff0c;特别是在选择磁盘类型时可能导致找不到磁盘的情况。通过清晰的步骤和解决方法&#xff0c;读者可以更好地理解如何正确进行磁盘划分以及如何解决磁盘无…

银行数据仓库体系实践(3)--数据架构

狭义的数据仓库数据架构用来特指数据分布&#xff0c;广义的数据仓库数据架构还包括数据模型、数据标准和数据治理。即包含相对静态部分如元数据、业务对象数据模型、主数据、共享数据&#xff0c;也包含相对动态部分如数据流转、ETL、整合、访问应用和数据全生命周期管控治理。…

AWS 专题学习 P12 (CloudWatch、CloudTrail、AWS Config)

文章目录 专题总览1. CloudWatch1.1 Amazon CloudWatch Metrics1.2 CloudWatch Metric Streams1.3 CloudWatch LogsCloudWatch Logs - SourcesCloudWatch Logs Metric Filter & InsightsCloudWatch Logs – S3 ExportCloudWatch Logs SubscriptionsCloudWatch Logs Aggrega…

jetson-inference----训练自己的目标检测模型(一)

系列文章目录 jetson-inference入门 jetson-inference----docker内运行分类任务 jetson-inference----训练自己的目标检测模型&#xff08;一&#xff09; 文章目录 系列文章目录前言一、jetson-inference docker环境介绍二、SSD目标检测三、训练自己的目标检测模型总结 前言 …

自动驾驶的决策层逻辑

作者 / 阿宝 编辑 / 阿宝 出品 / 阿宝1990 自动驾驶意味着决策责任方的转移 我国2020至2025年将会是向高级自动驾驶跨越的关键5年。自动驾驶等级提高意味着对驾驶员参与度的需求降低&#xff0c;以L3级别为界&#xff0c;低级别自动驾驶环境监测主体和决策责任方仍保留于驾驶…

淘宝扭蛋机小程序:新时代的互动营销与娱乐体验

随着科技的快速发展&#xff0c;小程序已经成为人们日常生活中不可或缺的一部分。在众多的小程序中&#xff0c;淘宝扭蛋机小程序以其独特的互动性和趣味性&#xff0c;吸引了大量用户。本文将深入探讨淘宝扭蛋机小程序的特色、用户体验以及未来发展。 一、淘宝扭蛋机小程序的…

Mybatis 拦截器

MyBatis 拦截器&#xff08;Interceptor&#xff09;是 MyBatis 提供的一种强大机制&#xff0c;允许开发者在 SQL 映射语句执行过程中的特定节点进行拦截和定制处理。通过实现 org.apache.ibatis.plugin.Interceptor 接口并注册到 MyBatis 的配置文件中&#xff0c;可以插入自…

Python开发实例 – Lambda表达式

Python开发实例 – Lambda表达式 Python Development Examples – Lambda expression By JacksonML 普通的函数我们很常用&#xff0c;只需要通过 def 声明&#xff0c;并且产生一段代码&#xff0c;包含&#xff08;但不限于&#xff09;参数&#xff0c;返回&#xff08;或…

解决:‘chromedriver’ executable needs to be in PATH

解决&#xff1a;chromedriver’ executable needs to be in PATH 文章目录 解决&#xff1a;chromedriver’ executable needs to be in PATH背景报错问题报错翻译报错位置代码报错原因解决方法方法一&#xff1a;检查python安装路径有没有添加到环境变量里面方法二&#xff1…

element-ui 树形控件 实现点击某个节点获取本身节点和底下所有的子节点数据

1、需求&#xff1a;点击树形控件中的某个节点&#xff0c;需要拿到它本身和底下所有的子节点的id 1、树形控件代码 <el-tree:data"deptOptions"node-click"getVisitCheckedNodes"ref"target_tree_Speech"node-key"id":default-ex…

漏洞复现-万户OA text2Html 任意文件读取(附漏洞检测脚本)

免责声明 文章中涉及的漏洞均已修复&#xff0c;敏感信息均已做打码处理&#xff0c;文章仅做经验分享用途&#xff0c;切勿当真&#xff0c;未授权的攻击属于非法行为&#xff01;文章中敏感信息均已做多层打马处理。传播、利用本文章所提供的信息而造成的任何直接或者间接的…

MIT_线性代数笔记:线性代数常用计算公式

目录 1.矩阵的加法和数乘2.矩阵的乘法3.转置 Transposes 相关运算 1.矩阵的加法和数乘 2.矩阵的乘法 1)标准方法&#xff08;行乘以列&#xff09; 矩阵乘法的标准计算方法是通过矩阵 A 第 i 行的行向量和矩阵 B 第 j 列的列向量点积得到 cij。即我们常说的点积&#xff0c;也…

华清远见作业第三十二天——C++(第一天)

思维导图&#xff1a; 提示并输入一个字符串&#xff0c;统计字符中大写、小写个数、空格个数以及其他字符个数要求使用C风格完成。 代码&#xff1a; #include <iostream> #include<array> using namespace std;int main() {string str;cout << "请输…

Python Flask与APScheduler构建简易任务监控

1. Flask Web Flask诞生于2010年&#xff0c;是用Python语言&#xff0c;基于Werkzeug工具箱编写的轻量级、灵活的Web开发框架&#xff0c;非常适合初学者或小型到中型的 Web 项目。 Flask本身相当于一个内核&#xff0c;其他几乎所有的功能都要用到扩展&#xff08;邮件扩展…

【异常收集】IDEA启动项目遇到的异常汇总,包括插件异常,版本依赖异常,启动异常等以及对应的解决办法

该文章旨在记录开发中遇到的一些异常&#xff0c;以供遇到似错误进行参考修改 一、项目在多个环境下切换&#xff0c;有一次启动后编译失败&#xff0c;报异常 背景&#xff1a;项目在不同环境下有对应的分支&#xff0c;切换分支后运行项目&#xff0c;报错如下 错误:Kotlin:…

vivado DDS学习

实现DDS通常有两种方式&#xff0c;一种是读取ROM存放的正弦/余弦信号的查表法&#xff0c;另一种是用DDS IP核。这篇学习笔记中&#xff0c;我们要讲解说明的是VIVADO DDS IP核的应用。 目前本篇默认Phase Generator and SIN/COS LUT&#xff08;DDS&#xff09;的standard模式…

102.乐理基础-五线谱-高音谱号

内容参考于&#xff1a;三分钟音乐社 上一个内容&#xff1a;五线谱的构造、谱号是什么-CSDN博客 谱号一共需要学习和了解四种&#xff0c;如下图&#xff1a;要牢牢掌握的是高音谱号和低音谱号这两种&#xff0c;如图1所示 首先高音谱号&#xff1a; 它大致范围&#xff0c;…

SpringBoot中集成XXL-JOB分布式任务调度平台,轻量级、低侵入实现定时任务

场景 XXL-JOB 分布式任务调度平台XXL-JOB XXL-JOB是一个分布式任务调度平台&#xff0c;其核心设计目标是开发迅速、学习简单、轻量级、易扩展。 特性&#xff1a; 1、简单&#xff1a;支持通过Web页面对任务进行CRUD操作&#xff0c;操作简单&#xff0c;一分钟上手&…

【51单片机】蜂鸣器实验和动态数码管实验

目录 蜂鸣器实验蜂鸣器介绍硬件设计软件设计 动态数码管实验多位数码管简介74HC245 芯片简介74HC138 芯片简介 硬件设计软件设计 橙色 蜂鸣器实验 蜂鸣器介绍 蜂鸣器采用直流电压供电&#xff0c;分为压电式蜂鸣器和电磁式蜂鸣器两种类型。 无论是压电式蜂鸣器还是电磁式蜂…

huggingface高速下载模型的实战代码

大家好,我是herosunly。985院校硕士毕业,现担任算法研究员一职,热衷于机器学习算法研究与应用。曾获得阿里云天池比赛第一名,CCF比赛第二名,科大讯飞比赛第三名。拥有多项发明专利。对机器学习和深度学习拥有自己独到的见解。曾经辅导过若干个非计算机专业的学生进入到算法…