// chapter-generator.page.ts
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms'; // 导入 FormsModule
import { IonRouterOutlet } from '@ionic/angular/standalone';
import { addIcons } from 'ionicons';
import { add } from 'ionicons/icons';
import { chevronForward } from 'ionicons/icons';
import { IonicModule, ModalController } from '@ionic/angular';
import { CommonModule } from '@angular/common';
import { AiExpandModalComponent } from '../ai-expand-modal/ai-expand-modal.component';
import { AiPolishModalComponent } from '../ai-polish-modal/ai-polish-modal.component';
import { AiContinueModalComponent } from '../ai-continue-modal/ai-continue-modal.component';
import { OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { CloudObject, CloudQuery } from '../lib/ncloud';
addIcons({ chevronForward });

@Component({
  selector: 'app-chapter-generator',
  templateUrl: './chapter-generator.page.html',
  styleUrls: ['./chapter-generator.page.scss'],
  standalone: true,
  imports: [
    FormsModule,
    IonRouterOutlet,
    CommonModule,
    IonicModule,
    AiExpandModalComponent,
    AiPolishModalComponent,
    AiContinueModalComponent
    ]
})
export class ChapterGeneratorPage implements OnInit {
  chapters:Array<CloudObject> = [];
  isSideShow: boolean = true;
  selectedChapterIndex: number | 0 = 0;
  selectedChapterTitle: string = '';
  selectedChapterContent: string = '';

  title: string = '';
  description: string = '';

  constructor(private modalCtrl: ModalController, private route: ActivatedRoute) {  
    addIcons({ add });
  }

  story:CloudObject|undefined
  async loadStory(){
    let query = new CloudQuery("Book");
    query.equalTo("title",this.title);
    this.story = await query.first()
    if(!this.story?.id){
      this.story = new CloudObject("Book");
      this.story.set({
        title:this.title,
        desc:this.description
      })
    }
    console.log(this.story)
    if(this.story?.id){
      let queryc = new CloudQuery("BookChapter")
      queryc.equalTo("story",this.story?.id)
      let list = await queryc.find();
      console.log(list)
      if(list?.length){
        this.chapters = list;
      }
      if(!this.chapters?.length){
        let citem = new CloudObject("BookChapter")
        citem.set({
          title:"新章节",
          index:1,
          content:""
        })
        this.chapters = [citem];
      }
    }
    console.log(this.chapters)
  }
  ngOnInit() {
    this.route.queryParams.subscribe(params => {
      this.title = params['title'];
      this.description = params['description'];
      console.log('Received Title:', this.title);
      console.log('Received Description:', this.description);
      this.loadStory();
    });
  }
  async openAiExpandModal() {
    const modal = await this.modalCtrl.create({
      component: AiExpandModalComponent,
      componentProps: {
        onInsertText: (text: string) => this.insertTextIntoChapterEnd(text)
      }
    });
    return await modal.present();
  }

  async openAiPolishModal() {
    const modal = await this.modalCtrl.create({
      component: AiPolishModalComponent,
      componentProps: {
        onInsertText: (text: string) => this.insertTextIntoChapterEnd(text)
      }
    });
    return await modal.present();
  }

  async openAiContinueModal() {
    const modal = await this.modalCtrl.create({
      component: AiContinueModalComponent,
      componentProps: {
        onInsertText: (text: string) => this.insertTextIntoChapterEnd(text)
      }
    });
    return await modal.present();
  }

  toggleSide() {
    this.isSideShow = !this.isSideShow;
  }

  addChapter() {
    let newChapter = new CloudObject("BookChapter");
    newChapter.set({ title: `新章节 ${this.chapters.length + 1}`, content: '' })
    this.chapters.push(newChapter);
    this.selectChapter(this.chapters.length - 1); // 自动编辑新添加的章节
  }

  deleteChapter(index: number) {
    if (index === this.selectedChapterIndex) {
      this.selectedChapterIndex = 0;
      this.selectedChapterTitle = '';
      this.selectedChapterContent = '';
    }
    this.chapters.splice(index, 1);
  }

  selectChapter(index: number) {
    this.editChapter(index);
    this.isSideShow = false; // 隐藏侧边栏
  }

  editChapter(index: number) {
    this.selectedChapterIndex = index;
    this.selectedChapterTitle = this.chapters[index]?.get("title");
    this.selectedChapterContent = this.chapters[index]?.get("content"); // 初始化内容为当前章节的内容
  }

  async saveChapter() {
    await this.story?.save();
    let query = new CloudQuery("BookChapter");
    query.equalTo("story",this.story?.id);
    query.equalTo("index",this.selectedChapterIndex+1)
    let storyChapter = new CloudObject("BookChapter");
    storyChapter.set({
      index:this.selectedChapterIndex+1,
      title:this.selectedChapterTitle,
      content:this.selectedChapterContent,
      story:this.story?.toPointer()
    })
    storyChapter.save();
  }

  insertTextIntoChapterEnd(text: string) {
    if (this.selectedChapterIndex !== null) {
      this.chapters[this.selectedChapterIndex].set({
        "content":this.chapters[this.selectedChapterIndex].get("content") + text
      });
      this.selectedChapterContent += text; // 更新显示的内容
    }
  }
}