import { CommonModule } from '@angular/common';
import { Component, OnInit } from '@angular/core';
import { IonHeader, IonToolbar, IonTitle, IonContent } from '@ionic/angular/standalone';
import { IonInput, IonTextarea, IonButton } from "@ionic/angular/standalone";
import { DalleOptions, FmodeChatCompletion, ImagineWork, MarkdownPreviewModule } from 'fmode-ng';

@Component({
  selector: 'app-page-createpic',
  templateUrl: './page-createpic.component.html',
  styleUrls: ['./page-createpic.component.scss'],
  standalone: true,
  imports: [
    IonHeader, IonToolbar, IonTitle, IonContent,
    IonButton, IonInput,
    IonTextarea, MarkdownPreviewModule,CommonModule
  ],
})
export class PageCreatepicComponent implements OnInit {

  userPrompt: string = "云想衣裳花想容，春风拂槛露华浓。若非群玉山头见，会向瑶台月下逢";
  promptInput(ev: any) {
    this.userPrompt = ev.detail.value;
  }

  imagineWork: ImagineWork | undefined;
  images: Array<string> = [];
  responseMsg: string | undefined; // 添加用于接收生成的消息内容

  constructor() {
    this.imagineWork = new ImagineWork(); // 初始化 ImagineWork 实例
  }

  async createImage() {
    let PromptTemplate = `
    请您作为一位专业的画家，分析以下古诗中的情感、意象和色彩。请考虑以下要素，并将其转化为视觉艺术的表现：

    1. **情感表达**：这首诗传达了哪些情感？是快乐、悲伤、怀念还是其他？
    2. **意象描绘**：诗中使用了哪些意象？它们分别代表什么？
    3. **色彩运用**：根据诗的情感和意象，您会选择哪些颜色进行表达？
    4. **画面构图**：您如何想象画面的构图？有哪些元素值得突出？

    古诗：
    ${this.userPrompt}
    `;


    let completion = new FmodeChatCompletion([
      { role: "system", content: "" },
      { role: "user", content: PromptTemplate }
    ]);

    completion.sendCompletion().subscribe({
      next: (message: any) => {
        console.log(message.content);
        this.responseMsg = message.content;
        if (message?.complete && this.imagineWork) { // 确保 imagineWork 已初始化
          let options: DalleOptions = { prompt: this.userPrompt };
          this.imagineWork.draw(options).subscribe({
            next: (work) => {
              console.log("imagineWork", work?.toJSON());
              if (work?.get("images")?.length) {
                this.images = work.get("images");
              }
            },
            error: (err) => {
              console.error("Error drawing image: ", err);
            }
          });
        } else {
          console.error("ImagineWork is not initialized or message is not complete.");
        }
      },
      error: (err) => {
        console.error("Error sending completion: ", err);
      }
    });
  }

  ngOnInit() {}
}
