123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352 |
- import { Component, OnInit } 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
- // 定义接口以确保类型安全
- 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 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,
- ]
- })
- export class InterestSearchComponent implements OnInit {
- // 固定字段
- name: string = '';
- birthday: string = '';
- // 动态问卷数据
- questionnaire: Questionnaire | null = null;
- questionsWithOptions: QuestionWithOptions[] = [];
- answers: { [questionId: string]: 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('test_q1'); // 使用 QuestionnaireId 'test_q1'
- }
- 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 loadQuestions(questionIds: string[]) {
- try {
- const questionQuery = new CloudQuery("Question");
- questionQuery.containedIn("QuestionId", questionIds); // 一次查询多个 QuestionId
- const questionObjs = await questionQuery.find();
- const questionsWithOptions: QuestionWithOptions[] = await Promise.all(
- questionObjs.map(async (questionObj: any) => {
- const question = questionObj.data as Question;
- const options = await this.loadOptions(question.options);
- return { ...question, optionsData: options };
- })
- );
- this.questionsWithOptions = questionsWithOptions;
- } catch (error) {
- console.error("批量加载问题时出错:", error);
- }
- }
- async loadOptions(optionIds: string[]): Promise<Option[]> {
- try {
- const optionQuery = new CloudQuery("Option");
- optionQuery.containedIn("OptionId", optionIds); // 批量查询所有 OptionId
- const optionObjs = await optionQuery.find();
- return optionObjs.map((optionObj: any) => optionObj.data as Option);
- } catch (error) {
- console.error("批量加载选项时出错:", error);
- return [];
- }
- }
- */
- /*
- // 加载问卷中的问题及选项
- async loadQuestions(questionIds: string[]) {
- try {
- const questions: QuestionWithOptions[] = [];
-
- for (const questionId of questionIds) {
- const questionQuery = new CloudQuery("Question");
- questionQuery.equalTo("QuestionId", questionId);
- const questionObj = await questionQuery.first();
-
- if (!questionObj) {
- console.error(`未找到问题ID为 ${questionId} 的问题。`);
- continue;
- }
-
- const question = questionObj.data as Question;
- const options = await this.loadOptions(question.options); // 加载选项
-
- questions.push({
- ...question,
- optionsData: options
- });
- }
-
- this.questionsWithOptions = questions;
- } catch (error) {
- console.error("加载问题时出错:", error);
- }
- }
-
- // 加载选项
- async loadOptions(optionIds: string[]): Promise<Option[]> {
- try {
- const options: Option[] = [];
-
- for (const optionId of optionIds) {
- const optionQuery = new CloudQuery("Option");
- optionQuery.equalTo("OptionId", optionId);
- const optionObj = await optionQuery.first();
-
- if (!optionObj) {
- console.error(`未找到选项ID为 ${optionId} 的选项。`);
- continue;
- }
-
- const option = optionObj.data as Option;
- options.push(option);
- }
-
- return options;
- } 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("问卷提交成功。");
- // 可选:清空表单
- this.name = '';
- this.birthday = '';
- this.answers = {};
- } catch (error) {
- console.error("提交问卷时出错:", error);
- }
- }
- /*async submit() {
- try {
- if (!this.questionnaire) {
- console.error("未加载问卷数据。");
- return;
- }
- const answersPointers: Pointer[] = [];
- for (const question of this.questionsWithOptions) {
- const selectedOptionId = this.answers[question.QuestionId];
- if (selectedOptionId) {
- const optionPointer: Pointer = {
- __type: "Pointer",
- className: "Option",
- objectId: selectedOptionId // 确保使用 objectId
- };
- answersPointers.push(optionPointer);
- }
- }
- const questionnaireResult = new CloudObject("QuestionnaireResult");
- questionnaireResult.set({
- QuestionnaireResultId: `qr_${new Date().getTime()}`, // 生成唯一的 QuestionnaireResultId
- userId: { __type: "Pointer", className: "_User", objectId: "user1" }, // 替换为实际的用户ID
- questionnaireId: { __type: "Pointer", className: "Questionnaire", QuestionnaireId: this.questionnaire.QuestionnaireId },
- answers: answersPointers
- });
- await questionnaireResult.save();
- console.log("问卷提交成功。");
- // 可选:清空表单
- this.name = '';
- this.birthday = '';
- this.answers = {};
- } catch (error) {
- console.error("提交问卷时出错:", error);
- }
- }*/
- }
|