import { ChapterTypeKeywords, ChapterTypeLabels, type Chapter, type ChapterType } from "@/types/report.types";
import Nzh from "nzh";

/**
 * 章节管理器
 */
export class ChapterManager {
  private chapters: Chapter[];

  constructor() {
    this.chapters = [];
  }

  public addChapter(chapterType: ChapterType) {
    const item = ChapterTypeLabels.find((item) => item.key == chapterType);
    const keywordsItem = ChapterTypeKeywords.find((item) => item.key == chapterType);
    if (item) {
      this.chapters.push({
        title: item.label,
        fullTitle: this.getTitleWithChineseNum(this.chapters.length, item.label),
        content: '',
        chapterType: chapterType,
        keywords: keywordsItem?.keywords || [],
      });
    }
  }

  public addChapters(chapterTypes: ChapterType[]) {
    for (const type of chapterTypes) {
      this.addChapter(type);
    }
  }

  public getChapter(index: number) {
    return this.chapters[index];
  }

  private getTitleWithChineseNum(index: number, title: string) {
    return Nzh.cn.encodeS(index+1) + '、' + title
  }

  public setChapter(index: number, data: Chapter) {
    const chapter = this.chapters[index]
    this.chapters[index] = {
      ...chapter,
      ...data,
      fullTitle: this.getTitleWithChineseNum(index, chapter.title)
    };
  }

  public setChapters(chapters: Chapter[]) {
    this.chapters = chapters;
  }

  public getChapters(): Chapter[] {
    return this.chapters.map((chapter, index) => {
      const fullTitle = this.getTitleWithChineseNum(index, chapter.title)
      return { ...chapter, fullTitle };
    });
  }

  public moveUp(index: number) {
    if (index < 1) {
      return;
    }
    const temp = this.chapters[index-1];
    this.chapters[index-1] = this.chapters[index]
    this.chapters[index] = temp
  }

  public moveDown(index: number) {
    if (index >= this.chapters.length-1) {
      return;
    }
    const temp = this.chapters[index+1];
    this.chapters[index+1] = this.chapters[index]
    this.chapters[index] = temp
  }

  public remove(index: number) {
    if (index >= 0 && index < this.chapters.length) {
      this.chapters.splice(index, 1)
    }
  }
}
