2 lines
17 KiB
JavaScript
2 lines
17 KiB
JavaScript
"use strict";const e=require("../../common/vendor.js");require("../../common/libraries/request.js");const t=require("../../common/store/useWeAppAuthStore.js");require("../../common/store/useWorkStore.js");const o=require("../../common/libraries/upload.js");if(require("../../gen/Apis.js"),require("../../common/libraries/setTabBar.js"),require("../../common/libraries/apiLoading.js"),!Array){e.resolveComponent("uni-icons")()}Math;const a=e.defineComponent({__name:"chat",setup(a){e.dayjs.extend(e.relativeTime),e.dayjs.locale("zh-cn");const s=t.useWeAppAuthStore(),n=e.ref(""),l=e.ref([]),r=e.ref(!1),i=e.ref([{role:"ai",content:"您好!我是物业客服,有什么可以帮助您的吗?",quickQuestions:[]}]),u=e.ref(!1),c=e.ref("正在输入中...");let m=null,g=e.ref(!1);const d="https://kf-api-test.linyikj.com.cn",p=e.ref(1),v=e.ref(10),y=e.ref(!0),_=e.ref(!1),f=e.ref(""),h=e.ref(0),k=e.ref([]),S=e.ref(""),q=e.ref(!0),C=e.ref(0);e.onPageScroll((e=>{console.log(e.scrollTop,C.value),C.value>0&&C.value>e.scrollTop&&(q.value=!1),C.value-e.scrollTop<50&&(q.value=!0),(0===C.value||C.value<e.scrollTop)&&(C.value=e.scrollTop)}));const w=(t,o)=>{e.index.previewImage({current:t,urls:o})},A=t=>{t?e.index.setClipboardData({data:t,success:()=>{e.index.showToast({title:"复制成功",icon:"success"})},fail:()=>{e.index.showToast({title:"复制失败",icon:"none"})}}):e.index.showToast({title:"暂无内容可复制",icon:"none"})},x=t=>{if(!t)return"";try{const o=e.dayjs(t);return o.isValid()?o.fromNow():""}catch(o){return console.error("时间格式化错误:",o),""}},T=()=>{e.nextTick$1((()=>{e.index.pageScrollTo({scrollTop:999999,duration:300})}))},b=async(t=1)=>{var o,a;const n=null==(a=null==(o=s.data)?void 0:o.user)?void 0:a.phone;if(n){if(!_.value)try{_.value=!0;const o=(t-1)*v.value;h.value=o,console.log("分页信息 - 页码:",t,"每页数量:",v.value,"计算出的offset:",o);const a=await e.index.request({url:`${d}/api/public/customer/init`,method:"POST",data:{platform:"property",platform_user_id:n,limit:v.value,offset:o}});if(200===a.statusCode){const s=a.data;let n=[];s.conversation&&s.conversation.id?(f.value=s.conversation.id,console.log("获取到会话ID:",f.value)):s.conversation_id?(f.value=s.conversation_id,console.log("获取到会话ID:",f.value)):s.conversations&&s.conversations.id&&(f.value=s.conversations.id,console.log("获取到会话ID:",f.value)),s.messages&&Array.isArray(s.messages)?(n=s.messages.map((e=>{const t={role:"customer"===e.sender_type?"user":"ai",content:e.message||e.content||"",created_at:e.created_at||e.timestamp||(new Date).toISOString()};e.message_type&&(t.message_type=e.message_type);let o=null;return e.image_url&&Array.isArray(e.image_url)?o=e.image_url:e.images&&Array.isArray(e.images)?o=e.images:e.metadata&&e.metadata.image_url&&Array.isArray(e.metadata.image_url)&&(o=e.metadata.image_url),o&&(t.image_url=o,t.images=o),e.metadata&&(t.metadata=e.metadata),t})),console.log("从messages字段获取到历史记录:",n.length)):s.data&&Array.isArray(s.data)?(n=s.data.map((e=>{const t={role:"customer"===e.sender_type?"user":"ai",content:e.message||e.content||"",created_at:e.created_at||e.timestamp||(new Date).toISOString()};e.message_type&&(t.message_type=e.message_type);let o=null;return e.image_url&&Array.isArray(e.image_url)?o=e.image_url:e.images&&Array.isArray(e.images)?o=e.images:e.metadata&&e.metadata.image_url&&Array.isArray(e.metadata.image_url)&&(o=e.metadata.image_url),o&&(t.image_url=o,t.images=o),e.metadata&&(t.metadata=e.metadata),t})),console.log("从data字段获取到历史记录:",n.length)):s.list&&Array.isArray(s.list)&&(n=s.list.map((e=>{const t={role:"customer"===e.sender_type?"user":"ai",content:e.message||e.content||"",created_at:e.created_at||e.timestamp||(new Date).toISOString()};e.message_type&&(t.message_type=e.message_type);let o=null;return e.image_url&&Array.isArray(e.image_url)?o=e.image_url:e.images&&Array.isArray(e.images)?o=e.images:e.metadata&&e.metadata.image_url&&Array.isArray(e.metadata.image_url)&&(o=e.metadata.image_url),o&&(t.image_url=o,t.images=o),e.metadata&&(t.metadata=e.metadata),t})),console.log("从list字段获取到历史记录:",n.length)),1===t?(n.length>0?(i.value=n,console.log("第一页历史记录已加载,总共",n.length,"条消息")):(console.log("没有历史记录"),i.value=[]),e.nextTick$1((()=>{if(k.value.length>0){const e={role:"ai",content:"您好!我是物业客服,有什么可以帮助您的吗?",quickQuestions:k.value,created_at:(new Date).toISOString()};i.value.push(e),console.log("[Customer] 获取历史记录成功后,在历史记录后面push新开场白消息"),T()}}))):n.length>0&&setTimeout((()=>{i.value.unshift(...n),console.log("加载更多历史记录,新增",n.length,"条消息,总共",i.value.length,"条")}),300);const l=s.total||s.count||s.total_count||0;y.value=l>i.value.length,p.value=t,t>1&&!y.value&&(console.log("分页加载完成,当前页:",t,"hasMore:",y.value,"展示开场白"),setTimeout((()=>{W(!0)}),500)),console.log("第",t,"页数据加载完成,offset:",o,", limit:",v.value,", 总数据:",l,", 当前已加载:",i.value.length,", 是否有更多:",y.value),1===t&&(setTimeout((()=>{T()}),100),console.log("[Customer] 历史记录加载完成,开始建立WebSocket连接"),O())}else console.error("获取历史记录失败,状态码:",a.statusCode)}catch(l){console.error("获取历史记录异常:",l)}finally{_.value=!1}}else console.log("用户未登录,无法获取历史记录")};e.onPullDownRefresh((async()=>{if(_.value||!y.value)return console.log("正在加载或没有更多数据"),void e.index.stopPullDownRefresh();console.log("触发下拉分页,加载更多历史记录");const t=p.value+1;try{await b(t),await new Promise((e=>setTimeout(e,500)))}catch(o){console.error("加载历史记录失败:",o)}finally{e.index.stopPullDownRefresh()}}));const O=()=>{if(!m)try{const t="wss://kf-api-test.linyikj.com.cn/ws/socket.io/?EIO=4&transport=websocket";console.log("正在建立Socket.IO连接"),console.log("连接URL:",t),m=e.index.connectSocket({url:t,header:{"content-type":"application/json"}}),e.index.onSocketOpen((t=>{console.log("[Customer] WebSocket connected",t),g.value=!0;e.index.sendSocketMessage({data:'40/customer,{"jwt":""}',success:()=>{console.log("[Customer] Socket.IO连接包发送成功"),f.value&&setTimeout((()=>{const t=`42/customer,["join_conversation",{"conversation_id":"${f.value}"}]`;console.log("[Customer] 加入会话房间:",t),e.index.sendSocketMessage({data:t,success:()=>{console.log("[Customer] 成功加入会话房间")},fail:e=>{console.error("[Customer] 加入会话房间失败:",e)}})}),200)},fail:e=>{console.error("[Customer] Socket.IO连接包发送失败:",e)}})})),e.index.onSocketError((e=>{console.error("[Customer] WebSocket error:",e),g.value=!1,m=null})),e.index.onSocketClose((e=>{console.log("[Customer] WebSocket disconnected",e),g.value=!1,m=null})),e.index.onSocketMessage((t=>{console.log("收到WebSocket原始消息:",t),console.log("消息数据类型:",typeof t.data),console.log("消息内容:",t.data);const o=t.data;if("string"==typeof o)if(o.startsWith("42/customer,")){const e=o.substring(12);try{const t=JSON.parse(e);console.log("解析Socket.IO事件:",t),j(t)}catch(a){console.error("解析Socket.IO数据失败:",a,"原始数据:",e)}}else if(o.startsWith("40/customer"))console.log("Socket.IO连接确认");else if(o.startsWith("2"))e.index.sendSocketMessage({data:"3"});else if(o.startsWith("0"))console.log("Socket.IO握手成功");else try{const e=JSON.parse(o);console.log("解析JSON消息:",e),I(e)}catch(a){console.log("非JSON格式的字符串消息:",o)}else"object"==typeof o?(console.log("收到对象类型消息:",o),Q(o)):console.log("收到其他类型消息,类型:",typeof o)}))}catch(t){console.error("初始化Socket.IO异常:",t),g.value=!1,m=null}},j=e=>{if(Array.isArray(e)&&e.length>=2){const t=e[0],o=e[1];console.log("[Customer] Socket.IO事件类型:",t,"事件数据:",o),"new_message"===t?P(o):"join_conversation_response"===t?console.log("[Customer] Joined room:",o):"message"===t?P(o):"typing"===t?D(o):console.log("[Customer] 未处理的Socket.IO事件类型:",t)}},I=e=>{console.log("[Customer] 处理JSON消息:",e),"message"===e.type||"new_message"===e.event?P(e.data||e):"typing"===e.type||"typing"===e.event?D(e.data||e):e.message||e.content?P(e):console.log("[Customer] 未识别的JSON消息结构:",e)},Q=e=>{console.log("[Customer] 处理对象消息:",e),e.message||e.content||e.text?P(e):void 0!==e.is_typing?D(e):console.log("[Customer] 未识别的对象消息结构:",e)},D=e=>{console.log("[Customer] 处理typing指示器:",e),e.is_typing&&"staff"===e.user_type?(u.value=!0,c.value="客服正在输入..."):u.value=!1},W=(e=!1)=>{if(0===k.value.length)return;if(!(k.value.length>0))return;const t={role:"ai",content:"您好!我是物业客服,有什么可以帮助您的吗?",quickQuestions:k.value,created_at:(new Date).toISOString()};console.log("[Customer] 创建开场白消息,是否最后一页:",e),0===i.value.length?(i.value=[t],console.log("[Customer] 设置开场白为第一条消息")):(i.value.unshift(t),console.log("[Customer] 在第一条消息前面插入开场白"))},P=e=>{if(console.log("[Customer] 处理消息数据:",e),"customer"===e.sender_type||"user"===e.role)return void console.log("[Customer] 过滤掉客户消息");let t="";if(t="string"==typeof e?e:e.message||e.content||e.text||e.body||"收到回复","string"==typeof t&&(t=t.replace(/↵/g,"\n").replace(/\\n/g,"\n")),console.log("[Customer] 收到新消息内容:",t),t===S.value)return console.log("[Customer] 消息与HTTP返回的消息相同,跳过显示"),void(S.value="");u.value=!1;const o={role:"ai",content:t,created_at:e.created_at||e.timestamp||e.time||(new Date).toISOString()};e.suggested_questions&&Array.isArray(e.suggested_questions)&&e.suggested_questions.length>0?o.quickQuestions=e.suggested_questions:e.quickQuestions&&Array.isArray(e.quickQuestions)&&e.quickQuestions.length>0&&(o.quickQuestions=e.quickQuestions),void 0!==e.need_confirmation&&(o.needConfirmation=e.need_confirmation),void 0!==e.confirmation_type&&(o.confirmationType=e.confirmation_type),i.value.push(o),T()},z=(e,t)=>{void 0===e.selectedConfirmation&&(e.selectedConfirmation=t,setTimeout((()=>{n.value=t,J()}),300))},F=async()=>{if(l.value.length>=9)e.index.showToast({title:"最多选择9张图片",icon:"none"});else try{const t=9-l.value.length,a=await o.upload(t,2,["image"]);if(a&&Array.isArray(a)&&a.length>0){const t=a.map((e=>e.url));l.value.push(...t),e.index.showToast({title:"图片上传成功",icon:"success"})}}catch(t){console.error("选择图片失败:",t),e.index.showToast({title:"选择图片失败",icon:"none"})}},J=async()=>{var t,o,a,r,m,p;const v=n.value.trim(),y=l.value.length>0;if(!v&&!y||u.value)return;const _=null==(o=null==(t=s.data)?void 0:t.user)?void 0:o.phone,h=null==(r=null==(a=s.data)?void 0:a.selected_house)?void 0:r.asset_projects_id,k=null==(p=null==(m=s.data)?void 0:m.selected_house)?void 0:p.full_name;if(!_||!h)return void e.index.showToast({title:"请先登录并绑定房屋",icon:"none"});g.value||(O(),await new Promise((e=>setTimeout(e,1e3))));const q=l.value;let C="text";y&&v?C="mixed":y&&!v&&(C="image");const w={role:"user",content:v||"",created_at:(new Date).toISOString(),message_type:C,image_url:q.length>0?q:void 0,images:q.length>0?q:void 0};i.value.push(w),n.value="",l.value=[],T(),v&&v.includes("查询")?c.value="正在查询中请稍后...":c.value="正在输入中...",u.value=!0;try{const t=await e.index.request({url:`${d}/api/public/chat`,method:"POST",data:{platform:"property",message:v||"",tenant_project_id:h,tenant_project_name:k||"",platform_user_id:_,conversation_id:f.value,message_type:C,image_url:q.length>0?q:void 0},header:{"Content-Type":"application/json"}});if(200!==t.statusCode)throw new Error("请求失败");{const e=t.data;console.log("[Customer] HTTP接口响应数据:",e);let o=null,a=[],s=!1,n=null;if(e.reply&&"string"==typeof e.reply?(o=e.reply,a=e.suggested_questions||[],s=e.need_confirmation||!1,n=e.confirmation_type||null):e.reply&&e.reply.message?(o=e.reply.message,a=e.reply.suggested_questions||e.suggested_questions||[],s=e.reply.need_confirmation||e.need_confirmation||!1,n=e.reply.confirmation_type||e.confirmation_type||null):e.reply&&e.reply.content?(o=e.reply.content,a=e.reply.suggested_questions||e.suggested_questions||[],s=e.reply.need_confirmation||e.need_confirmation||!1,n=e.reply.confirmation_type||e.confirmation_type||null):e.message?(o=e.message,a=e.suggested_questions||[],s=e.need_confirmation||!1,n=e.confirmation_type||null):e.content?(o=e.content,a=e.suggested_questions||[],s=e.need_confirmation||!1,n=e.confirmation_type||null):e.answer?(o=e.answer,a=e.suggested_questions||[],s=e.need_confirmation||!1,n=e.confirmation_type||null):e.response?(o=e.response,a=e.suggested_questions||[],s=e.need_confirmation||!1,n=e.confirmation_type||null):"string"==typeof e&&(o=e),o){console.log("[Customer] HTTP接口返回回答消息:",o),console.log("[Customer] 建议问题:",a),console.log("[Customer] 需要确认:",s,"确认类型:",n);let e=o;"string"==typeof e&&(e=e.replace(/↵/g,"\n").replace(/\\n/g,"\n")),S.value=e,u.value=!1,i.value.push({role:"ai",content:e,created_at:(new Date).toISOString(),quickQuestions:a.length>0?a:void 0,needConfirmation:s,confirmationType:n}),T()}else console.log("[Customer] 消息发送成功,等待WebSocket回复")}}catch(A){console.error("发送消息失败:",A),e.index.showToast({title:"发送失败,请稍后重试",icon:"none"}),i.value.push({role:"ai",content:"抱歉,网络连接出现问题,请稍后再试。"}),u.value=!1,T()}};return e.onUnmounted((()=>{(m||g.value)&&(e.index.closeSocket(),m=null,g.value=!1,console.log("页面卸载,WebSocket连接已关闭"))})),e.onLoad((async t=>{var o;k.value=await(async()=>{try{const t=await e.index.request({url:`${d}/api/public/quick-questions`,method:"GET"});if(200===t.statusCode){const e=t.data;let o=[];return e.data&&Array.isArray(e.data)?o=e.data.map((e=>e.question||e.title||e.text||e)):e.questions&&Array.isArray(e.questions)?o=e.questions.map((e=>e.question||e.title||e.text||e)):Array.isArray(e)&&(o=e.map((e=>e.question||e.title||e.text||e))),console.log("获取到开场白按钮数据:",o),o}return console.error("获取开场白数据失败,状态码:",t.statusCode),[]}catch(t){return console.error("获取开场白数据异常:",t),[]}})(),console.log("页面加载时已获取开场白按钮数据:",k.value.length),b(1),(null==t?void 0:t.message)&&(o=t,n.value=o.message,J())})),(t,o)=>e.e({a:e.f(i.value,((t,o,a)=>{return e.e({a:"ai"===t.role},(t.role,{}),{b:t.image_url&&t.image_url.length>0},t.image_url&&t.image_url.length>0?{c:e.f(t.image_url,((o,a,s)=>({a:o,b:e.o((e=>w(o,t.image_url)),a),c:a}))),d:1===t.image_url.length?"widthFix":"aspectFill",e:1===t.image_url.length?1:""}:t.images&&t.images.length>0?{g:e.f(t.images,((o,a,s)=>({a:o,b:e.o((e=>w(o,t.images)),a),c:a}))),h:1===t.images.length?"widthFix":"aspectFill",i:1===t.images.length?1:""}:t.metadata&&t.metadata.image_url&&t.metadata.image_url.length>0?{k:e.f(t.metadata.image_url,((o,a,s)=>({a:o,b:e.o((e=>w(o,t.metadata.image_url)),a),c:a}))),l:1===t.metadata.image_url.length?"widthFix":"aspectFill",m:1===t.metadata.image_url.length?1:""}:{},{f:t.images&&t.images.length>0,j:t.metadata&&t.metadata.image_url&&t.metadata.image_url.length>0,n:t.content&&t.content.trim()},t.content&&t.content.trim()?{o:e.f((s=t.content,s&&"string"==typeof s?s.split("\n").filter((e=>""!==e.trim())):[""]),((t,o,a)=>({a:e.t(t),b:"text-"+o})))}:{},{p:t.quickQuestions&&t.quickQuestions.length>0},t.quickQuestions&&t.quickQuestions.length>0?{q:e.f(t.quickQuestions,((t,o,a)=>({a:e.t(t),b:o,c:e.o((e=>(e=>{n.value=e,J()})(t)),o)})))}:{},{r:t.needConfirmation},t.needConfirmation?{s:"是"===t.selectedConfirmation?1:"",t:void 0!==t.selectedConfirmation?1:"",v:e.o((e=>z(t,"是")),o),w:"否"===t.selectedConfirmation?1:"",x:void 0!==t.selectedConfirmation?1:"",y:e.o((e=>z(t,"否")),o)}:{},{z:t.created_at&&!t.quickQuestions},t.created_at&&!t.quickQuestions?e.e({A:"ai"===t.role},"ai"===t.role?{B:e.o((e=>A(t.content)),o)}:{},{C:e.t(x(t.created_at)),D:"user"===t.role},"user"===t.role?{E:e.o((e=>A(t.content)),o)}:{}):{},{F:o,G:`msg-${o}`,H:e.n("user"===t.role?"user-message":"ai-message")});var s})),b:u.value},u.value?{c:e.t(c.value)}:{},{d:l.value.length>0},l.value.length>0?e.e({e:e.f(l.value,((t,o,a)=>({a:t,b:"25c36616-0-"+a,c:e.o((e=>(e=>{l.value.splice(e,1)})(o)),o),d:o}))),f:e.p({type:"closeempty",size:"14",color:"#fff"}),g:l.value.length<9},l.value.length<9?{h:e.p({type:"plus",size:"30",color:"#999"}),i:e.o(F)}:{}):{},{j:e.o((e=>r.value=!0)),k:e.o((e=>r.value=!1)),l:e.o(J),m:n.value,n:e.o((e=>n.value=e.detail.value)),o:!n.value.trim()&&!r.value&&0===l.value.length},n.value.trim()||r.value||0!==l.value.length?{}:{p:e.p({type:"camera",size:"24",color:"#666"}),q:e.o(F)},{r:(n.value.trim()||r.value||l.value.length>0)&&!u.value},(n.value.trim()||r.value||l.value.length>0)&&!u.value?{s:e.p({type:"paperplane-filled",size:"20",color:"#fff"}),t:e.o(J)}:{},{v:u.value},u.value?{w:e.p({type:"spinner-cycle",size:"20",color:"#ccc"})}:{})}});a.__runtimeHooks=1,wx.createPage(a);
|