123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519 |
- import { Component, OnInit, ViewChild } from '@angular/core';
- import {
- IonTextarea, IonCheckbox, IonList, IonButton, IonContent, IonHeader, IonInput, IonTitle,
- IonToolbar, IonItem, IonLabel, IonRadioGroup, IonRadio, IonDatetimeButton, IonDatetime,
- IonModal, IonAlert, IonBackButton, IonButtons
- } from '@ionic/angular/standalone';
- import { CloudQuery, CloudObject, Pointer } from '../../lib/ncloud'; // 确保路径正确
- import { CommonModule, DatePipe } from '@angular/common'; // 导入 CommonModule
- import { FormsModule } from '@angular/forms'; // 导入 FormsModule
- import { FmodeChatCompletion, MarkdownPreviewModule } from 'fmode-ng';
- import { AlertController } from '@ionic/angular';
- // 定义接口以确保类型安全
- interface Questionnaire {
- objectId: string;
- createdAt: string;
- QuestionnaireId: string;
- title: string;
- status: string;
- questions: string[]; // 修改为字符串数组
- }
- interface Question {
- objectId: string;
- createdAt: string;
- QuestionId: string;
- questionnaireId: string; // 修改为字符串
- questionText: string;
- options: string[]; // 修改为字符串数组
- }
- interface Option {
- objectId: string;
- createdAt: string;
- OptionId: string;
- questionId: string; // 修改为字符串
- optionText: string;
- isSelected: boolean;
- }
- interface QuestionnaireResult {
- objectId: string;
- createdAt: string;
- QuestionnaireResultId: string;
- userId: Pointer;
- questionnaireId: Pointer;
- answers: Pointer[];
- }
- interface UserInterestProfile {
- objectId: string;
- createdAt: string;
- userId: String;
- QuestionnaireId: String;
- interestTags: String[];
- content: String;
- }
- interface QuestionWithOptions extends Question {
- optionsData: Option[];
- }
- @Component({
- selector: 'app-interest-search',
- templateUrl: './interest-search.component.html',
- styleUrls: ['./interest-search.component.scss'],
- standalone: true,
- imports: [IonTextarea, IonCheckbox, IonList, IonButton, IonContent, IonHeader, IonInput,
- IonTitle, IonToolbar, IonItem, IonLabel, IonRadioGroup, IonRadio, IonDatetimeButton,
- IonDatetime, IonModal, CommonModule, FormsModule, IonDatetime, IonModal, IonAlert,
- IonBackButton, IonButtons, MarkdownPreviewModule
- ]
- })
- export class InterestSearchComponent implements OnInit {
- // 固定字段
- name: string = '';
- birthday: string = '';
- // 动态问卷数据
- questionnaire: Questionnaire | null = null;
- questionsWithOptions: QuestionWithOptions[] = [];
- answers: { [questionId: string]: string } = {}; // 存储用户答案
- //新增AI分析部分的变量
- aiAnalysisResult: { interestTags: string[], content: string } | null = null; // AI 分析结果
- isComplete: boolean = false; // 定义完成状态属性,用来标记是否补全完成
- @ViewChild(IonModal) modal!: IonModal; // 引入 IonModal 以控制其打开和关闭
- modalIsOpen: boolean = false; // 使用 isOpen 控制 Modal 的显示状态
- modalContent: string = ''; // 保存弹窗的内容
- constructor() { }
- // 定义方法,用于获取 <ion-datetime> 组件选择的值
- onDateTimeChange(event: any) {
- this.birthday = event.detail.value;
- // // 使用DatePipe进行日期格式化,只保留年、月、日
- // this.birthday = this.datePipe.transform(this.birthday, 'yyyy-MM-dd')!;
- console.log('选择的日期为:', this.birthday);
- }
- alertButtons = ['确定'];
- ngOnInit() {
- this.loadQuestionnaireData('q1'); // 使用 QuestionnaireId 'q1'
- //this.loadQuestionnaireData(this.getRandomQuestionnaire());
- }
- getRandomQuestionnaire() {
- const questionnaires = ['q1', 'q2', 'q3']; // List of your questionnaires
- const randomIndex = Math.floor(Math.random() * questionnaires.length); // Generate a random index
- return questionnaires[randomIndex]; // Return the randomly selected questionnaire ID
- }
- async loadQuestionnaireData(questionnaireId: string) {
- try {
- const questionnaireQuery = new CloudQuery("Questionnaire");
- questionnaireQuery.equalTo("QuestionnaireId", questionnaireId);
- const questionnaireObj = await questionnaireQuery.first();
- if (questionnaireObj) {
- const questionnaireData = questionnaireObj.data as Questionnaire;
- // 确保 objectId 存在且为字符串
- this.questionnaire = {
- ...questionnaireData,
- objectId: String(questionnaireObj.id)
- };
- console.log("加载到的问卷数据:", this.questionnaire);
- // 确保 questions 被正确传入
- if (this.questionnaire.questions) {
- await this.loadQuestions(this.questionnaire.questions);
- }
- } else {
- console.error(`未找到 QuestionnaireId 为 ${questionnaireId} 的问卷。`);
- }
- } catch (error) {
- console.error("加载问卷数据时出错:", error);
- }
- }
- async loadQuestions(questionIds: string[]) {
- this.questionsWithOptions = []; // 初始化问题列表
- for (const questionId of questionIds) {
- try {
- const questionQuery = new CloudQuery("Question");
- questionQuery.equalTo("QuestionId", questionId);
- const questionObj = await questionQuery.first();
- if (questionObj) {
- const question = questionObj.data as Question;
- // 异步加载选项并立即显示问题
- this.questionsWithOptions.push({ ...question, optionsData: [] });
- this.loadOptions(question.options).then((options) => {
- const index = this.questionsWithOptions.findIndex(
- (q) => q.QuestionId === question.QuestionId
- );
- if (index !== -1) {
- this.questionsWithOptions[index].optionsData = options;
- }
- });
- // 可选:每加载一个问题,立即触发渲染
- console.log("已加载问题:", question);
- }
- } catch (error) {
- console.error(`加载问题 ID ${questionId} 时出错:`, error);
- }
- }
- }
- async loadOptions(optionIds: string[]): Promise<Option[]> {
- try {
- if (!optionIds || optionIds.length === 0) return [];
- const optionQuery = new CloudQuery("Option");
- optionQuery.containedIn("OptionId", optionIds); // 批量查询
- const optionObjs = await optionQuery.find();
- return optionObjs.map((optionObj: any) => optionObj.data as Option);
- } catch (error) {
- console.error("加载选项时出错:", error);
- return [];
- }
- }
- // 保存功能(可选)
- async save() {
- try {
- // 实现保存逻辑,例如保存到本地存储或发送到后台
- console.log("保存的答案:", this.answers);
- console.log("姓名:", this.name);
- console.log("生日:", this.birthday);
- } catch (error) {
- console.error("保存答案时出错:", error);
- }
- }
- // 提交功能
- async submit() {
- try {
- if (!this.questionnaire) {
- console.error("未加载问卷数据。");
- return;
- }
- // 创建一个数组保存选中的 OptionId
- const answersArray: string[] = [];
- // 遍历每个问题,获取用户选择的选项
- for (const question of this.questionsWithOptions) {
- const selectedOptionId = this.answers[question.QuestionId];
- if (selectedOptionId) {
- // 将选中的 OptionId 存入 answersArray
- answersArray.push(selectedOptionId);
- }
- }
- // 创建一个新的 QuestionnaireResult 对象
- const questionnaireResult = new CloudObject("QuestionnaireResult");
- // 设置 QuestionnaireResult 的属性
- questionnaireResult.set({
- QuestionnaireResultId: `qr_${new Date().getTime()}`, // 生成唯一的 QuestionnaireResultId
- userId: { __type: "Pointer", className: "_User", objectId: "user1" }, // 替换为实际的用户ID
- // 使用 Pointer 类型的引用方式来设置 questionnaireId
- questionnaireId: { __type: "Pointer", className: "Questionnaire", objectId: this.questionnaire.objectId },
- answers: answersArray // 将选中的 OptionId 数组存入 answers 字段
- });
- // 保存 QuestionnaireResult 对象
- await questionnaireResult.save();
- console.log("问卷提交成功。");
- // 构建用于 AI 模型分析的提示词
- const aiPrompt = this.createAiPrompt(answersArray);
- // 调用 AI 模型分析,强制等待结果
- const aiResponse = await this.callAiModel(aiPrompt);
- // 如果 AI 响应有效,则执行以下逻辑
- if (aiResponse) {
- this.aiAnalysisResult = aiResponse; // 保存 AI 响应结果
- this.showAnalysisResult(); // 显示结果给用户
- await this.saveAnalysisResult(aiResponse); // 保存到数据库
- }
- } catch (error) {
- console.error("提交问卷时出错:", error);
- }
- }
- // 生成 AI 模型的提示词
- createAiPrompt(answersArray: string[]): string {
- const questionTexts = this.questionsWithOptions.map(q => q.questionText);
- const optionTexts = answersArray.map(optionId => {
- // 找到对应的 Option,并提取其 optionText
- const option = this.questionsWithOptions
- .flatMap(q => q.optionsData) // 从每个问题的 optionsData 获取 Option 对象
- .find(o => o.OptionId === optionId);
- return option ? option.optionText : ''; // 返回选项文本
- });
- return `
- 您是一名专业的兴趣分析师,请根据用户填写的问卷内容以及选项分析用户的兴趣并且生成以下格式的响应:
-
- {
- "interestTags": ["标签1", "标签2", "标签3", "标签4"], // 生成用户最感兴趣的四个标签(如:书法、绘画、摄影等)
- "content": "标签描述" // 针对每个标签生成简洁、生动的描述,帮助用户更清楚了解兴趣特点。描述可以包括用户行为、倾向和相关建议。
- }
- 请根据以下信息进行分析:
- 问题:${questionTexts.join(',')}
- 选项:${optionTexts.join(',')}
- 注意:
- - 仅选择用户**最感兴趣**的四个标签。
- - 生成的描述需要具体、生动,反映用户的兴趣深度或行为倾向。
- - 请忽略与用户兴趣无关的内容。
- - 标签和描述应通俗易懂,适合用户直接阅读。
- `;
- }
- async callAiModel(prompt: string): Promise<{ interestTags: string[], content: string }> {
- try {
- const completion = new FmodeChatCompletion([
- { role: "system", content: "您是一个专业的兴趣分析助手。" },
- { role: "user", content: prompt }
- ]);
- let fullContent = '';
- let count = 0;
- return new Promise((resolve, reject) => {
- completion.sendCompletion().subscribe({
- next: (message: any) => {
- if (message.content) {
- try {
- console.log('Received content:', message.content);
- fullContent = message.content;
- // 判断消息是否完成
- if (message?.complete) {
- this.isComplete = true;
- }
- // 如果消息完成且内容符合 JSON 格式,则解析
- if (this.isComplete) {
- const cleanedContent = fullContent.trim();
- // 检查是否是有效的 JSON 格式
- if (cleanedContent.startsWith('{') && cleanedContent.endsWith('}')) {
- try {
- // 清理掉换行符和多余空格
- let finalContent = cleanedContent.replace(/[\r\n]+/g, ''); // 去掉换行符
- finalContent = finalContent.replace(/\s+/g, ' '); // 去掉多余的空格
- console.log(finalContent);
- // 解析 JSON
- const parsedResponse = JSON.parse(finalContent);
- // 如果解析成功并且格式正确
- if (parsedResponse && parsedResponse.interestTags && parsedResponse.content) {
- const { interestTags, content } = parsedResponse;
- // 如果 content 是对象类型,转化成字符串
- let contentStr = '';
- if (typeof content === 'string') {
- contentStr = content; // 如果已经是字符串,直接使用
- } else if (typeof content === 'object') {
- // 如果是对象,转换为 JSON 字符串
- contentStr = JSON.stringify(content, null, 2); // 美化 JSON 字符串格式
- count = 0;
- this.isComplete = false;
- }
- resolve({
- interestTags: Array.isArray(interestTags) ? interestTags : [],
- content: contentStr
- });
- } else {
- reject(new Error("AI 返回的内容格式不正确"));
- }
- } catch (err) {
- console.log(fullContent);
- console.error("解析 AI 响应失败:", err);
- reject(new Error("解析 AI 响应失败"));
- }
- } else {
- reject(new Error("返回的内容不是有效的 JSON 格式"));
- }
- }
- } catch (err) {
- console.error("处理消息时出错:", err);
- reject(new Error("处理消息时出错"));
- }
- } else {
- if (count !== 0) {
- console.error("AI 返回的消息为空");
- reject(new Error("AI 返回的消息为空"));
- }
- count = 1;
- }
- },
- error: (err) => {
- console.error("AI 模型调用失败:", err);
- reject(new Error("AI 模型调用失败"));
- },
- complete: () => {
- // 可以在这里处理完成后的操作
- console.log("AI 请求完成");
- }
- });
- });
- } catch (error) {
- console.error("AI 模型调用失败:", error);
- throw new Error("AI 模型调用失败");
- }
- }
- /*
- // 显示分析结果
- showAnalysisResult() {
- if (this.aiAnalysisResult) {
- this.showAlert(this.aiAnalysisResult.content); // 弹窗显示 AI 分析的内容
- }
- }
- async showAlert(content: string) {
- //const formattedContent = this.formatContent(content); // 格式化内容
- const alert = await this.alertController.create({
- header: '兴趣分析结果',
- message: `${content}`, // 使用 pre 标签来保持格式
- buttons: ['确定']
- });
- await alert.present();
- }
- // 格式化 content 为可读的文本格式
- formatContent(content: string): string {
- try {
- // 尝试将 content 解析为 JSON 对象
- const contentObj = JSON.parse(content);
- // 构建格式化后的文本
- let formattedContent = '';
- // 遍历 JSON 对象,生成类似 "标签: 描述" 的格式
- for (const [tag, description] of Object.entries(contentObj)) {
- formattedContent += `${tag}: \n${description}\n\n`;
- }
- // 将换行符转换为 <br/>
- return formattedContent.replace(/\n/g, '<br/>');
- } catch (e) {
- console.error('格式化 AI 响应时出错:', e);
- return '分析结果格式错误。';
- }
- }
- *//*
- // 格式化 AI 响应内容
- formatContent(content: string): string {
- try {
- const contentObj = JSON.parse(content);
- return Object.entries(contentObj)
- .map(
- ([key, value]) =>
- `<strong>${key}:</strong><br>${value}<br><br>`
- )
- .join('');
- } catch (error) {
- console.error('格式化 AI 响应时出错:', error);
- return '分析结果格式错误。';
- }
- }
- */
- // 格式化 AI 响应内容
- formatContent(content: string): string {
- try {
- const contentObj = JSON.parse(content);
- console.log(contentObj)
- // 提取 interestTags 数组并格式化为一行展示
- const interestTags = contentObj.interestTags || [];
- const interestTagsFormatted = Array.isArray(interestTags)
- ? `${interestTags.join(',')}` // 标签用逗号分隔
- : '';
- // 提取 content 对象内容并格式化
- const contentDetails = contentObj.content || {};
- const contentFormatted = contentDetails
- .replace(/\"/g, '') // 移除转义字符如 \"
- .replace(/\n/g, '') // 移除换行符 \n
- .replace(/,/g, '') // 移除,
- .replace(/{/g, '') // 移除{
- .replace(/}/g, '') // 移除}
- .replace(/。/g, '。<br /><br />'); // 在每个句号 "。" 后插入换行 <br />
- // 冒号前加粗,描述部分保持普通
- // 拼接“兴趣描述”标题和换行
- const fullContent = `<strong class="fontsize">兴趣描述</strong>:<br />${contentFormatted}`;
- // 拼接最终输出
- return `
- <strong class="fontsize">兴趣标签:</strong><br> ${interestTagsFormatted}<br><br>
- ${fullContent}
- `;
- } catch (error) {
- console.error('格式化 AI 响应时出错:', error);
- return '分析结果格式错误。';
- }
- }
- // 显示分析结果
- showAnalysisResult() {
- if (this.aiAnalysisResult) {
- this.modalContent = this.formatContent(
- JSON.stringify({
- interestTags: this.aiAnalysisResult.interestTags,
- content: this.aiAnalysisResult.content
- })
- );
- this.modalIsOpen = true; // 打开 Modal
- }
- }
- // 关闭 Modal
- closeModal() {
- this.modalIsOpen = false; // 关闭 Modal
- }
- // 保存 AI 分析结果到数据库
- async saveAnalysisResult(aiResponse: { interestTags: string[], content: string }) {
- try {
- const userInterestProfile = new CloudObject("UserInterestProfile");
- userInterestProfile.set({
- userId: { __type: "Pointer", className: "_User", objectId: "user1" }, // 假设这是当前用户ID
- QuestionnaireId: this.questionnaire?.QuestionnaireId,
- interestTags: aiResponse.interestTags,
- content: aiResponse.content
- });
- await userInterestProfile.save();
- console.log("分析结果已保存");
- } catch (error) {
- console.error('保存分析结果时出错:', error);
- }
- }
- }
|