12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570 |
- <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.images && message.images.length > 0">
- <view class="message-images">
- <image v-for="(img, index) in message.images" :key="index" :src="img" class="chat-image"
- mode="aspectFill" @tap="previewImage(message.images, index)" />
- </view>
- </template>
- <!-- 视频展示部分 -->
- <template v-if="message.videos && message.videos.length > 0">
- <view class="message-videos">
- <view v-for="(video, index) in message.videos" :key="index"
- class="video-thumbnail-container">
- <!-- 视频封面图 -->
- <image :src="video + '?x-oss-process=video/snapshot,t_0,f_jpg'" class="chat-image"
- mode="aspectFill" @tap="previewVideoThumbnail(message.videos, index)" />
- </view>
- </view>
- </template>
- <!-- 文档展示部分 -->
- <template v-if="message.docs && message.docs.length > 0">
- <view class="message-docs">
- <view v-for="(doc, index) in message.docs" :key="index" class="doc-preview">
- <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>
- </view>
- </template>
- <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 uploadedVideos" :key="'vid-'+index">
- <view class="video-preview-container">
- <image :src="video.url + '?x-oss-process=video/snapshot,t_0,f_jpg'" 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: [], // 当前选择的声音可用的风格
- videoThumbnails: {}, // 存储视频封面
- /* 文档类型 */
- docTypeMap: {
- 'pdf': 'PDF文档',
- 'doc': 'Word文档',
- 'docx': 'Word文档',
- 'txt': '文本文件',
- 'xls': 'Excel表格',
- 'xlsx': 'Excel表格',
- 'ppt': 'PPT演示',
- 'pptx': 'PPT演示'
- },
- };
- },
- 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'
- },
- timeout: 180000, // 设置30秒超时,默认是60秒
- data: {
- message: message,
- image_urls: userMessage.images,
- video_urls: userMessage.videos, // 添加视频URL到请求
- documents: 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'],
- maxDuration: 60, // 限制视频时长最大60秒
- success: async (res) => {
- // 检查视频大小(res.size 单位为字节)
- const sizeInMB = res.size / (1024 * 1024);
- if (sizeInMB > 10) {
- uni.showToast({
- title: '视频大小不能超过10MB',
- icon: 'none'
- });
- return;
- }
-
- await this.uploadSingleVideo(res.tempFilePath, res.size);
- },
- fail: (err) => {
- console.error('选择视频失败:', err);
- uni.showToast({
- title: '选择视频失败',
- icon: 'none'
- });
- }
- });
- },
- // 修改上传单个视频方法
- async uploadSingleVideo(tempFilePath, fileSize) {
- try {
- // 再次检查文件大小
- if (fileSize && fileSize / (1024 * 1024) > 10) {
- throw new Error('视频大小不能超过10MB');
- }
- 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'
- },
- formData: {
- // 可以添加额外的表单数据
- fileType: 'video',
- maxSize: 10 * 1024 * 1024 // 10MB in bytes
- }
- });
- if (uploadResult.statusCode === 200) {
- const response = JSON.parse(uploadResult.data);
-
- // 检查服务器响应
- if (response.code === 413 || response.message?.includes('大小超过限制')) {
- throw new Error('视频大小超过限制');
- }
- const fileUrl = response.data.fileUrl;
- // 添加到已上传视频数组
- this.uploadedVideos.push({
- url: fileUrl,
- size: fileSize
- });
- // 更新预览视频数组
- 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: error.message || '上传失败',
- icon: 'none',
- duration: 2000
- });
- }
- },
- // 添加获取文件大小的辅助方法
- formatFileSize(bytes) {
- if (bytes === 0) return '0 B';
- const k = 1024;
- const sizes = ['B', 'KB', 'MB', 'GB'];
- const i = Math.floor(Math.log(bytes) / Math.log(k));
- return (bytes / Math.pow(k, i)).toFixed(2) + ' ' + sizes[i];
- },
- // 修改移除视频方法
- 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.maxDocs}个文档`,
- icon: 'none'
- });
- return;
- }
- this.chooseFromChat();
- /* // 根据平台显示不同的选项
- const options = ['从聊天记录选择', '从文件管理器选择'];
-
- uni.showActionSheet({
- itemList: options,
- success: (res) => {
- if (res.tapIndex === 0) {
- // 从聊天记录选择
-
- } else {
- // 从文件管理器选择
- this.chooseFromFileSystem();
- }
- }
- }); */
- },
- // 添加从聊天记录选择文档的方法
- chooseFromChat() {
- // #ifdef MP-WEIXIN
- uni.chooseMessageFile({
- count: 1,
- type: 'file',
- extension: ['doc', 'docx', 'pdf', 'txt'],
- success: (res) => {
- const tempFile = res.tempFiles[0];
- this.uploadSingleDoc(tempFile);
- }
- });
- // #endif
- // #ifdef APP-PLUS
- plus.gallery.pick((path) => {
- this.uploadSingleDoc({
- path: path,
- name: path.substring(path.lastIndexOf('/') + 1)
- });
- }, (error) => {
- uni.showToast({
- title: '选择文件失败',
- icon: 'none'
- });
- }, {
- filter: 'document'
- });
- // #endif
- },
- // 修改 chooseFromFileSystem 方法
- async chooseFromFileSystem() {
- // #ifdef MP-WEIXIN
- // 微信小程序使用 wx.chooseMessageFile API
- uni.chooseMessageFile({
- count: 1, // 可选择文件的数量
- type: 'file', // 选择文件类型
- extension: ['doc', 'docx', 'pdf', 'txt'], // 允许的文件类型
- success: (res) => {
- if (res.tempFiles && res.tempFiles.length > 0) {
- const file = res.tempFiles[0];
- this.uploadSingleDoc({
- path: file.path,
- name: file.name
- });
- }
- },
- fail: (err) => {
- console.error('选择文件失败:', err);
- uni.showToast({
- title: '选择文件失败',
- icon: 'none'
- });
- }
- });
- // #endif
- // #ifdef APP-PLUS
- // 保持原有的 APP 端代码
- try {
- if (uni.getSystemInfoSync().platform === 'android') {
- // ... 原有的 Android 代码 ...
- }
- } catch (error) {
- console.error('File picker error:', error);
- uni.showToast({
- title: '选择文件失败',
- icon: 'none',
- duration: 2000
- });
- }
- // #endif
- },
- // 修改 uploadSingleDoc 方法以处理不同格式的文件路径
- async uploadSingleDoc(file) {
- try {
- uni.showLoading({
- title: '正在上传文档...',
- mask: true
- });
- let uploadFile;
- // #ifdef APP-PLUS
- if (typeof file === 'object' && file.path) {
- // 处理 Android/iOS 返回的文件对象
- uploadFile = {
- path: file.path,
- name: file.name
- };
- }
- // #endif
- // #ifdef MP-WEIXIN
- if (file.path) {
- uploadFile = {
- path: file.path,
- name: file.name
- };
- }
- // #endif
- // #ifdef H5
- if (file instanceof File) {
- uploadFile = file;
- }
- // #endif
- if (!uploadFile) {
- throw new Error('Invalid file format');
- }
- const uploadResult = await uni.uploadFile({
- url: `${this.apiUrl}/upload/file`,
- filePath: uploadFile.path || uploadFile,
- 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: uploadFile.name || '文档'
- });
- // 更新预览文档数组
- this.selectedDocs.push({
- name: uploadFile.name || '文档',
- path: uploadFile.path || uploadFile
- });
- 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
- }
- },
- // 添加图片预览方法
- previewImage(images, current) {
- uni.previewImage({
- urls: images,
- current: images[current]
- });
- },
- // 添加权限检查方法
- async checkAndRequestPermissions() {
- // #ifdef APP-PLUS
- if (uni.getSystemInfoSync().platform === 'android') {
- const permission = 'android.permission.READ_EXTERNAL_STORAGE';
- const result = await new Promise((resolve) => {
- plus.android.requestPermissions(
- [permission],
- function(resultObj) {
- resolve(resultObj.granted.indexOf(permission) >= 0);
- },
- function(error) {
- console.error('Error requesting permissions:', error);
- resolve(false);
- }
- );
- });
- if (!result) {
- uni.showToast({
- title: '需要存储权限才能选择文件',
- icon: 'none'
- });
- return false;
- }
- return true;
- }
- // #endif
- return true;
- },
- // 修改文件选择方法
- async chooseFromFileSystem() {
- // 先检查权限
- const hasPermission = await this.checkAndRequestPermissions();
- if (!hasPermission) {
- return;
- }
- // 原有的文件选择代码...
- },
- // 获取文档类型的中文释义
- getDocumentType(filename) {
- const extension = filename.split('.').pop().toLowerCase();
- return this.docTypeMap[extension] || '未知文件';
- },
- // 格式化文件名显示
- formatFileName(filename) {
- // 如果文件名过长,截断显示
- const maxLength = 10;
- const name = filename.split('.')[0]; // 获取文件名(不含扩展名)
- if (name.length > maxLength) {
- return name.substring(0, maxLength) + '...';
- }
- return name;
- },
- // 预览视频缩略图
- previewVideoThumbnail(videos, current) {
- // 生成所有视频的缩略图URL数组
- const thumbnailUrls = videos.map(video => video + '?x-oss-process=video/snapshot,t_0,f_jpg');
- uni.previewImage({
- urls: thumbnailUrls,
- current: thumbnailUrls[current],
- longPressActions: {
- itemList: ['发送给朋友', '保存图片', '收藏'],
- success: function(data) {
- console.log('选中了第' + (data.tapIndex + 1) + '个按钮');
- }
- }
- });
- },
- },
- // 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;
- word-break: break-all;
- }
- .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;
- margin-bottom: 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;
- }
- /* 添加图片聊天相关样式 */
- .message-images {
- margin-bottom: 8px;
- }
- .chat-image {
- width: 120px;
- height: 120px;
- border-radius: 8px;
- margin-bottom: 5px;
- }
- /* 视频样式 */
- .message-videos {
- margin-bottom: 8px;
- }
- .video-thumbnail-container {
- position: relative;
- width: 120px;
- height: 120px;
- margin-bottom: 5px;
- }
- .hidden-video {
- position: absolute;
- width: 1px;
- height: 1px;
- opacity: 0;
- pointer-events: none;
- }
- .play-icon-overlay {
- position: absolute;
- top: 0;
- left: 0;
- right: 0;
- bottom: 0;
- display: flex;
- align-items: center;
- justify-content: center;
- background-color: rgba(0, 0, 0, 0.2);
- border-radius: 8px;
- }
- .play-icon {
- width: 40px;
- height: 40px;
- opacity: 0.8;
- }
- /* 调整视频缩略图样式 */
- .chat-image {
- width: 120px;
- height: 120px;
- border-radius: 8px;
- object-fit: cover;
- }
- /* 文档展示 */
- .message-docs {
- display: flex;
- flex-wrap: wrap;
- gap: 5px;
- margin-top: 5px;
- }
- .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;
- }
- </style>
|