// ai-polish-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';
import { FmodeChatCompletion, MarkdownPreviewModule } from 'fmode-ng';

@Component({
  selector: 'app-ai-polish-modal',
  templateUrl: './ai-polish-modal.component.html',
  styleUrls: ['./ai-polish-modal.component.scss'],
  standalone: true,
  imports: [
    IonButton, IonIcon, IonInput, IonItem, IonTitle, FormsModule,
    IonLabel, IonToolbar, IonHeader, IonContent, IonButtons, MarkdownPreviewModule, IonTextarea
  ]
})
export class AiPolishModalComponent {
  inputText: string = '';
  polishedText: 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.polishedText = message.content; // 将生成的内容赋值给 polishedText
      if (message?.complete) { // 判断message为完成状态，则设置isComplete为完成
        this.isComplete = true;
      }
    });
  }

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

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

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