123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208 |
- <template>
- <view class="chat-container">
- <scroll-view class="messages" scroll-y :scroll-top="scrollTop" scroll-with-animation>
- <block v-for="message in messages" :key="message.id">
- <view :class="['message', message.user]">
- <view class="avatar-container">
- <image :src="message.user === 'user' ? userAvatar : '/static/机器人.png'" class="avatar"
- mode="aspectFill" />
- <text class="sender-name">{{ message.user === 'user' ? userInfo.nickName : 'AI助理' }}</text>
- </view>
- <view class="message-content"> <!-- 改为 message-content 类 -->
- <template v-if="message.message.includes('相关资料来源')">
- <view>{{ getMainContent(message.message) }}</view>
- <view class="source-section" v-if="minioUrls && minioUrls.length > 0">
- <view class="source-title">相关资料来源:</view>
- <view class="source-links">
- <view v-for="(item, index) in minioUrls" :key="index" class="source-link"
- @tap="copyLink(item.url)">
- {{ item.object_name }}
- </view>
- </view>
- </view>
- <!-- <view v-if="message.user === 'bot' && message.audioData && message.audioData.visible"
- class="audio-controls">
- <view class="audio-btn" @tap="playAudio(message.audioData.base64, message.id)">
- <image :src="message.audioData.isPlaying ? '/static/pause.svg' : '/static/play.svg'"
- class="audio-icon" mode="aspectFit" />
- </view>
- <view class="audio-progress" v-if="message.audioData.progress">
- {{ message.audioData.progress }}%
- </view>
- </view> -->
- </template>
- <template v-else>
- {{ message.message }}
- </template>
- </view>
- </view>
- </block>
- </scroll-view>
- <!-- 添加新建对话按钮 -->
- <!-- <view class="new-chat-btn">
- <button @tap="startNewChat" class="btn-new">新建对话</button>
- </view> -->
- <view class="input-container">
- <!-- 图片预览区域和上传按钮组合 -->
- <scroll-view class="image-upload-area" scroll-x :show-scrollbar="false"
- v-if="selectedImages.length > 0 || selectedVideos.length > 0 || selectedDocs.length > 0">
- <view class="image-list">
- <!-- 图片预览 -->
- <view class="image-preview" v-for="(image, index) in selectedImages" :key="'img-'+index">
- <image :src="image" mode="aspectFill" class="preview-img" />
- <view class="delete-btn" @tap="removeImage(index)">
- <text class="delete-icon">×</text>
- </view>
- </view>
- <!-- 视频预览 -->
- <view class="image-preview" v-for="(video, index) in selectedVideos" :key="'vid-'+index">
- <view class="video-preview-container">
- <image src="/static/video-placeholder.svg" mode="aspectFill" class="preview-img" />
- <!-- <image src="/static/play-icon.svg" class="play-icon" /> -->
- </view>
- <view class="delete-btn" @tap="removeVideo(index)">
- <text class="delete-icon">×</text>
- </view>
- </view>
- <!-- 文档预览 -->
- <view class="doc-preview" v-for="(doc, index) in selectedDocs" :key="'doc-'+index">
- <view class="doc-preview-container">
- <image src="/static/doc-icon.svg" mode="aspectFit" class="doc-icon" />
- <text class="doc-name">{{ doc.name }}</text>
- </view>
- <view class="delete-btn" @tap="removeDoc(index)">
- <text class="delete-icon">×</text>
- </view>
- </view>
- <!-- 继续上传按钮 -->
- <view class="upload-btn" @tap="chooseMedia"
- v-if="selectedImages.length < maxImages && selectedVideos.length < maxVideos && selectedDocs.length < maxDocs">
- <image src="/static/upload.svg" class="upload-icon" mode="aspectFit" />
- </view>
- </view>
- </scroll-view>
- <view class="input-wrapper">
- <textarea v-model="userInput" @keydown="handleKeydown" placeholder="有问题可以咨询我..." maxlength="100"
- class="input-textarea" />
- <!-- 添加设置按钮 -->
- <view class="set_btn">
- <image src="/static/images/setting.png" @tap="showVoiceSettings" class="settings-icon" />
- <view
- v-if="!userInput.trim() && !selectedImages.length && !selectedVideos.length && !selectedDocs.length"
- class="upload-options">
- <image src="/static/upload.svg" @tap="chooseMedia" class="upload-icon" />
- </view>
- <image v-else src="/static/sendm.svg" @tap="sendMessage" class="upload-img"></image>
- </view>
- </view>
- </view>
- <!-- 添加语音设置弹窗 -->
- <uni-popup ref="voiceSettingsPopup" type="center" :mask-click="false" mask-background-color="rgba(0, 0, 0, 0.6)"
- @change="handlePopupChange">
- <view class="settings-popup">
- <view class="settings-header">
- <text class="settings-title">语音设置</text>
- <text class="close-btn" @tap="closeVoiceSettings">×</text>
- </view>
- <view class="settings-content">
- <view class="settings-item">
- <text class="item-label">语言</text>
- <picker :value="languageOptions.indexOf(voiceSettings.language)" :range="languageOptions"
- @change="handleLanguageChange">
- <view class="picker-value">{{voiceSettings.language || '请选择'}}</view>
- </picker>
- </view>
- <view class="settings-item">
- <text class="item-label">声音名称</text>
- <picker :value="currentVoices.findIndex(v => v.name === voiceSettings.voice_name)"
- :range="currentVoices" range-key="name" @change="handleVoiceNameChange">
- <view class="picker-value">{{voiceSettings.voice_name || '请选择'}}</view>
- </picker>
- </view>
- <view class="settings-item">
- <text class="item-label">性别</text>
- <view class="picker-value">{{voiceSettings.gender}}</view>
- </view>
- <view class="settings-item">
- <text class="item-label">风格</text>
- <picker :value="styleOptions.indexOf(voiceSettings.style)" :range="styleOptions"
- @change="handleStyleChange">
- <view class="picker-value">{{voiceSettings.style || '请选择'}}</view>
- </picker>
- </view>
- <view class="settings-item">
- <text class="item-label">语速 ({{voiceSettings.rate}})</text>
- <slider :value="parseInt(voiceSettings.rate)" @change="handleRateChange" min="0" max="100"
- show-value />
- </view>
- <view class="settings-item">
- <text class="item-label">音量 ({{voiceSettings.volume}})</text>
- <slider :value="parseInt(voiceSettings.volume)" @change="handleVolumeChange" min="0" max="100"
- show-value />
- </view>
- </view>
- <button class="save-btn" @tap="saveVoiceSettings">保存设置</button>
- </view>
- </uni-popup>
- </view>
- </template>
- <script>
- import MarkdownIt from "markdown-it";
- const md = new MarkdownIt();
- export default {
- data() {
- return {
- messages: [{
- user: "bot",
- messageType: "TEXT",
- message: "欢迎使用智能AI助理",
- html: "",
- time: "",
- done: true,
- }, ],
- userInput: "",
- websocket: null,
- AiUrl: '',
- apiUrl: 'https://ylaiapi.raycos.com.cn', //https://ylaiapi.raycos.com.cn
- scrollTop: 0,
- tweaks: {},
- userAvatar: '/static/用户.png',
- userInfo: {},
- level: 1,
- idArray: [],
- minioUrls: [], // 新增:用于存储 Minio URL
- generating: false, // 是否正在生成回复
- typewriterTimer: null,
- currentIndex: 0,
- fullMessage: '',
- session_id: "",
- platform: {
- type: '', // 平台类型
- name: '', // 平台名称
- isWeixin: false
- },
- selectedImages: [], // 存储已上传图片的信息
- uploadedFiles: [], // 存储上传后的文件信息
- maxImages: 9,
- selectedVideos: [], // 存储已选择的视频
- uploadedVideos: [], // 存储已上传的视频信息
- maxVideos: 1, // 限制视频上传数量
- currentAudioContext: null,
- currentPlayingMessage: null,
- currentPlayingMessageId: null, // 添加:跟踪当前正在播放的消息ID
- selectedDocs: [], // 存储已选择的文档
- uploadedDocs: [], // 存储已上传的文档信息
- maxDocs: 3, // 限制文档上传数量
- voiceSettings: {
- language: 'zh-cn',
- voice_name: '',
- gender: '',
- style: '',
- rate: '+10%',
- volume: '+20%'
- },
- voicesData: {}, // 存储接口返回的语音数据
- languageOptions: [], // 可选择的语言
- currentVoices: [], // 当前语言下的声音选项
- styleOptions: [], // 当前选择的声音可用的风格
- };
- },
- created() {
- },
- onLoad() {
- // this.getKbmUrl()
- this.loadUserInfo()
- this.getPlatformInfo();
- },
- onShow() {
- this.getKbmUrl()
- },
- watch: {
- messages: {
- handler() {
- this.$nextTick(() => {
- this.scrollToBottom();
- });
- },
- deep: true
- }
- },
- methods: {
- /* 语速及音量 */
- handleRateChange(e) {
- const value = e.detail.value;
- // 将滑块值转换为百分比格式
- this.voiceSettings.rate = value > 0 ? `+${value}%` : `${value}%`;
- },
- handleVolumeChange(e) {
- const value = e.detail.value;
- // 将滑块值转换为百分比格式
- this.voiceSettings.volume = value > 0 ? `+${value}%` : `${value}%`;
- },
- // 添加新建对话方法
- startNewChat() {
- uni.showModal({
- title: '确认新建对话',
- content: '是否清空当前对话内容开始新的对话?',
- success: (res) => {
- if (res.confirm) {
- // 重置消息列表,只保留欢迎息
- this.messages = [{
- user: "bot",
- messageType: "TEXT",
- message: "欢迎使用智能AI助理",
- html: "",
- time: "",
- done: true,
- }];
- // 清空session_id
- this.session_id = "";
- // 清空MinioUrls
- this.minioUrls = [];
- // 重置其他相关状态
- this.generating = false;
- this.currentIndex = 0;
- this.fullMessage = '';
- // 显示提示
- uni.showToast({
- title: '已开始新对话',
- icon: 'success',
- duration: 1500
- });
- }
- }
- });
- },
- // 获取平台信息
- getPlatformInfo() {
- try {
- const systemInfo = uni.getSystemInfoSync();
- // console.log('系统信息:', systemInfo);
- // 判断平台类型
- // #ifdef MP-WEIXIN
- this.platform.type = 'mp-weixin';
- this.platform.name = '微信小程序';
- this.platform.isWeixin = true;
- // #endif
- // #ifdef MP-ALIPAY
- this.platform.type = 'mp-alipay';
- this.platform.name = '支付宝小程序';
- // #endif
- // #ifdef MP-BAIDU
- this.platform.type = 'mp-baidu';
- this.platform.name = '百度小程序';
- // #endif
- // #ifdef MP-TOUTIAO
- this.platform.type = 'mp-toutiao';
- this.platform.name = '头条小程序';
- // #endif
- // #ifdef H5
- this.platform.type = 'h5';
- this.platform.name = 'H5';
- // 在H5中判断是否在微信浏览器中
- if (navigator.userAgent.toLowerCase().indexOf('micromessenger') !== -1) {
- this.platform.isWeixin = true;
- this.platform.name = 'H5微信浏览器';
- }
- // #endif
- // #ifdef APP-PLUS
- this.platform.type = 'app';
- this.platform.name = 'App';
- // #endif
- // console.log('当前平台:', this.platform);
- // 获取更详细的平台信息
- const platformInfo = {
- brand: systemInfo.brand, // 手机品牌
- model: systemInfo.model, // 手机型号
- system: systemInfo.system, // 操作系统版本
- platform: systemInfo.platform, // 客户端平台
- SDKVersion: systemInfo.SDKVersion, // 小程序基库版本
- version: systemInfo.version, // 微信版本号
- };
- // console.log('平台详细信息:', platformInfo);
- return this.platform;
- } catch (error) {
- console.error('获取平台信息失败:', error);
- return {
- type: 'unknown',
- name: '未知平台',
- isWeixin: false
- };
- }
- },
- getMainContent(message) {
- const parts = message.split('相关资料来源');
- return parts[0].trim();
- },
- extractUrls(message) {
- const urlRegex = /href="([^"]+)"/g;
- const urls = [];
- let match;
- while ((match = urlRegex.exec(message)) !== null) {
- urls.push(match[1]);
- }
- return urls;
- },
- getFileName(url) {
- try {
- const decodedUrl = decodeURIComponent(url);
- const parts = decodedUrl.split('/');
- let fileName = parts[parts.length - 1];
- // 如果文件名过长,截断
- if (fileName.length > 30) {
- fileName = fileName.substring(0, 27) + '...';
- }
- return fileName;
- } catch (e) {
- return '文件';
- }
- },
- // 修改 copyLink 方法
- copyLink(url) {
- if (!url) return;
- uni.setClipboardData({
- data: url,
- success: () => {
- uni.showToast({
- title: '链接已复制',
- icon: 'none',
- duration: 1500
- });
- }
- });
- },
- loadUserInfo() {
- const userDataString = uni.getStorageSync('userInfo');
- if (userDataString) {
- this.userInfo = JSON.parse(userDataString);
- this.userAvatar = this.userInfo.avatarUrl || '/static/用户.png'; // Fallback to default if no avatar
- }
- },
- scrollToBottom() {
- // 使用一个很大的值来确保滚动到底部
- this.scrollTop += 9999;
- // 重置 scrollTop 以便下次动生效
- // this.$nextTick(() => {
- // this.scrollTop = 0;
- // });
- },
- /* 请求链接 */
- getKbmUrl() {
- let userDataString;
- if (uni.getStorageSync('userData') == '') {
-
- // 跳转到个人页面
- uni.switchTab({
- url: '/pages/my/index',
- success: function() {
- },
- fail: function(err) {
- console.error('Failed to switch to personal page:', err);
- }
- });
- return;
- } else {
- userDataString = JSON.parse(uni.getStorageSync('userData'));
- }
- uni.request({
- url: this.apiUrl + '/wechat/getUserInfo',
- method: 'POST',
- data: {
- openid: userDataString.openid
- },
- header: {
- 'content-type': 'application/x-www-form-urlencoded'
- },
- success: (res) => {
- console.log('获取用户信息成功', res.data);
- this.AiUrl = this.apiUrl + '/chatbot/multimodal'
- this.level = res.data.data.level
- },
- fail: (err) => {
- console.error('获取用户信息失败', err);
- uni.showToast({
- title: '获取用户信息失败,请重试',
- icon: 'none'
- });
- }
- });
- /* uni.request({
- url: this.apiUrl + '/wechat/getKbmUrl', // 确保这是正确的URL
- method: 'POST',
- data: {
- openid: userDataString.openid
- }, //JSON.stringify()
- header: {
- 'content-type': 'application/x-www-form-urlencoded' // 设置正确的内容类型
- },
- success: (res) => {
- console.log('Login response:', res.data);
- if (res.data && res.data.status == 200) {
- this.tweaks = res.data.data.tweaks
- this.connectWebSocket();
- }
- },
- fail: (err) => {
- console.error('请求失败', err);
- uni.showToast({
- title: '请求失败,请重试',
- icon: 'none'
- });
- }
- }) */
- },
- getUuid() {
- return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(
- /[xy]/g,
- function(c) {
- var r = (Math.random() * 16) | 0,
- v = c == "x" ? r : (r & 0x3) | 0x8;
- return v.toString(16);
- }
- );
- },
- connectWebSocket() {
- const wsUrl = this.AiUrl
- //'http://ai.raycos.net/api/v1/run/c7ea3a2d-f50c-4936-b96c-3fe7c34fa062?stream=false';
- // 使用 XMLHttpRequest 替代 fetch
- uni.request({
- url: wsUrl,
- method: 'POST',
- data: JSON.stringify({}), // 如果需要发送数据,可以在这里加
- header: {
- 'content-type': 'application/json'
- },
- success: (res) => {
- if (res.statusCode === 200) {
- const result = res.data;
- this.handleWebSocketMessage(result);
- } else {
- console.error("请求失败:", res.statusCode);
- }
- },
- fail: (err) => {
- console.error("网络连接错误:", err);
- }
- });
- // 如果需要发送数据,可以在这里添加
- },
- // 新增方法来处理消息
- handleWebSocketMessage(result) {
-
- // 检查消息是否完结
- if (result.done) {
- this.messages[this.messages.length - 1].done = true;
- return;
- }
- if (this.messages[this.messages.length - 1].done) {
- // 添加新的消息
- this.messages.push({
- time: Date.now(),
- message: result.content,
- messageType: "TEXT",
- user: "bot",
- done: false,
- });
- } else {
- // 更新最后一条消息
- let lastMessage = this.messages[this.messages.length - 1];
- lastMessage.message += result.content;
- this.messages[this.messages.length - 1] = lastMessage;
- }
- },
- // 修改发送消息方法
- async sendMessage() {
- /* // 确保在发送新消息前停止当前音频
- if (this.currentAudioContext) {
- this.stopCurrentAudio();
- } */
- const message = this.userInput.trim();
- if (!message && !this.selectedImages.length && !this.selectedVideos.length && !this.selectedDocs.length) {
- return;
- }
- // 构建用户消息对象
- const userMessage = {
- id: this.getUuid(),
- user: "user",
- messageType: "TEXT",
- message: message,
- time: Date.now(),
- done: true,
- images: this.uploadedFiles.map(file => file.url),
- videos: this.uploadedVideos.map(file => file.url),
- docs: this.uploadedDocs.map(file => file.url)
- };
- this.messages.push(userMessage);
- // 清空输入框和媒体文件
- this.userInput = "";
- this.selectedImages = [];
- this.uploadedFiles = [];
- this.selectedVideos = [];
- this.uploadedVideos = [];
- this.selectedDocs = [];
- this.uploadedDocs = [];
- this.scrollToBottom();
- // 添加AI助理的消息
- const botMessage = {
- id: this.getUuid(),
- user: "bot",
- messageType: "TEXT",
- message: "正在思考中...",
- time: Date.now(),
- done: false,
- };
- this.messages.push(botMessage);
- try {
- const response = await uni.request({
- url: this.AiUrl,
- method: 'POST',
- header: {
- 'Content-Type': 'application/json'
- },
- data: {
- message: message,
- image_urls: userMessage.images,
- video_urls: userMessage.videos, // 添加视频URL到请求
- documents_file: userMessage.docs, // 添加文档URL到请求
- chat_config_id: '17',
- user_id: this.userInfo.phoneNumber,
- session_id: this.session_id || "",
- }
- });
- // 检查响应状态和数据
- if (response.statusCode !== 200 || !response.data || !response.data.data?.answer) {
- throw new Error('Invalid response from server');
- }
- if (this.level === '0' && response.data.data?.milvus_ids) {
- await this.getMinioUrls({
- ids: response.data.data.milvus_ids
- });
- }
- this.session_id = response.data.data.session_id;
- await this.handleResponse(response.data, botMessage);
- // 如果有音频,播放音频
- if (
- response.data.data.audio_info &&
- response.data.data.audio_info.audio
- ) {
- this.playAudio(response.data.data.audio_info.audio);
- }
- } catch (error) {
- console.error("Error sending message:", error);
- // 找到最后一条消息(应该是机器人的消息)并更新它
- const lastMessage = this.messages[this.messages.length - 1];
- if (lastMessage && lastMessage.user === 'bot') {
- lastMessage.message = "抱歉,处理消息时出现错误,请重试。";
- lastMessage.done = true;
- }
- uni.showToast({
- title: '发送消息失败,请重试',
- icon: 'none'
- });
- }
- },
- // 修改停止当前音频的方法
- stopCurrentAudio() {
- try {
- if (this.currentAudioContext) {
- // 先停止播放
- this.currentAudioContext.stop();
-
- // 更新消息的播放状态
- if (this.currentPlayingMessageId) {
- const message = this.messages.find(m => m.id === this.currentPlayingMessageId);
- if (message && message.audioData) {
- message.audioData.isPlaying = false;
- message.audioData.progress = 0;
- }
- }
- // 销毁音频实例
- this.currentAudioContext.destroy();
- this.currentAudioContext = null;
- this.currentPlayingMessageId = null;
- }
- } catch (error) {
- console.error('停止音频时出错:', error);
- // 即使出错也要重置状态
- this.currentAudioContext = null;
- this.currentPlayingMessageId = null;
- }
- },
- // 修改播放音频方法
- playAudio(audioBase64, messageId) {
- try {
- // 如果有正在播放的音频,先停止它
- if (this.currentAudioContext) {
- this.stopCurrentAudio();
- }
- // 创建新的音频上下文
- const innerAudioContext = uni.createInnerAudioContext();
-
- // 设置音频源
- innerAudioContext.src = audioBase64;
- // 更新状态和引用
- this.currentAudioContext = innerAudioContext;
- this.currentPlayingMessageId = messageId;
- // 更新消息的播放状态
- const message = this.messages.find(m => m.id === messageId);
- if (message && message.audioData) {
- message.audioData.isPlaying = true;
- message.audioData.progress = 0;
- }
- // 监听播放错误
- innerAudioContext.onError((res) => {
- console.error('音频播放错误:', res.errMsg);
- uni.showToast({
- title: '音频播放失败',
- icon: 'none'
- });
- this.stopCurrentAudio();
- });
- // 播放结束后的处理
- innerAudioContext.onEnded(() => {
- this.stopCurrentAudio();
- });
- // 开始播放
- innerAudioContext.play();
- } catch (error) {
- console.error('播放音频失败:', error);
- this.stopCurrentAudio();
- }
- },
- // 修改组件销毁时的处理
- beforeDestroy() {
- // 确保在组件销毁前停止并清理音频
- if (this.currentAudioContext) {
- this.stopCurrentAudio();
- }
- },
- // 修改 getMinioUrls 方法
- async getMinioUrls(idObject) {
- this.minioUrls = []
- try {
- const response = await uni.request({
- url: `${this.apiUrl}/milvus/getMinioURl`,
- method: 'POST',
- data: idObject,
- header: {
- 'Content-Type': 'application/json'
- }
- });
- if (response.statusCode === 200 && response.data?.data) {
- this.minioUrls = response.data.data;
- console.log("Received Minio URLs:", this.minioUrls);
- } else {
- this.minioUrls = [];
- console.error("Invalid response format:", response);
- }
- } catch (error) {
- console.error("Error fetching Minio URLs:", error);
- this.minioUrls = [];
- uni.showToast({
- title: '获取资源链接失败',
- icon: 'none'
- });
- }
- },
- // 修改 handleResponse 方法
- async handleResponse(value, existingMessage) {
- try {
- if (!value?.data?.answer) {
- throw new Error('Invalid response format');
- }
- const data = value.data.answer;
- this.fullMessage = data;
- this.currentIndex = 0;
- // 先设置基本消息结构
- existingMessage.message = '';
- existingMessage.done = false;
- // 如果有音频数据,创建完整的音频数据结构
- if (value.data.audio_info?.audio) {
- existingMessage.audioData = {
- base64: value.data.audio_info.audio,
- isPlaying: false,
- progress: 0,
- visible: true // 添加可见性标志
- };
- }
- // 开始打字效果
- this.startTypewriter(existingMessage);
- } catch (error) {
- console.error("Error handling response:", error);
- existingMessage.message = "抱歉,处理响应时出现错误。";
- existingMessage.done = true;
- }
- },
- // 新的打字效果实现
- startTypewriter(existingMessage) {
- // 清除可能存在的旧计时器
- if (this.typewriterTimer) {
- clearInterval(this.typewriterTimer);
- this.typewriterTimer = null;
- }
- const doTypewriter = () => {
- if (this.currentIndex < this.fullMessage.length) {
- // 保存有的音频数据
- const audioData = existingMessage.audioData;
- // 新消息内容
- existingMessage.message = this.fullMessage.slice(0, this.currentIndex + 1);
- // 恢复音频数据
- if (audioData) {
- existingMessage.audioData = audioData;
- }
- this.currentIndex++;
- // 使用 nextTick 确保视图更新
- this.$nextTick(() => {
- this.scrollToBottom();
- });
- // 使用 setTimeout 代替 setInterval
- this.typewriterTimer = setTimeout(() => {
- doTypewriter();
- }, 30);
- } else {
- // 打字效果完成
- // 保存原有的音频数据
- const audioData = existingMessage.audioData;
- if (this.minioUrls && this.minioUrls.length > 0) {
- existingMessage.message += '\n\n相关资料来源';
- }
- // 恢复音频数据
- if (audioData) {
- existingMessage.audioData = audioData;
- }
- existingMessage.done = true;
- this.typewriterTimer = null;
- this.scrollToBottom();
- }
- };
- // 立即开始打字效果
- doTypewriter();
- },
- // 修改 renderMarkdown 方法以保留 HTML 标签
- /* renderMarkdown(rawMarkdown) {
- if (typeof rawMarkdown !== 'string') {
- console.warn('Invalid input for renderMarkdown:', rawMarkdown);
- return '';
- }
- try {
- const md = new MarkdownIt({
- html: true, // 允许 HTML 标签
- breaks: true,
- linkify: true
- });
- // 自定义链接渲染
- md.renderer.rules.link_open = (tokens, idx) => {
- const token = tokens[idx];
- const hrefIndex = token.attrIndex('href');
- const href = token.attrs[hrefIndex][1];
- return `<text class="link" style="color: #1296db; text-decoration: underline;" data-href="${href}">`;
- };
- md.renderer.rules.link_close = () => '</text>';
- // 自定义段落染
- md.renderer.rules.paragraph_open = () =>
- '<p style="font-size: 12px; margin: 5px 0 10px; padding: 0; line-height: 22px;">';
- return md.render(rawMarkdown);
- } catch (error) {
- console.error('Markdown rendering error:', error);
- return rawMarkdown;
- }
- }, */
- // 修改 sendMessage 方法
- /* async sendMessage() {
- const wsUrl = this.AiUrl;
- let message = this.userInput.trim();
- if (message) {
- // 添加用户消息
- const userMessage = {
- id: this.getUuid(),
- user: "user",
- messageType: "TEXT",
- message: message,
- time: Date.now(),
- done: true,
- };
- this.messages.push(userMessage);
- // 清空输入框并滚动
- this.userInput = "";
- this.scrollToBottom();
- // 添加AI助理的消息
- const botMessage = {
- id: this.getUuid(),
- user: "bot",
- messageType: "TEXT",
- message: "正在思考中...", // 添加加载提示
- time: Date.now(),
- done: false,
- };
- this.messages.push(botMessage);
- try {
- const response = await uni.request({
- url: wsUrl,
- method: 'POST',
- header: {
- 'Content-Type': 'application/json'
- },
- data: {
- message: message,
- chat_config_id: '17',
- user_id: this.userInfo.phoneNumber,
- session_id: this.session_id || "",
- }
- });
- if (response.statusCode === 200 && response.data) {
- // 如果需要获取 MinioUrls,先获取
- if (this.level === '0' && response.data.data?.milvus_ids) {
- await this.getMinioUrls({
- ids: response.data.data.milvus_ids
- });
- }
- // 然后处理完整响应
- await this.handleResponse(response.data, botMessage);
- }
- } catch (error) {
- console.error("Error sending message:", error);
- botMessage.message = "抱歉,发送消息失败,请重试。";
- botMessage.done = true;
- uni.showToast({
- title: '发送消息失败,请重试',
- icon: 'none'
- });
- }
- }
- }, */
- // 修改 renderMarkdown 方法
- /* renderMarkdown(rawMarkdown) {
- if (typeof rawMarkdown !== 'string') {
- console.warn('Invalid input for renderMarkdown:', rawMarkdown);
- return '';
- }
-
- try {
- const md = new MarkdownIt({
- html: true,
- breaks: true,
- linkify: true
- });
-
- // 自定义链接渲染
- md.renderer.rules.link_open = (tokens, idx) => {
- const token = tokens[idx];
- const hrefIndex = token.attrIndex('href');
- const href = token.attrs[hrefIndex][1];
- return `<text class="link" data-href="${href}">`;
- };
- md.renderer.rules.link_close = () => '</text>';
-
- return md.render(rawMarkdown);
- } catch (error) {
- console.error('Markdown rendering error:', error);
- return rawMarkdown;
- }
- }, */
- // 添加链接点击处理方法
- // 修改 handleLinkClick 方法
- // 修改 renderMarkdown 方法
- renderMarkdown(rawMarkdown) {
- if (typeof rawMarkdown !== 'string') {
- console.warn('Invalid input for renderMarkdown:', rawMarkdown);
- return '';
- }
- try {
- const md = new MarkdownIt({
- html: true,
- breaks: true,
- linkify: true
- });
- // 自定义链接渲染
- md.renderer.rules.link_open = (tokens, idx) => {
- const token = tokens[idx];
- const hrefIndex = token.attrIndex('href');
- const href = token.attrs[hrefIndex][1];
- // 使用自定义的类名和数据属性
- return `<view class="custom-link" data-url="${href}">`;
- };
- md.renderer.rules.link_close = () => '</view>';
- const html = md.render(rawMarkdown);
- return html;
- } catch (error) {
- console.error('Markdown rendering error:', error);
- return rawMarkdown;
- }
- },
- // 修改 handleLinkClick 方法
- handleLinkClick(e) {
- // 查找最近的带有 custom-link 类的父元素
- let target = e.target;
- while (target && !target.classList?.contains('custom-link')) {
- target = target.parentElement;
- }
- if (target && target.dataset.url) {
- const url = target.dataset.url;
- console.log('Clicked URL:', url);
- // 复制链接到剪贴板
- uni.setClipboardData({
- data: url,
- success: () => {
- uni.showToast({
- title: '链接已复制',
- icon: 'none'
- });
- }
- });
- }
- },
- /* renderMarkdown(rawMarkdown) {
- if (typeof rawMarkdown !== 'string') {
- console.warn('Invalid input for renderMarkdown:', rawMarkdown);
- return '';
- }
- return md.render(rawMarkdown);
- }, */
- handleKeydown(event) {
- // Check if 'Enter' is pressed without the 'Alt' key
- if (event.key === "Enter" && !(event.shiftKey || event.altKey)) {
- event.preventDefault(); // Prevent the default action to avoid line break in textarea
- this.sendMessage();
- } else if (event.key === "Enter" && event.altKey) {
- // Allow 'Alt + Enter' to insert a newline
- const cursorPosition = event.target.selectionStart;
- const textBeforeCursor = this.userInput.slice(0, cursorPosition);
- const textAfterCursor = this.userInput.slice(cursorPosition);
- // Insert the newline character at the cursor position
- this.userInput = textBeforeCursor + "\n" + textAfterCursor;
- // Move the cursor to the right after the inserted newline
- this.$nextTick(() => {
- event.target.selectionStart = cursorPosition + 1;
- event.target.selectionEnd = cursorPosition + 1;
- });
- }
- },
- beforeDestroy() {
- if (this.websocket) {
- this.websocket.close();
- }
- },
- // 选择图片
- chooseImage() {
- const remainingSlots = this.maxImages - this.selectedImages.length;
- if (remainingSlots <= 0) {
- uni.showToast({
- title: `最多只能上传${this.maxImages}张图片`,
- icon: 'none'
- });
- return;
- }
- uni.chooseImage({
- count: remainingSlots,
- success: async (res) => {
- // 即处理每个选择的图片
- for (const tempFilePath of res.tempFilePaths) {
- await this.uploadSingleImage(tempFilePath);
- }
- },
- fail: (err) => {
- console.error('选择图片失败:', err);
- uni.showToast({
- title: '选择图片失败',
- icon: 'none'
- });
- }
- });
- },
- // 新增单个图片上传方法
- async uploadSingleImage(tempFilePath) {
- try {
- // 显示上传进度提示
- uni.showLoading({
- title: '正在上传...',
- mask: true
- });
- const uploadResult = await uni.uploadFile({
- url: `${this.apiUrl}/upload/file`, // 修改为你的上传接口
- filePath: tempFilePath,
- name: 'file',
- header: {
- 'Content-Type': 'multipart/form-data'
- }
- });
- if (uploadResult.statusCode === 200) {
- const response = JSON.parse(uploadResult.data);
- const fileUrl = response.data.fileUrl; // 根据实际返回结构调整
- // 添加已上传文件组
- this.uploadedFiles.push({
- url: fileUrl
- });
- // 更新预览图片数组
- this.selectedImages.push(tempFilePath);
- uni.hideLoading();
- uni.showToast({
- title: '上传成功',
- icon: 'success'
- });
- } else {
- throw new Error('Upload failed');
- }
- } catch (error) {
- console.error('图片上传失败:', error);
- uni.hideLoading();
- uni.showToast({
- title: '上传失败',
- icon: 'none'
- });
- }
- },
- // 修改移除图片方法
- removeImage(index) {
- // 同时移除预览图和已上传的文件信息
- this.selectedImages.splice(index, 1);
- this.uploadedFiles.splice(index, 1);
- },
- // 添加选择视频方法
- chooseVideo() {
- if (this.selectedVideos.length >= this.maxVideos) {
- uni.showToast({
- title: `最多只能上传${this.maxVideos}个视频`,
- icon: 'none'
- });
- return;
- }
- uni.chooseVideo({
- count: 1,
- sourceType: ['album', 'camera'],
- success: async (res) => {
- await this.uploadSingleVideo(res.tempFilePath);
- },
- fail: (err) => {
- console.error('选择视频失败:', err);
- uni.showToast({
- title: '选择视频失败',
- icon: 'none'
- });
- }
- });
- },
- // 添加上传单个视频方法
- async uploadSingleVideo(tempFilePath) {
- try {
- uni.showLoading({
- title: '正在上传视频...',
- mask: true
- });
- const uploadResult = await uni.uploadFile({
- url: `${this.apiUrl}/upload/file`,
- filePath: tempFilePath,
- name: 'file',
- header: {
- 'Content-Type': 'multipart/form-data'
- }
- });
- if (uploadResult.statusCode === 200) {
- const response = JSON.parse(uploadResult.data);
- const fileUrl = response.data.fileUrl;
- // 添加到已上传视频数组
- this.uploadedVideos.push({
- url: fileUrl
- });
- // 更新预览视频数组
- this.selectedVideos.push(tempFilePath);
- uni.hideLoading();
- uni.showToast({
- title: '上传成功',
- icon: 'success'
- });
- } else {
- throw new Error('Upload failed');
- }
- } catch (error) {
- console.error('视频上传失败:', error);
- uni.hideLoading();
- uni.showToast({
- title: '上传失败',
- icon: 'none'
- });
- }
- },
- // 修改移除视频方法
- removeVideo(index) {
- this.selectedVideos.splice(index, 1);
- this.uploadedVideos.splice(index, 1);
- },
- // 新增统一的媒体选择方法
- chooseMedia() {
- const options = [];
- if (this.selectedImages.length < this.maxImages) {
- options.push('选择图片');
- }
- if (this.selectedVideos.length < this.maxVideos) {
- options.push('选择视频');
- }
- if (this.selectedDocs.length < this.maxDocs) {
- options.push('选择文档');
- }
- if (options.length === 0) {
- uni.showToast({
- title: '已达上传上限',
- icon: 'none'
- });
- return;
- }
- uni.showActionSheet({
- itemList: options,
- success: (res) => {
- const selected = options[res.tapIndex];
- if (selected === '选择图片') {
- this.chooseImage();
- } else if (selected === '选择视频') {
- this.chooseVideo();
- } else if (selected === '选择文档') {
- this.chooseDoc();
- }
- }
- });
- },
- // 切换音频播放状态
- toggleAudio(message) {
- if (!message.audioData) {
- uni.showToast({
- title: '没有可用的音频',
- icon: 'none'
- });
- return;
- }
- if (message.audioData.isPlaying) {
- this.stopAudio(message);
- } else {
- this.playAudio(message.audioData.base64);
- }
- },
- // 播放音频
- playAudio(audioBase64) {
- try {
- // 先停止当前正在播放的音频
- this.stopCurrentAudio();
- // 创建新的音频上下文
- const innerAudioContext = uni.createInnerAudioContext();
- this.currentAudioContext = innerAudioContext;
- // 设置音频源
- innerAudioContext.src = audioBase64;
- // 监听播放错误
- innerAudioContext.onError((res) => {
- console.error('音频播放错误:', res.errMsg);
- uni.showToast({
- title: '音频播放失败',
- icon: 'none'
- });
- this.stopCurrentAudio();
- });
- // 播放结束后的处理
- innerAudioContext.onEnded(() => {
- // 只调用 stop,不销毁实例
- if (this.currentAudioContext) {
- this.currentAudioContext.stop();
- }
- });
- // 开始播放
- innerAudioContext.play();
- } catch (error) {
- console.error('播放音频失败:', error);
- this.stopCurrentAudio();
- }
- },
- // 停止音频
- stopAudio(message) {
- if (this.currentAudioContext) {
- this.currentAudioContext.stop();
- this.currentAudioContext.destroy();
- this.currentAudioContext = null;
- }
- message.audioData.isPlaying = false;
- message.audioData.progress = 0;
- },
- // 组件销毁时清理音频
- beforeDestroy() {
- this.stopCurrentAudio();
- },
- // 添加选择文档方法
- chooseDoc() {
- if (this.selectedDocs.length >= this.maxDocs) {
- uni.showToast({
- title: `最多只能上传${this.max +'Docs'}个文档`,
- icon: 'none'
- });
- return;
- }
- // #ifdef H5
- // H5环境下使用input标签选择文件
- const input = document.createElement('input');
- input.type = 'file';
- input.accept = '.doc,.docx,.pdf,.txt';
- input.onchange = (event) => {
- const file = event.target.files[0];
- if (file) {
- this.uploadSingleDoc(file);
- }
- };
- input.click();
- // #endif
- // #ifdef APP-PLUS || MP-WEIXIN
- // 小程序和APP环境下使用选择文件API
- uni.chooseMessageFile({
- count: 1,
- type: 'file',
- extension: ['doc', 'docx', 'pdf', 'txt'],
- success: (res) => {
- const tempFile = res.tempFiles[0];
- this.uploadSingleDoc(tempFile);
- }
- });
- // #endif
- },
- // 添加上传单个文档方法
- async uploadSingleDoc(file) {
- try {
- uni.showLoading({
- title: '正在上传文档...',
- mask: true
- });
- const uploadResult = await uni.uploadFile({
- url: `${this.apiUrl}/upload/file`,
- filePath: file.path || file,
- name: 'file',
- header: {
- 'Content-Type': 'multipart/form-data'
- }
- });
- if (uploadResult.statusCode === 200) {
- const response = JSON.parse(uploadResult.data);
- const fileUrl = response.data.fileUrl;
- // 添加到已上传文档数组
- this.uploadedDocs.push({
- url: fileUrl,
- name: file.name || '文档'
- });
- // 更新预览文档数组
- this.selectedDocs.push({
- name: file.name || '文档',
- path: file.path || file
- });
- uni.hideLoading();
- uni.showToast({
- title: '上传成功',
- icon: 'success'
- });
- } else {
- throw new Error('Upload failed');
- }
- } catch (error) {
- console.error('文档上传失败:', error);
- uni.hideLoading();
- uni.showToast({
- title: '上传失败',
- icon: 'none'
- });
- }
- },
- // 添加移除文档方法
- removeDoc(index) {
- this.selectedDocs.splice(index, 1);
- this.uploadedDocs.splice(index, 1);
- },
- /* 打开弹窗 */
- async showVoiceSettings() {
- try {
- const response = await uni.request({
- url: `${this.apiUrl}/chatbot/list_voices`,
- method: 'GET'
- });
- if (response.statusCode === 200 && response.data.code === 200) {
- this.voicesData = response.data.data.voices;
- this.languageOptions = Object.keys(this.voicesData);
- // 设置默认值
- if (!this.voiceSettings.language || !this.voicesData[this.voiceSettings.language]) {
- this.voiceSettings.language = this.languageOptions[0];
- }
- // 初始化 rate 和 volume 的值
- if (!this.voiceSettings.rate) {
- this.voiceSettings.rate = '+10%';
- }
- if (!this.voiceSettings.volume) {
- this.voiceSettings.volume = '+20%';
- }
- this.updateVoiceOptions();
- // 打开弹窗
- this.$refs.voiceSettingsPopup.open();
- }
- } catch (error) {
- uni.showToast({
- title: '获取语音配置失败',
- icon: 'none'
- });
- }
- },
- // 更新声音选项
- updateVoiceOptions() {
- this.currentVoices = this.voicesData[this.voiceSettings.language] || [];
- // 如果当前选择的声音不在新的选项中,重置选择
- if (!this.currentVoices.find(v => v.name === this.voiceSettings.voice_name)) {
- if (this.currentVoices.length > 0) {
- this.voiceSettings.voice_name = this.currentVoices[0].name;
- this.voiceSettings.gender = this.currentVoices[0].gender;
- this.updateStyleOptions(this.currentVoices[0]);
- }
- }
- },
- // 更新风格选项
- updateStyleOptions(voice) {
- this.styleOptions = voice.style || [];
- if (!this.styleOptions.includes(this.voiceSettings.style)) {
- this.voiceSettings.style = this.styleOptions[0] || '';
- }
- },
- // 处理语言变化
- handleLanguageChange(e) {
- const newLanguage = this.languageOptions[e.detail.value];
- this.voiceSettings.language = newLanguage;
- this.updateVoiceOptions();
- },
- // 处理声音名称变化
- handleVoiceNameChange(e) {
- const selectedVoice = this.currentVoices[e.detail.value];
- this.voiceSettings.voice_name = selectedVoice.name;
- this.voiceSettings.gender = selectedVoice.gender;
- this.updateStyleOptions(selectedVoice);
- },
- // 处理风格变化
- handleStyleChange(e) {
- this.voiceSettings.style = this.styleOptions[e.detail.value];
- },
- // 保存配置
- async saveVoiceSettings() {
- try {
- const response = await uni.request({
- url: this.apiUrl + '/switch_voice_config', // 确保使用正确的接口地址
- method: 'POST',
- data: {
- language: this.voiceSettings.language,
- voice_name: this.voiceSettings.voice_name,
- gender: this.voiceSettings.gender,
- style: this.voiceSettings.style,
- rate: this.voiceSettings.rate,
- volume: this.voiceSettings.volume
- },
- header: {
- 'content-type': 'application/x-www-form-urlencoded'
- }
- });
- if (response.statusCode === 200 && response.data.code === 200) {
- uni.showToast({
- title: '设置保存成功',
- icon: 'success'
- });
- this.closeVoiceSettings();
- } else {
- throw new Error(response.data.msg || '保存失败');
- }
- } catch (error) {
- console.error('保存设置失败:', error); // 添加错误日志
- uni.showToast({
- title: error.message || '保存失败,请重试',
- icon: 'none'
- });
- }
- },
- // 添加关闭弹窗方法
- closeVoiceSettings() {
- this.$refs.voiceSettingsPopup.close();
- },
- // 添加弹窗状态改变处理方法
- handlePopupChange(e) {
- if (e.show) {
- // 弹窗打开时
- uni.hideTabBar(); // 隐藏底部导航栏
- // #ifdef H5
- // 禁止页面滚动
- document.body.style.overflow = 'hidden';
- // #endif
- } else {
- // 弹窗关闭时
- uni.showTabBar(); // 显示底部导航栏
- // #ifdef H5
- // 恢复页面滚动
- document.body.style.overflow = 'auto';
- // #endif
- }
- }
- },
- // updated() {
- // const messagesContainer = this.$el.querySelector(".messages");
- // messagesContainer.scrollTop = messagesContainer.scrollHeight;
- // },
- };
- </script>
- <style scoped>
- /* 这里引入 ChatBox.css 的内容 */
- /* @import '/static/css/ChatBox.css'; */
- .chat-container {
- display: flex;
- flex-direction: column;
- height: 100vh;
- /* 或者按照实际需要调整高度 */
- }
- .messages {
- width: 90%;
- /* 设置消息列表宽度为屏幕宽度的 80% */
- max-width: 90%;
- /* 限制最大宽度,避免超出视口 */
- margin: 0 auto;
- /* 上下保持原有的 margin,左右自动调整以居中 */
- overflow-y: auto;
- /* 如果消息太多,允许滚动 */
- height: calc(100vh - 120px);
- /* 高度需要根据输入框和其元素的高度调整 */
- padding: 10px 10px 0;
- /* 或你希望的内边距大小 */
- }
- .message {
- display: flex;
- padding: 10px;
- align-items: flex-start;
- }
- .avatar-container {
- display: flex;
- flex-direction: column;
- align-items: center;
- min-width: 50px;
- /* 确保头像容器有固定宽度 */
- }
- .messages li {
- display: flex;
- align-items: flex-start;
- /* 这将确保所有子素对到容器的顶部 */
- margin-bottom: 10px;
- }
- .avatar-container {
- display: flex;
- /* flex-direction: column; */
- flex-direction: row;
- margin-right: 10px;
- }
- .avatar {
- width: 30px;
- height: 30px;
- border-radius: 50%;
- margin-bottom: 5px;
- }
- .sender-name {
- margin-left: 15px;
- font-size: 12px;
- color: #666;
- margin-top: 2px;
- }
- .message {
- display: flex;
- align-items: flex-start;
- flex-direction: column;
- /* 增加消息间距 */
- }
- .user-avatar {
- /* background-image: url('/static/用户.png'); */
- /* 替换为您的 GIF 文件路径 */
- background-size: cover;
- /* 确保 GIF 覆盖整个头像区域 */
- background-repeat: no-repeat;
- /* 防止 GIF 重复 */
- background-position: center;
- /* 将 GIF 居中 */
- border-radius: 50%;
- }
- .bot-avatar {
- background-image: url('/static/机器人.png');
- /* 替换为您的 GIF 文件路径 */
- background-size: cover;
- /* 确保 GIF 覆盖整个头像区域 */
- background-repeat: no-repeat;
- /* 防止 GIF 重复 */
- background-position: center;
- /* 将 GIF 居中 */
- }
- .message-content {
- background-color: #f0f0f0;
- /* 消息背景 */
- padding-left: 20px;
- /* 上下右内边距 */
- padding-right: 10px;
- /* 上下左右的内边距 */
- padding-top: 10px;
- /* 上下左右的内边距 */
- padding-bottom: 10px;
- /* 上下左右的内边距 */
- max-width: calc(90% - 15px);
- /* 计算头像和间距 */
- border-radius: 10px 10px 10px 10px;
- /* 边框圆角 */
- margin-bottom: 10px;
- /* 和下一条消息之���的间距 */
- /* 消息内容样式 */
- display: flex;
- flex-direction: column;
- /* 排列文本 */
- margin-left: 30px;
- margin-top: 0;
- font-size: 12px;
- }
- .message-text {
- margin: 0;
- white-space: normal;
- /* 确保文本会换行 */
- word-wrap: break-word;
- /* 长单词或 URL 会被断开以适应容器宽度 */
- }
- .input-container {
- position: fixed;
- bottom: 0;
- left: 0;
- width: 96%;
- background: white;
- padding: 5px 10px;
- box-shadow: 0px -2px 5px rgba(0, 0, 0, 0.1);
- }
- .input-wrapper {
- display: flex;
- align-items: center;
- gap: 10px;
- }
- .input-textarea {
- flex: 1;
- background: #f5f5f5;
- border-radius: 20px;
- padding: 8px 15px;
- min-height: 20px;
- max-height: 80px;
- font-size: 14px;
- }
- .send-btn {
- min-width: 60px;
- height: 36px;
- line-height: 36px;
- font-size: 14px;
- background: #1296db;
- color: white;
- border-radius: 18px;
- padding: 0 15px;
- margin: 0;
- }
- .sender-name {
- font-weight: bold;
- color: #333;
- font-size: 12px;
- margin-bottom: 5px;
- }
- .btn {
- border: none;
- background-color: #1296db;
- color: #fff;
- }
- .message-content :deep(p) {
- font-size: 12px !important;
- margin: 5px 0 10px;
- padding: 0;
- line-height: 22px;
- font-weight: inherit;
- }
- .message-content :deep(ol) {
- padding-bottom: 10px;
- }
- .message-content :deep(.source-section) {
- margin: 20px 0 3px;
- color: #333;
- font-size: 16px;
- }
- .message-content :deep(ol li) {
- padding-top: 3px;
- }
- .message-content :deep(ol li a) {
- font-size: 14px;
- color: #1296db;
- }
- /* 添加资料来源相关的新样式 */
- .source-section {
- border-top: 1px solid #e5e5e5;
- padding-top: 10px;
- margin-top: 10px;
- }
- .source-title {
- font-size: 14px;
- color: #666;
- margin-bottom: 8px;
- }
- .source-links {
- display: flex;
- flex-direction: column;
- gap: 5px;
- }
- .source-link {
- color: #1296db;
- font-size: 12px;
- cursor: pointer;
- /* text-decoration: underline; */
- }
- .source-link:hover {
- opacity: 0.8;
- }
- /* 添加新建对话按钮样式 */
- .new-chat-btn {
- padding: 0px 20px;
- display: flex;
- justify-content: flex-start;
- background-color: #fff;
- }
- .btn-new {
- background-color: #1296db;
- color: #fff;
- font-size: 14px;
- border-radius: 5px;
- border: none;
- height: 35px;
- margin: 0;
- }
- /* 上传图标 */
- .upload-img {
- width: 30px;
- height: 30px;
- }
- .image-upload-area {
- width: 100%;
- white-space: nowrap;
- margin-bottom: 10px;
- padding: 5px;
- }
- .image-list {
- display: inline-flex;
- gap: 10px;
- }
- .image-preview {
- width: 75px;
- height: 75px;
- position: relative;
- flex-shrink: 0;
- border-radius: 8px;
- /* overflow: hidden; */
- }
- .preview-img {
- width: 100%;
- height: 100%;
- object-fit: cover;
- }
- .delete-btn {
- position: absolute;
- top: 0px;
- right: 0px;
- width: 20px;
- height: 20px;
- background: rgba(0, 0, 0, 0.5);
- border-radius: 50%;
- display: flex;
- align-items: center;
- justify-content: center;
- z-index: 5;
- }
- .delete-icon {
- color: white;
- font-size: 18px;
- }
- .upload-btn {
- width: 75px;
- height: 75px;
- border: 2px dashed #ddd;
- border-radius: 8px;
- display: flex;
- align-items: center;
- justify-content: center;
- flex-shrink: 0;
- }
- .upload-icon {
- width: 30px;
- height: 30px;
- opacity: 0.5;
- }
- /* 添加消息中图片的样式 */
- .message-images {
- display: flex;
- flex-wrap: wrap;
- gap: 5px;
- margin-top: 5px;
- }
- .message-image {
- width: 120px;
- height: 120px;
- border-radius: 8px;
- object-fit: cover;
- }
- /* 添加视频相关样式 */
- .upload-options {
- display: flex;
- justify-content: center;
- align-items: center;
- }
- .upload-icon {
- width: 24px;
- height: 24px;
- opacity: 0.7;
- }
- .video-preview {
- width: 120px;
- height: 120px;
- position: relative;
- flex-shrink: 0;
- }
- .video-thumbnail {
- width: 100%;
- height: 100%;
- border-radius: 8px;
- object-fit: cover;
- }
- .play-icon {
- position: absolute;
- top: 50%;
- left: 50%;
- transform: translate(-50%, -50%);
- width: 30px;
- height: 30px;
- opacity: 0.8;
- }
- /* 添加视频预览相关样式 */
- .video-preview-container {
- width: 100%;
- height: 100%;
- position: relative;
- display: flex;
- align-items: center;
- justify-content: center;
- background-color: #f5f5f5;
- border-radius: 8px;
- }
- .play-icon {
- position: absolute;
- width: 24px;
- height: 24px;
- opacity: 0.8;
- }
- /* 添加音频控件样式 */
- .audio-controls {
- display: flex;
- align-items: center;
- margin-top: 8px;
- gap: 10px;
- }
- .audio-btn {
- width: 30px;
- height: 30px;
- border-radius: 50%;
- /* background: #1296db; */
- display: flex;
- align-items: center;
- justify-content: center;
- cursor: pointer;
- }
- .audio-icon {
- width: 16px;
- height: 16px;
- }
- .audio-progress {
- font-size: 12px;
- color: #666;
- }
- /* 更新消息内容样式 */
- .message-content {
- display: flex;
- flex-direction: column;
- background-color: #f0f0f0;
- padding: 10px 15px;
- border-radius: 10px;
- margin-left: 30px;
- max-width: calc(90% - 15px);
- font-size: 12px;
- }
- /* 添加文档预览相关样式 */
- .doc-preview {
- width: 75px;
- height: 75px;
- position: relative;
- flex-shrink: 0;
- border-radius: 8px;
- overflow: hidden;
- background-color: #f5f5f5;
- }
- .doc-preview-container {
- width: 100%;
- height: 100%;
- display: flex;
- flex-direction: column;
- align-items: center;
- justify-content: center;
- padding: 5px;
- }
- .doc-icon {
- width: 30px;
- height: 30px;
- margin-bottom: 5px;
- }
- .doc-name {
- font-size: 10px;
- color: #666;
- text-align: center;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- width: 100%;
- padding: 0 5px;
- }
- /* 设置图标样式 */
- .settings-icon {
- width: 24px;
- height: 24px;
- margin-bottom: 10px;
- opacity: 0.7;
- }
- /* 设置弹窗样式 */
- .settings-popup {
- background: #fff;
- border-radius: 12px;
- width: 80vw;
- padding: 20px;
- position: relative;
- z-index: 999;
- /* 确保弹窗在最上层 */
- }
- .settings-header {
- display: flex;
- justify-content: space-between;
- align-items: center;
- margin-bottom: 20px;
- }
- .settings-title {
- font-size: 18px;
- font-weight: bold;
- }
- .close-btn {
- font-size: 24px;
- color: #999;
- }
- .settings-content {
- max-height: 60vh;
- overflow-y: auto;
- }
- .settings-item {
- margin-bottom: 15px;
- }
- .item-label {
- display: block;
- margin-bottom: 5px;
- color: #666;
- font-size: 14px;
- }
- .picker-value {
- height: 35px;
- line-height: 35px;
- padding: 0 10px;
- background: #f5f5f5;
- border-radius: 5px;
- }
- input {
- height: 35px;
- padding: 0 10px;
- background: #f5f5f5;
- border-radius: 5px;
- }
- .save-btn {
- margin-top: 20px;
- background: #1296db;
- color: #fff;
- border: none;
- border-radius: 5px;
- height: 40px;
- line-height: 40px;
- }
- /* 添加遮罩层样式 */
- :deep(.uni-popup__mask) {
- z-index: 998;
- }
- /* 更新弹窗样式以适应不同设备 */
- .settings-popup {
- background: #fff;
- border-radius: 12px;
- width: 80vw;
- padding: 20px;
- position: relative;
- z-index: 999;
- /* 确保弹窗在最上层 */
- }
- .settings-content {
- max-height: 60vh;
- /* 限制内容最大高度 */
- overflow-y: auto;
- }
- /* 确保遮罩层在正确的层级 */
- :deep(.uni-popup__mask) {
- z-index: 998;
- }
- /* 适配小屏幕设备 */
- @media screen and (max-width: 375px) {
- .settings-popup {
- width: 90vw;
- padding: 15px;
- }
- .settings-title {
- font-size: 16px;
- }
- .item-label {
- font-size: 13px;
- }
- }
- /* 适配大屏幕设备 */
- @media screen and (min-width: 768px) {
- .settings-popup {
- width: 60vw;
- max-width: 500px;
- }
- }
- .set_btn {
- display: flex;
- flex-direction: column;
- /* 设置为竖向排列 */
- gap: 10px;
- /* 按钮之间的间距 */
- justify-content: center;
- align-items: center;
- }
- </style>
|