import { Component, OnInit } from '@angular/core';
import { IonicModule, ToastController } from '@ionic/angular';
import { FormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';
import { TagInputComponent } from '../tag-input/tag-input.component';
import { addIcons } from 'ionicons';
import { barbellOutline, chevronBackOutline, closeCircleOutline, checkmarkCircleOutline, fitness, personOutline, square, alarmOutline, arrowBack } from 'ionicons/icons';
import { DalleOptions, FmodeChatCompletion, MarkdownPreviewModule } from 'fmode-ng';
import { LoadingController } from '@ionic/angular';
import { AlertController, IonThumbnail, IonBadge, IonButton, IonButtons, IonCard, IonCardContent, IonCardHeader, IonCardSubtitle, IonCardTitle, IonCol, IonContent, IonGrid, IonHeader, IonIcon, IonImg, IonInput, IonItem, IonLabel, IonList, IonRow, IonSegment, IonSegmentButton, IonSelect, IonSelectOption, IonToolbar, IonTitle, IonSpinner, IonTextarea, IonProgressBar, ModalController } from '@ionic/angular/standalone';
import { NavController } from '@ionic/angular';
import { Router } from '@angular/router';
import { CloudObject, CloudQuery, CloudUser } from 'src/lib/ncloud';
import { extractAllJsonFromString } from '../agent/agent.json';
import { IonBackButton } from '@ionic/angular/standalone';
@Component({
  selector: 'app-test-page',
  templateUrl: './test-page.component.html',
  styleUrls: ['./test-page.component.scss'],
  standalone: true,
  imports: [
    IonTextarea,
    IonSpinner,
    IonTitle,
    IonBackButton,
    MarkdownPreviewModule,
    IonSelectOption,
    IonSelect,
    IonThumbnail,
    IonCardSubtitle,
    IonImg,
    IonCard,
    IonCardTitle,
    IonCardHeader,
    IonCardContent,
    IonButtons,
    IonItem,
    IonList,
    IonIcon,
    FormsModule,
    CommonModule,
    IonHeader,
    IonToolbar,
    IonContent,
    IonSegment,
    IonSegmentButton,
    IonGrid,
    IonRow,
    IonCol,
    IonButton,
    IonLabel,
    IonBadge,
    IonInput,
    TagInputComponent,
    IonProgressBar
  ]  // 添加 CommonModule
})
export class TestPageComponent implements OnInit {
  selectedTags: string[] = [];
  exercisePreference: string = '';
  workoutFrequency: string = '';
  height: number | null = null;
  weight: number | null = null;
  age: number | null = null;
  goalDescription: string = '';
  generatedPlan: string = '';  // 用来存储生成的健身计划
  isGenerating: boolean = false;  // 是否正在生成计划
  isRevert: boolean = false
  messageList: any[] = [];  // 存储消息列表
  planReady: boolean = false;  // 是否可以显示确认按钮
  constructor(private toastController: ToastController,
    private modalCtrl: ModalController,
    private router: Router,
    private navCtrl: NavController
  ) {
    addIcons({ chevronBackOutline, fitness, personOutline, closeCircleOutline, barbellOutline, alarmOutline, square, arrowBack, checkmarkCircleOutline, });
  }
  ngOnInit() { }

  onTagsChanged(tags: string[]) {
    this.selectedTags = tags;
    console.log('当前标签:', this.selectedTags);
  }

  onGoalDescriptionChange(event: any) {
    this.goalDescription = event.detail.value;
  }

  onExercisePreferenceChange(event: any) {
    this.exercisePreference = event.detail.value;
  }

  onWorkoutFrequencyChange(event: any) {
    this.workoutFrequency = event.detail.value;
  }

  onHeightChange(event: any) {
    this.height = event.detail.value;
  }

  onWeightChange(event: any) {
    this.weight = event.detail.value;
  }

  onAgeChange(event: any) {
    this.age = event.detail.value;
  }

  // 显示toast提示
  async showToast(message: string) {
    const toast = await this.toastController.create({
      message: message,
      duration: 2000,
      position: 'top',
      color: 'danger',
    });
    toast.present();
  }

  async generatePlan() {
    // 检查身高和体重是否为空
    if (!this.height || !this.weight) {
      // 如果为空，显示提示信息
      await this.showToast('身高或体重为空，无法生成个人健身计划');
      return; // 退出函数，不继续生成健身计划
    }
    this.generatedPlan = '';
    this.messageList = [];
    this.isGenerating = true;
    this.isRevert = true
    console.log('生成健身计划', {
      tags: this.selectedTags,
      exercisePreference: this.exercisePreference,
      workoutFrequency: this.workoutFrequency,
      height: this.height,
      weight: this.weight,
      age: this.age,
      goalDescription: this.goalDescription
    });

    let prompt = `您作为一名专业的健身计划定制大师，请帮我根据以下情况制定健身计划(健身计划请给每天的运动标上序号)。关键词：${this.selectedTags.join(",")},目标描述:${this.goalDescription},运动偏好:${this.exercisePreference},
    健身频率每周:${this.workoutFrequency},身高:${this.height}cm,体重:${this.weight}kg,年龄:${this.age},注意：训练部位给出具体部位(如胸部，腿部),具体次数,组数。一般一天一个部位。具体计划只需给出训练日计划,训练日只做四个运动`;

    let messageList = new FmodeChatCompletion([
      { role: "system", content: '' },
      { role: "user", content: prompt }
    ]);

    messageList.sendCompletion().subscribe((message: any) => {
      console.log(message.content);
      this.generatedPlan = message.content;
      if (message?.complete) {
        this.isGenerating = false;
        this.getJson()
      }
    });
  }
  public gptre = ""
  title: string = "123"
  chatID = ""
  complete: boolean = false
  planArray: any
  JSONcomplete: boolean = false
  JSONdes = ""

  JSONobject: { [key: string]: string } = {}
  getJson() {
    let promt = `请你以以下json格式分每天来整合文段内容：
    {
    "date":"周几运动",
    "srcId": "plan001等等",
    "trainingPart":"训练部位如(胸部,腿部)",
    "trainingItems":"四个运动项目,以下面形式给出,形式如下"[
  {
    "item": "引体向上",
    "reps": 8,
    "sets": 4
  },
  {
    "item": "划船",
    "reps": 10,
    "sets": 3
  },
  {
    "item": "背部伸展",
    "reps": 12,
    "sets": 3
  },
  {
    "item": "拉力器划船",
    "reps": 12,
    "sets": 3
  }
]"
}
    内容如下：${this.generatedPlan}
`

    let completion = new FmodeChatCompletion([
      { role: "system", content: "" },
      { role: "user", content: promt }
    ])
    completion.sendCompletion().subscribe((message: any) => {
      console.log(message.content)
      this.JSONdes = message.content;

      if (message?.complete) {
        console.log("json:", this.JSONdes);
        this.generatedPlan = message.content;
        this.planArray = extractAllJsonFromString(this.JSONdes);
        this.isRevert = false
        this.planReady = true;
        console.log(this.planArray)
        // planArray.forEach((plan: any) => {
        //   plan.detail = this.generatedPlan; // 添加额外的计划内容
        //   console.log(plan);

        //   // 准备插入数据库的数据对象
        //   let newPlan = {
        //     "date": plan['date'],
        //     "srcId": plan['srcId'],
        //     "trainingPart": plan['trainingPart'],
        //     "trainingItems": plan['trainingItems'],
        //     "user": new CloudUser().toPointer(),
        //   };

        //   // 创建新的 CloudObject 实例
        //   let newObject = new CloudObject("fitPlan");
        //   newObject.set(newPlan);
        //   newObject.save()
        //     .then(() => {
        //       console.log("计划保存成功");
        //     })
        //     .catch((error: any) => {
        //       console.error("保存计划时发生错误", error);
        //     });
        // });
        // this.JSONcomplete = true;
      }
    });
  }
  confirmPlan() {
    this.savePlanToDatabase(this.generatedPlan);
  }
  discardPlan() {
    this.generatedPlan = ""
    this.dismiss()
  }
  backPage() {
    this.dismiss()
  }
  async savePlanToDatabase(plan: string) {
    let currentUser = new CloudUser().toPointer();
    console.log(currentUser)
    console.log('计划保存到数据库', plan);
    const cloudQuery = new CloudQuery("fitPlan");
    cloudQuery.equalTo("user", currentUser)
    try {
      const userPlans = await cloudQuery.find();
      console.log("找到的计划数量:", userPlans.length);

      // 删除当前用户的所有计划
      for (const planObj of userPlans) {
        await planObj.destroy();
        console.log("已删除计划:", planObj);
      }
      this.planArray.forEach((plan: any) => {
        plan.detail = this.generatedPlan;
        console.log(plan);
        // 准备插入数据库的数据对象
        let newPlan = {
          "date": plan['date'],
          "srcId": plan['srcId'],
          "trainingPart": plan['trainingPart'],
          "trainingItems": plan['trainingItems'],
          "user": currentUser,
        };
        // 创建新的 CloudObject 实例
        let newObject = new CloudObject("fitPlan");
        newObject.set(newPlan);
        newObject.save()
          .then(() => {
            console.log("计划保存成功");
            this.dismiss()
          })
          .catch((error: any) => {
            console.error("保存计划时发生错误", error);
          });
      });
      this.JSONcomplete = true;
    } catch (error) {
      console.error("查询或删除计划时发生错误", error);
    }
  }
  dismiss() {
    this.modalCtrl.dismiss();
  }
  goBack() {
    this.navCtrl.back();
  }

}
