import { Component, OnInit } from '@angular/core';
import { IonicModule } from '@ionic/angular';
import { FormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';  // 导入 CommonModule
import { TagInputComponent } from '../tag-input/tag-input.component';
import { addIcons } from 'ionicons';
import { barbellOutline, personOutline, square, alarmOutline } from 'ionicons/icons';

@Component({
  selector: 'app-test-page',
  templateUrl: './test-page.component.html',
  styleUrls: ['./test-page.component.scss'],
  standalone: true,
  imports: [IonicModule, FormsModule, CommonModule, TagInputComponent]  // 添加 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;  // 是否正在生成计划
  messageList: any[] = [];  // 存储消息列表

  constructor() {
    addIcons({ personOutline, barbellOutline, alarmOutline, square });
  }

  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;
  }

  async generatePlan() {
    this.isGenerating = true;  // 开始生成计划时禁用按钮
    this.generatedPlan = '';  // 清空之前的结果
    this.messageList = [];  // 清空旧的消息列表，避免重复内容

    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 TOKEN = `r:E4KpGvTEto-131588121831732778669`;
    localStorage.setItem("token", TOKEN);

    let messageList: any = [
      { role: "system", content: `开始生成健身计划：${new Date().toDateString()}` },
      { role: "user", content: prompt }
    ];

    let bodyJson = {
      "token": `Bearer ${TOKEN}`,
      "messages": messageList,
      "model": "fmode-4.5-128k",
      "temperature": 0.5,
      "presence_penalty": 0,
      "frequency_penalty": 0,
      "top_p": 1,
      "stream": true
    };

    let response = await fetch("https://test.fmode.cn/api/apig/aigc/gpt/v1/chat/completions", {
      "headers": {
        "accept": "text/event-stream",
        "sec-fetch-dest": "empty",
        "sec-fetch-mode": "cors",
        "sec-fetch-site": "same-site"
      },
      "body": JSON.stringify(bodyJson),
      "method": "POST",
      "mode": "cors",
      "credentials": "omit"
    });

    let reader = response.body?.getReader();
    if (!reader) {
      throw new Error("Failed to get the response reader.");
    }

    let buffer = "";
    const decoder = new TextDecoder();  // 定义 TextDecoder
    while (true) {
      let { done, value } = await reader.read();
      if (done) break;

      let data = decoder.decode(value);
      buffer += data;  // 保留数据流中的内容

      let messages = buffer.split("\n");
      buffer = messages.pop() || "";  // 保留未处理的部分

      messages.forEach(message => {
        let dataText: string = message.split("data: ")[1];
        if (dataText && dataText.startsWith("{")) {
          try {
            let json = JSON.parse(dataText);
            let content = json?.choices?.[0]?.delta?.content;
            if (content) {
              console.log(content);
              this.generatedPlan += content;  // 追加内容
            }
          } catch (err) {
            console.error('生成计划失败:', err);
          }
        }
      });
    }

    this.isGenerating = false;  // 生成结束后恢复按钮
  }
}
