import { CommonModule } from '@angular/common';
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { IonHeader, IonToolbar, IonTitle, IonContent, IonButtons, IonBackButton } from '@ionic/angular/standalone';
import { IonInput, IonTextarea, IonButton } from "@ionic/angular/standalone";
import { DalleOptions, FmodeChatCompletion, ImagineWork, MarkdownPreviewModule } from 'fmode-ng';
import {  CloudObject, CloudQuery, CloudUser} from 'src/lib/ncloud';

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

  userPrompt: string = "云想衣裳花想容，春风拂槛露华浓。若非群玉山头见，会向瑶台月下逢";
  responseMsg: string | undefined; 
  images: Array<string> = [];
  imagineWork: ImagineWork | undefined;
  currentUser: CloudUser | undefined;
  error: string | undefined;


  constructor(private router: Router) {
    this.imagineWork = new ImagineWork();
    this.currentUser = new CloudUser();
  }

  ngOnInit() {
    this.checkUserLogin();
  }

  checkUserLogin() {
    if (!this.currentUser?.id) { // 使用可选链操作符
      this.router.navigate(['/tabs/login']);
    }
  }

  promptInput(ev: any) {
    this.userPrompt = ev.detail.value;
  }

  clearPrompt() {
    this.userPrompt = ''; // 清空示例诗句内容
  }

  async createImage() {

    if (!this.currentUser?.id) {
      this.router.navigate(['/tabs/login']);
      return;
    }

    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) {
          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);
      }
    });
  }
  saveCreation() {
    if (!this.currentUser?.id) {
      this.error = '请先登录';
      alert('请先登录');
      return;
    }

    const creationData = {
      title: this.content.title,
      content: this.responseMsg,
      style: '绘画',
      images: JSON.stringify(this.images)
    };

    const creation = new CloudObject("PL_Creations");
    creation.set(creationData);
    creation.set({
      'user_id': this.currentUser.toPointer()
    });

    creation.save().then((savedCreation) => {
      console.log('Creation saved with ID:', savedCreation.id);
      alert('创作已保存');
    }).catch((error) => {
      console.error('Error saving creation:', error);
      alert('保存创作时出错');
    });
  }
  content: { title: string } = { title: '画创' };
}