import { CommonModule } from '@angular/common';
import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import {
  IonButton,
  IonContent,
  IonHeader,
  IonIcon,
  IonInput,
  IonItem,
  IonLabel,
  IonSpinner,
  IonTextarea,
  IonTitle,
  IonToolbar,
} from '@ionic/angular/standalone';
import { FmodeChatCompletion, MarkdownPreviewModule } from 'fmode-ng';

@Component({
  selector: 'app-page-dream-analysis',
  templateUrl: './page-dream-analysis.component.html',
  styleUrls: ['./page-dream-analysis.component.scss'],
  encapsulation: ViewEncapsulation.None, // 添加这一行
  standalone: true,
  imports: [
    IonHeader,
    IonToolbar,
    IonTitle,
    IonIcon,
    IonContent,
    IonButton,
    IonTextarea,
    IonInput,
    IonItem,
    IonLabel,
    IonSpinner,
    MarkdownPreviewModule,
    CommonModule,
  ],
})
export class PageDreamAnalysisComponent implements OnInit {
  background: string = '梦境背景';
  userPrompt: string = '请描述您的梦境内容';
  responseMsg: string = '';
  isComplete: boolean = false;
  isLoading: boolean = false; // 新增

  ngOnInit(): void {}

  backgroundInput(event: CustomEvent) {
    this.background = event.detail.value;
  }

  promptInput(event: CustomEvent) {
    this.userPrompt = event.detail.value;
  }

  sendMessage() {
    this.isComplete = false;
    this.isLoading = true; // 开始加载
    const PromptTemplate = `
      对于最近发生的${this.background}，请你作为一名解梦师，根据用户的梦境描述，给出一些解释和建议。
      以下是用户的梦境：${this.userPrompt}
    `;

    const completion = new FmodeChatCompletion([
      { role: 'system', content: '你是一名专业的解梦师。' },
      { role: 'user', content: PromptTemplate },
    ]);

    completion.sendCompletion().subscribe(
      (message: any) => {
        this.responseMsg = message.content;
        if (message?.complete) {
          this.isLoading = false; // 加载结束
          this.isComplete = true; // 解析完成
        }
      },
      (error: any) => {
        console.error('AI 回复错误:', error);
        this.responseMsg = '抱歉，发生了错误。请稍后再试。';
        this.isLoading = false; // 加载结束
        this.isComplete = true;
      }
    );
  }
}