2026-04-02 10:29:32 +08:00

2 lines
17 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"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"),a=require("../../common/libraries/public.js");if(require("../../gen/Apis.js"),require("../../common/libraries/setTabBar.js"),require("../../common/libraries/apiLoading.js"),!Array){e.resolveComponent("uni-icons")()}Math;const s=e.defineComponent({__name:"chat",setup(s){e.dayjs.extend(e.relativeTime),e.dayjs.locale("zh-cn");const n=t.useWeAppAuthStore(),l=e.ref(""),r=e.ref([]),i=e.ref(!1),u=e.ref([{role:"ai",content:"您好!我是物业客服,有什么可以帮助您的吗?",quickQuestions:[]}]),c=e.ref(!1),m=e.ref("正在输入中...");let g=null,d=e.ref(!1);const p="https://kf-api-test.linyikj.com.cn",v=e.ref(1),f=e.ref(10),y=e.ref(!0),_=e.ref(!1),h=e.ref(""),k=e.ref(0),q=e.ref([]),S=e.ref(""),C=(t,o)=>{e.index.previewImage({current:t,urls:o})},w=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"})},A=t=>{if(!t)return"";try{const o=e.dayjs(t);return o.isValid()?o.fromNow():""}catch(o){return console.error("时间格式化错误:",o),""}},x=()=>{e.nextTick$1((()=>{e.index.pageScrollTo({scrollTop:999999,duration:300})}))},T=async(t=1)=>{var o,a;const s=null==(a=null==(o=n.data)?void 0:o.user)?void 0:a.phone;if(s){if(!_.value)try{_.value=!0;const o=(t-1)*f.value;k.value=o,console.log("分页信息 - 页码:",t,"每页数量:",f.value,"计算出的offset:",o);const a=await e.index.request({url:`${p}/api/public/customer/init`,method:"POST",data:{platform:"property",platform_user_id:s,limit:f.value,offset:o}});if(200===a.statusCode){const s=a.data;let n=[];s.conversation&&s.conversation.id?(h.value=s.conversation.id,console.log("获取到会话ID:",h.value)):s.conversation_id?(h.value=s.conversation_id,console.log("获取到会话ID:",h.value)):s.conversations&&s.conversations.id&&(h.value=s.conversations.id,console.log("获取到会话ID:",h.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?(u.value=n,console.log("第一页历史记录已加载,总共",n.length,"条消息")):(console.log("没有历史记录"),u.value=[]),e.nextTick$1((()=>{if(q.value.length>0){const e={role:"ai",content:"您好!我是物业客服,有什么可以帮助您的吗?",quickQuestions:q.value,created_at:(new Date).toISOString()};u.value.push(e),console.log("[Customer] 获取历史记录成功后在历史记录后面push新开场白消息"),x()}}))):n.length>0&&setTimeout((()=>{u.value.unshift(...n),console.log("加载更多历史记录,新增",n.length,"条消息,总共",u.value.length,"条")}),300);const l=s.total||s.count||s.total_count||0;y.value=l>u.value.length,v.value=t,t>1&&!y.value&&(console.log("分页加载完成,当前页:",t,"hasMore:",y.value,"展示开场白"),setTimeout((()=>{D(!0)}),500)),console.log("第",t,"页数据加载完成offset:",o,", limit:",f.value,", 总数据:",l,", 当前已加载:",u.value.length,", 是否有更多:",y.value),1===t&&(setTimeout((()=>{x()}),100),console.log("[Customer] 历史记录加载完成开始建立WebSocket连接"),b())}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=v.value+1;try{await T(t),await new Promise((e=>setTimeout(e,500)))}catch(o){console.error("加载历史记录失败:",o)}finally{e.index.stopPullDownRefresh()}}));const b=()=>{if(!g)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),g=e.index.connectSocket({url:t,header:{"content-type":"application/json"}}),e.index.onSocketOpen((t=>{console.log("[Customer] WebSocket connected",t),d.value=!0;e.index.sendSocketMessage({data:'40/customer,{"jwt":""}',success:()=>{console.log("[Customer] Socket.IO连接包发送成功"),h.value&&setTimeout((()=>{const t=`42/customer,["join_conversation",{"conversation_id":"${h.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),d.value=!1,g=null})),e.index.onSocketClose((e=>{console.log("[Customer] WebSocket disconnected",e),d.value=!1,g=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),O(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),j(e)}catch(a){console.log("非JSON格式的字符串消息:",o)}else"object"==typeof o?(console.log("收到对象类型消息:",o),I(o)):console.log("收到其他类型消息,类型:",typeof o)}))}catch(t){console.error("初始化Socket.IO异常:",t),d.value=!1,g=null}},O=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?W(o):"join_conversation_response"===t?console.log("[Customer] Joined room:",o):"message"===t?W(o):"typing"===t?Q(o):console.log("[Customer] 未处理的Socket.IO事件类型:",t)}},j=e=>{console.log("[Customer] 处理JSON消息:",e),"message"===e.type||"new_message"===e.event?W(e.data||e):"typing"===e.type||"typing"===e.event?Q(e.data||e):e.message||e.content?W(e):console.log("[Customer] 未识别的JSON消息结构:",e)},I=e=>{console.log("[Customer] 处理对象消息:",e),e.message||e.content||e.text?W(e):void 0!==e.is_typing?Q(e):console.log("[Customer] 未识别的对象消息结构:",e)},Q=e=>{console.log("[Customer] 处理typing指示器:",e),e.is_typing&&"staff"===e.user_type?(c.value=!0,m.value="客服正在输入..."):c.value=!1},D=(e=!1)=>{if(0===q.value.length)return;if(!(q.value.length>0))return;const t={role:"ai",content:"您好!我是物业客服,有什么可以帮助您的吗?",quickQuestions:q.value,created_at:(new Date).toISOString()};console.log("[Customer] 创建开场白消息,是否最后一页:",e),0===u.value.length?(u.value=[t],console.log("[Customer] 设置开场白为第一条消息")):(u.value.unshift(t),console.log("[Customer] 在第一条消息前面插入开场白"))},W=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="");c.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),u.value.push(o),x()},P=e=>{l.value=e.message,J()},z=(e,t)=>{void 0===e.selectedConfirmation&&(e.selectedConfirmation=t,setTimeout((()=>{l.value=t,J()}),300))},F=async()=>{if(r.value.length>=9)e.index.showToast({title:"最多选择9张图片",icon:"none"});else try{const t=9-r.value.length,a=await o.upload(t,2,["image"]);if(a&&Array.isArray(a)&&a.length>0){const t=a.map((e=>e.url));r.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,s,i,g;const v=l.value.trim(),f=r.value.length>0;if(!v&&!f||c.value)return;const y=null==(o=null==(t=n.data)?void 0:t.user)?void 0:o.phone,_=null==(s=null==(a=n.data)?void 0:a.selected_house)?void 0:s.asset_projects_id,k=null==(g=null==(i=n.data)?void 0:i.selected_house)?void 0:g.full_name;if(!y||!_)return void e.index.showToast({title:"请先登录并绑定房屋",icon:"none"});d.value||(b(),await new Promise((e=>setTimeout(e,1e3))));const q=r.value;let C="text";f&&v?C="mixed":f&&!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};u.value.push(w),l.value="",r.value=[],x(),v&&v.includes("查询")?m.value="正在查询中请稍后...":m.value="正在输入中...",c.value=!0;try{const t=await e.index.request({url:`${p}/api/public/chat`,method:"POST",data:{platform:"property",message:v||"",tenant_project_id:_,tenant_project_name:k||"",platform_user_id:y,conversation_id:h.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,c.value=!1,u.value.push({role:"ai",content:e,created_at:(new Date).toISOString(),quickQuestions:a.length>0?a:void 0,needConfirmation:s,confirmationType:n}),x()}else console.log("[Customer] 消息发送成功等待WebSocket回复")}}catch(A){console.error("发送消息失败:",A),e.index.showToast({title:"发送失败,请稍后重试",icon:"none"}),u.value.push({role:"ai",content:"抱歉,网络连接出现问题,请稍后再试。"}),c.value=!1,x()}};return e.onUnmounted((()=>{(g||d.value)&&(e.index.closeSocket(),g=null,d.value=!1,console.log("页面卸载WebSocket连接已关闭"))})),e.onLoad((async t=>{q.value=await(async()=>{try{const t=await e.index.request({url:`${p}/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("页面加载时已获取开场白按钮数据:",q.value.length),T(1),(null==t?void 0:t.message)&&P(t)})),(t,o)=>e.e({a:e.f(u.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=>C(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=>C(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=>C(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=>{l.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=>w(t.content)),o)}:{},{C:e.t(A(t.created_at)),D:"user"===t.role},"user"===t.role?{E:e.o((e=>w(t.content)),o)}:{}):{},{F:o,G:`msg-${o}`,H:e.n("user"===t.role?"user-message":"ai-message")});var s})),b:c.value},c.value?{c:e.t(m.value)}:{},{d:r.value.length>0},r.value.length>0?e.e({e:e.f(r.value,((t,o,a)=>({a:t,b:"f3306fff-0-"+a,c:e.o((e=>(e=>{r.value.splice(e,1)})(o)),o),d:o}))),f:e.p({type:"closeempty",size:"14",color:"#fff"}),g:r.value.length<9},r.value.length<9?{h:e.p({type:"plus",size:"30",color:"#999"}),i:e.o(F)}:{}):{},{j:e.f(e.unref(a.quickActions),((t,o,a)=>({a:e.t(t.label),b:o,c:e.o((e=>P(t)),o)}))),k:e.o((e=>i.value=!0)),l:e.o((e=>i.value=!1)),m:e.o(J),n:l.value,o:e.o((e=>l.value=e.detail.value)),p:!l.value.trim()&&!i.value&&0===r.value.length},l.value.trim()||i.value||0!==r.value.length?{}:{q:e.p({type:"camera",size:"24",color:"#666"}),r:e.o(F)},{s:(l.value.trim()||i.value||r.value.length>0)&&!c.value},(l.value.trim()||i.value||r.value.length>0)&&!c.value?{t:e.p({type:"paperplane-filled",size:"20",color:"#fff"}),v:e.o(J)}:{},{w:c.value},c.value?{x:e.p({type:"spinner-cycle",size:"20",color:"#ccc"})}:{})}}),n=e._export_sfc(s,[["__scopeId","data-v-f3306fff"]]);wx.createPage(n);