import wordTableApi from '@/api/subject/wordTable'
import obj from '@/utils/obj'

export const useWordBookSelect = defineStore('word-book-select', () => {
  const stageOptions = [
    {
      label: '小学',
      value: 1,
    },
    {
      label: '初中',
      value: 2,
    },
    {
      label: '高中',
      value: 3,
    },
  ]
  const stageMap = obj.options2map(stageOptions)
  const versionsMap = {} as any
  const textbooksMap = {} as any
  const chaptersMap = {} as any

  async function getVersions(stageId: any) {
    let versions = versionsMap[stageId]
    if (!versions) {
      versions = await wordTableApi.getTextbookVersion(stageId)
      versionsMap[stageId] = versions
    }
    return versions
  }

  async function getVersionOptions(stageId: any) {
    return (await getVersions(stageId)).map((item: any) => ({
      label: item.name,
      value: item.id,
    }))
  }

  async function getTextbooks(versionId: any) {
    let textbooks = textbooksMap[versionId]
    if (!textbooks) {
      textbooks = await wordTableApi.getTextbookList(versionId)
      textbooksMap[versionId] = textbooks
    }
    return textbooks
  }

  async function getChapters(bookId: any) {
    let chapters = chaptersMap[bookId]
    if (!chapters) {
      chapters = await wordTableApi.getChapterList(bookId)
      chaptersMap[bookId] = chapters
    }
    return chapters
  }

  async function getTextbookOptions(versionId: any) {
    return (await getTextbooks(versionId)).map((item: any) => ({
      label: item.name,
      value: item.id,
    }))
  }

  return {
    stageOptions,
    stageMap,
    getVersions,
    getVersionOptions,
    getTextbooks,
    getTextbookOptions,
    getChapters,
  }
})
