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 } 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() { }

  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);
    }
  }*/
}
