Browse Source

update:合并方法

cainiao-hue 3 months ago
parent
commit
4b7722cdfb
1 changed files with 117 additions and 196 deletions
  1. 117 196
      soul-app/src/app/tab2/tab2.page.ts

+ 117 - 196
soul-app/src/app/tab2/tab2.page.ts

@@ -53,171 +53,136 @@ export class Tab2Page {
     // 其他构造函数代码
     this.cyclePlaceholder();
   }
-  async clickToConsult(chatpartner:CloudObject) {
-    // 验证用户登录
-    let currentUser = new CloudUser();
-    let userPrompt = ``
-    if(!currentUser?.id){
-      console.log("用户未登录,请登录后重试")
-      let user = await openUserLoginModal(this.modalCtrl)
-      if(!user?.id){
-        console.log("用户登录失败");
-        return
-      } 
-      else {
-        console.log("当前用户ID:", currentUser.id);
-      }    
-    }
-    if(currentUser?.get("username")){
-      userPrompt += `当前来访的用户,姓名:${currentUser?.get("username")}`
-    }
-    if(currentUser?.get("gender")){
-      userPrompt += `,性别:${currentUser?.get("gender")}`
-    }
-    if(currentUser?.get("age")){
-      userPrompt += `,年龄:${currentUser?.get("age")}`
-    }
-
-    // 弹窗形式聊天:开始聊天
-    localStorage.setItem("company","E4KpGvTEto")
-    // 创建聊天记录对象
-    let consult = new CloudObject("ChatRecord")
-    // 设置聊天记录的基本信息
-    let now = new Date();
-    let dateStr = `${now.getFullYear()}-${now.getMonth()+1}-${now.getDate()}`
-    //对象权限的精确制定
-    let ACL:any = {//公开访客 不可读 不可写
-      "*":{read:true,write:true}
-    }
-
-    consult.set({
-      title:`${chatpartner.get('expertise') || ""}领域聊天记录${dateStr}-${chatpartner.get('name')}`,
-      chatpartner:chatpartner.toPointer(),
-      user:currentUser.toPointer(),
-      ACL:ACL,
-      content: [], // 初始内容为空
-      createdAt: now, // 可以加上创建时间
-    })
-    // 进入聊天面板
-    let options:ChatPanelOptions = {
-      roleId:"2DXJkRsjXK",
-      onChatInit: (chat: FmodeChat) => {
-        console.log("onChatInit");
-        console.log("预设角色", chat.role);
-        chat.role.set("name", chatpartner.get("name"));
-        chat.role.set("bio",chatpartner.get("bio"));
-        chat.role.set("expertise", chatpartner.get("expertise"));
-        chat.role.set("avatar", chatpartner.get("avatar") || "/assets/img/2.png")//设置陪聊师头像
-        chat.role.set("prompt", `
-        # 角色设定
-        您是${chatpartner.get("name")},一位${chatpartner.get("bio")},${chatpartner.get("expertise")},需要为用户提供陪伴和支持等积极情绪。
-        # 开始话语
-        当您准备好了,可以以一个关心用户的朋友的身份,向来访的用户打招呼。
-        # 对话环节
-        耐心积极的开导用户,给人一种暖心的感觉
-        ${userPrompt}
-        `);
-      },
+  matchedCounselor: { name: string; specialty: string } | null = null;
+  async clickToConsult(chatpartner: CloudObject) {
+      await this.initChat(chatpartner, true);
+  }
 
-      onMessage: (chat: FmodeChat, message: FmodeChatMessage) => {
-        console.log("onMessage", message);
-        let content:any = message?.content
-        // 更新 consult 对象的内容
-        consult.set({
-            content: chat.messageList, // 直接存储数组
-        });
-        // 仅在内容发生变化时保存
-        consult.save()
-      },
-        // chat?.chatSession?.id 本次会话的 chatId
-        onChatSaved:(chat:FmodeChat)=>{
-        console.log("onChatSaved",chat,chat?.chatSession,chat?.chatSession?.id)
-      }
-    }
-    openChatPanelModal(this.modalCtrl,options)
-    
+  async goChat(chatcompanion: CloudObject) {
+      await this.initChat(chatcompanion, false);
   }
-  matchedCounselor: { name: string; specialty: string } | null = null;
 
-  async goChat(chatcompanion:CloudObject) {
-    // 验证用户登录
-    let currentUser = new CloudUser();
-    let userPrompt = ``
-    if(!currentUser?.id){
-      console.log("用户未登录,请登录后重试")
-      let user = await openUserLoginModal(this.modalCtrl)
-      if(!user?.id){
-        return
-      }     
-    }
-    if(currentUser?.get("username")){
-      userPrompt += `当前来访的用户,姓名:${currentUser?.get("username")}`
+  private async initChat(partner: CloudObject, isConsult: boolean) {
+      // 验证用户登录
+      let currentUser = new CloudUser();
+      let userPrompt = ``;
+      if (!currentUser?.id) {
+          console.log("用户未登录,请登录后重试");
+          let user = await openUserLoginModal(this.modalCtrl);
+          if (!user?.id) {
+              return;
+          }
+      }
+    if (currentUser?.get("username")) {
+        userPrompt += `当前来访的用户,姓名:${currentUser?.get("username")}`;
     }
-    if(currentUser?.get("gender")){
-      userPrompt += `,性别:${currentUser?.get("gender")}`
+    if (currentUser?.get("gender")) {
+        userPrompt += `,性别:${currentUser?.get("gender")}`;
     }
-    if(currentUser?.get("age")){
-      userPrompt += `,年龄:${currentUser?.get("age")}`
+    if (currentUser?.get("age")) {
+        userPrompt += `,年龄:${currentUser?.get("age")}`;
     }
-
     // 弹窗形式聊天:开始聊天
-    localStorage.setItem("company","E4KpGvTEto")
+    localStorage.setItem("company", "E4KpGvTEto");
     // 创建聊天记录对象
-    this.consult = new CloudObject("ChatRecord")
+    this.consult = new CloudObject("ChatRecord");
     // 设置聊天记录的基本信息
     let now = new Date();
-    let dateStr = `${now.getFullYear()}-${now.getMonth()+1}-${now.getDate()}`
-    //对象权限的精确制定
-    let ACL:any = {//公开访客 不可读 不可写
-      "*":{read:true,write:true}
-    }
+    let dateStr = `${now.getFullYear()}-${now.getMonth() + 1}-${now.getDate()}`;
+    // 对象权限的精确制定
+    let ACL: any = {
+        "*": { read: true, write: true }
+    };
     this.consult.set({
-      title:`${chatcompanion.get('expertise') || ""}领域聊天记录${dateStr}-${chatcompanion.get('name')}`,
-      chatcompanion:chatcompanion.toPointer(),
-      user:currentUser.toPointer(),
-      content: [], // 初始内容为空
-      createdAt: now, // 可以加上创建时间
-      ACL:ACL
-    })
-    let options:ChatPanelOptions = {
-      roleId:"2DXJkRsjXK",
-      onChatInit: (chat: FmodeChat) => {
-        console.log("onChatInit");
-        console.log("预设角色", chat.role);
-        chat.role.set("name", chatcompanion.get("name"));
-        chat.role.set("bio",chatcompanion.get("bio"));
-        chat.role.set("expertise", chatcompanion.get("expertise"));
-        chat.role.set("avatar", chatcompanion.get("avatar") || "/assets/img/2.png")//设置聊天伙伴头像
-        chat.role.set("prompt", `
-        # 角色设定
-        您是${chatcompanion.get("name")},一位${chatcompanion.get("bio")}的聊天伙伴,需要为用户提供陪伴和支持等积极情绪。
-        # 开始话语
-        当您准备好了,可以以一个关心用户的朋友的身份,向来访的用户打招呼
-        # 对话环节
-        耐心与用户聊天,给人一种暖心陪伴的感觉
-        ${userPrompt}
-        `);
-      },
-      onMessage: (chat: FmodeChat, message: FmodeChatMessage) => {
-        console.log("onMessage", message);
-        let content:any = message?.content
-        // 更新 consult 对象的内容
-        this.consult.set({
-           content: chat.messageList, // 直接存储数组
-        });
-        // 仅在内容发生变化时保存
-        this.consult.save().then(() => {
-          // 生成聊天记录报告
-          this.generateReport(); // 确保此处 consult 已定义
-        })
+        title: `${partner.get('expertise') || ""}领域聊天记录${dateStr}-${partner.get('name')}`,
+        [isConsult ? 'chatpartner' : 'chatcompanion']: partner.toPointer(),
+        user: currentUser.toPointer(),
+        content: [], // 初始内容为空
+        createdAt: now, // 可以加上创建时间
+        ACL: ACL
+    });
+    let options: ChatPanelOptions = {
+        roleId: "2DXJkRsjXK",
+        onChatInit: (chat: FmodeChat) => {
+            console.log("onChatInit");
+            console.log("预设角色", chat.role);
+            chat.role.set("name", partner.get("name"));
+            chat.role.set("bio", partner.get("bio"));
+            chat.role.set("expertise", partner.get("expertise"));
+            chat.role.set("avatar", partner.get("avatar") || "/assets/img/2.png"); // 设置聊天伙伴头像
+            chat.role.set("prompt", `
+            # 角色设定
+            您是${partner.get("name")},一位${partner.get("bio")}的聊天伙伴,需要为用户提供陪伴和支持等积极情绪。
+            # 开始话语
+            当您准备好了,可以以一个关心用户的朋友的身份,向来访的用户打招呼
+            # 对话环节
+            耐心与用户聊天,给人一种暖心陪伴的感觉
+            ${userPrompt}
+            `);
+        },
+        onMessage: (chat: FmodeChat, message: FmodeChatMessage) => {
+            console.log("onMessage", message);
+            let content: any = message?.content;
+            // 更新 consult 对象的内容
+            this.consult.set({
+                content: chat.messageList, // 直接存储数组
+            });
+            // 仅在内容发生变化时保存
+            this.consult.save().then(() => {
+                // 生成聊天记录报告
+                this.generateReport(); // 确保此处 consult 已定义
+            });
+        },
+        onChatSaved: (chat: FmodeChat) => {
+            console.log("onChatSaved", chat, chat?.chatSession, chat?.chatSession?.id);
+        }
+    };
+    openChatPanelModal(this.modalCtrl, options);
+}
 
-      },
-        onChatSaved:(chat:FmodeChat)=>{
-        console.log("onChatSaved",chat,chat?.chatSession,chat?.chatSession?.id)
-      }
+async generateReport() {
+  if (!this.consult) {
+    console.error('Consult对象未定义');
+    return;
+  }
+  let chatContent = this.consult.get('content') || [];
+  // 检查 chatContent 是否有效
+  let report = "聊天记录报告\n\n";
+  if (chatContent.length === 0) {
+      report += "没有聊天记录。\n\n";
+  } else {
+      chatContent.forEach((message: any, index: number) => {
+          report += `消息 ${index + 1}:\n\n`;
+          report += `内容: ${message.content}\n\n`;
+          
+          // 假设有一个情感分析函数 analyzeSentiment
+          const sentiment = this.analyzeSentiment(message.content);
+          report += `心晴分析: ${sentiment}\n\n`;
+      });
+  }
+  // 显示报告
+  await this.showReportModal(report);
+  }
+  analyzeSentiment(text:String) {
+    // 这里可以使用简单的关键词匹配或更复杂的模型来分析情感
+    if (text.includes("好") || text.includes("喜欢")) {
+        return "积极";
+    } else if (text.includes("坏") || text.includes("不喜欢")) {
+        return "消极";
+    } else {
+        return "中性";
     }
-    openChatPanelModal(this.modalCtrl,options)
-    
+  }
+  extractKeywords(text:String): string[] {
+    // 这里可以实现简单的关键词提取逻辑
+    return text.split(/\s+/).filter(word => word.length > 0); // 示例:提取长度大于0的单词
+  }
+  async showReportModal(report: string) {
+    const modal = await this.modalCtrl.create({
+      component: ReportModalComponent, // 你需要创建这个组件来显示报告
+      componentProps: { report }
+    });
+    return await modal.present();
   }
   questions = [
     {
@@ -251,48 +216,4 @@ export class Tab2Page {
     this.chatcompanionList = await query.find()
   }
 
-  async generateReport() {
-    if (!this.consult) {
-      console.error('Consult对象未定义');
-      return;
-    }
-    let chatContent = this.consult.get('content') || [];
-    // 检查 chatContent 是否有效
-    let report = "聊天记录报告\n\n";
-    if (chatContent.length === 0) {
-        report += "没有聊天记录。\n\n";
-    } else {
-        chatContent.forEach((message: any, index: number) => {
-            report += `消息 ${index + 1}:\n\n`;
-            report += `内容: ${message.content}\n\n`;
-            
-            // 假设有一个情感分析函数 analyzeSentiment
-            const sentiment = this.analyzeSentiment(message.content);
-            report += `心晴分析: ${sentiment}\n\n`;
-        });
-    }
-    // 显示报告
-    await this.showReportModal(report);
-  }
-  analyzeSentiment(text:String) {
-    // 这里可以使用简单的关键词匹配或更复杂的模型来分析情感
-    if (text.includes("好") || text.includes("喜欢")) {
-        return "积极";
-    } else if (text.includes("坏") || text.includes("不喜欢")) {
-        return "消极";
-    } else {
-        return "中性";
-    }
-  }
-  extractKeywords(text:String): string[] {
-    // 这里可以实现简单的关键词提取逻辑
-    return text.split(/\s+/).filter(word => word.length > 0); // 示例:提取长度大于0的单词
-  }
-  async showReportModal(report: string) {
-    const modal = await this.modalCtrl.create({
-      component: ReportModalComponent, // 你需要创建这个组件来显示报告
-      componentProps: { report }
-    });
-    return await modal.present();
-  }
 }