// ai-expand-modal.component.ts
import { Component, Input } from '@angular/core';
import { ModalController } from '@ionic/angular';
import {
  IonButton, IonIcon, IonInput, IonItem, IonLabel,
  IonToolbar, IonHeader, IonContent, IonTitle, IonButtons,
  IonTextarea
} from '@ionic/angular/standalone';
import { FormsModule } from '@angular/forms'; // 导入 FormsModule
import { FmodeChatCompletion, MarkdownPreviewModule } from 'fmode-ng';

@Component({
  selector: 'app-ai-expand-modal',
  templateUrl: './ai-expand-modal.component.html',
  styleUrls: ['./ai-expand-modal.component.scss'],
  standalone: true,
  imports: [
    IonButton, IonIcon, IonInput, IonItem, IonTitle, FormsModule,
    IonLabel, IonToolbar, IonHeader, IonContent, IonButtons, MarkdownPreviewModule, IonTextarea
  ]
})
export class AiExpandModalComponent {
  inputText: string = '';
  expandedText: string = '';
  userPrompt: string = "";
  responseMsg: any = "";
  isComplete: boolean = false;

  @Input() onInsertText?: (text: string) => void;

  constructor(private modalCtrl: ModalController) { }

  dismiss() {
    this.modalCtrl.dismiss();
  }

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

  sendMessage() {
    console.log("create");

    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;
      this.expandedText = message.content; // 将生成的内容赋值给 expandedText
      if (message?.complete) { // 判断message为完成状态，则设置isComplete为完成
        this.isComplete = true;
      }
    });
  }

  copyExpandedText() {
    navigator.clipboard.writeText(this.expandedText).then(() => {
      alert('文本已复制到剪贴板');
    }, (err) => {
      console.error('未能复制文本:', err);
    });
  }

  insertIntoChapterEnd() {
    // 检查是否有选择的章节
    if (this.expandedText && this.onInsertText) {
      this.onInsertText(this.expandedText);
      this.dismiss();
    } else {
      alert('请先生成扩写内容');
    }
  }

  regenerate() {
    // 清空输入框和结果区域
    this.userPrompt = '';
    this.responseMsg = '';
    this.expandedText = '';
    this.isComplete = false;
    // 重新发送请求
    this.sendMessage();
  }
}