import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { IonicModule } from '@ionic/angular';
import { NavController } from '@ionic/angular/standalone';
import { addIcons } from 'ionicons';
import { arrowBackOutline } from 'ionicons/icons';
addIcons({ arrowBackOutline });
/** 引用：从fmode-ng库引用FmodeChatCompletion类 */
import { ChatImageContentItem, FmodeChatCompletion } from 'fmode-ng';
import { DalleOptions, ImagineWork } from 'fmode-ng';
@Component({
  selector: 'app-generate-result',
  templateUrl: './generate-result.component.html',
  styleUrls: ['./generate-result.component.scss'],
  standalone: true,
  imports: [IonicModule],
})

export class GenerateResultComponent implements OnInit {
  constructor(private route: ActivatedRoute, private router: Router, private navCtrl: NavController) {
    // 示例任务，自己生成图片后请存储新的ID
    this.imagineWork = new ImagineWork("lpJGiFwWeA");
    this.imagineWork.fetchTask().then(work => {
      this.images = this.imagineWork?.images || [];
    });
  }
  userPrompt: string = "";
  responseMsg: any = "";
  imagineWork: ImagineWork | undefined;
  images: Array<string> = [];

  ngOnInit() {
    this.route.queryParams.subscribe(params => {
      this.userPrompt = params['userPrompt'] || "";
    });
    console.log(this.userPrompt)
    this.createImage()
  }
  goBack() {
    this.navCtrl.back();
  }

  async createImage() {
    this.imagineWork = new ImagineWork();
    // 文本生成
    let PromptTemplate = `${this.userPrompt}`
    let completion = new FmodeChatCompletion([
      { role: "system", content: "" },
      { role: "user", content: PromptTemplate }
    ])
    completion.sendCompletion().subscribe((message: any) => {
      // 打印消息体
      console.log(message.content)
      // 赋值消息内容给组件内属性
      this.responseMsg = message.content
      if (message?.complete) { // 判断message为完成状态，则设置isComplete为完成
        // 图片生成
        let PicturePrompt = `${this.responseMsg}`
        let options: DalleOptions = { prompt: PicturePrompt }
        this.imagineWork?.draw(options).subscribe(work => {
          console.log("imagineWork", work?.toJSON())
          console.log("images", work?.get("images"))
          if (work?.get("images")?.length) {
            this.images = work?.get("images");
          }
        })
      }
    })


  }

}
