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

@Component({
  selector: 'app-page-create',
  templateUrl: './page-create.component.html',
  styleUrls: ['./page-create.component.scss'],
  standalone: true,
  imports: [IonBackButton, IonIcon, IonButtons, IonHeader, IonToolbar, IonTitle, IonContent, IonButton, IonTextarea, IonInput, MarkdownPreviewModule
    ,CommonModule
  ],
})
export class PageCreateComponent implements OnInit {
  isComplete: boolean = false;
  error: string | null = null; // 添加错误状态
  ngOnInit() {this.checkUserLogin()}
  checkUserLogin() {
    if (!this.currentUser?.id) {
      this.router.navigate(['/login']);
    }
  }
  content: { title: string } = { title: '诗创' };
  currentUser: CloudUser|undefined;
  constructor(private ActivatedRoute: ActivatedRoute, private router: Router) {
    this.currentUser = new CloudUser();
  }

  style: string = "诗句格式";
  styleInput(ev: any) {
    this.style = ev.detail.value;
    this.isComplete = false;
    this.responseMsg = '';
  }

  userPrompt: string = "请描述你的诗歌需求";
  promptInput(ev: any) {
    this.userPrompt = ev.detail.value;
    this.isComplete = false;
    this.responseMsg = '';
  }

  responseMsg: any = "";

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

    console.log("create");

    let PromptTemplate = `
    您作为一位专业的${this.style}诗歌创作者，请您根据以下用户需求创作一首符合格式的诗歌：

    1. 主题：用户希望表达的主题（例如：爱情、自然、时间等）
    2. 感官体验：用户期望使用的视觉、听觉等感官细节描述
    3. 情感表达：用户想要传达的情感，例如：快乐、悲伤、怀念等
    4. 诗歌格式：请按照以下格式创作诗歌
    - 诗歌的行数：要求的行数
    - 每行字数：例如：五言、七言
    - 韵律：是否需要押韵

    以下是用户的需求：
    ${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) {
        this.isComplete = true;
        this.saveCreation();
      }
    });
  }
  saveCreation() {
    if (!this.currentUser?.id) {
      this.error = '请先登录';
      alert('请先登录');
      return;
    }

    const creationData = {
      title: this.content.title,
      content: this.responseMsg,
      style: this.style,
      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('保存创作时出错');
    });
  }
}