import obj from '#/utils/obj'

export function useChapter() {
  const { editQuestion } = inject('sharedData') as any

  // 章节
  const chapterRef = ref()
  const chapterSearchText = ref('')
  const chapters = ref([] as any)
  const defaultExpandedChapters = ref([] as any)
  watch(
    () => chapterSearchText.value,
    (v) => {
      // eslint-disable-next-line unicorn/no-array-callback-reference
      chapterRef.value.filter(v)
    },
  )
  const chapterFilter = (v: any, chapter: any) => {
    if (!v) return true
    return chapter.name.toLowerCase().includes(v.toLowerCase())
  }

  // 初始化数据
  const initChapterData = async () => {
    const checkedKeys = editQuestion.value.chapterIds || []
    // 设置章节选中
    chapterRef.value.setCheckedKeys(checkedKeys)
    const set = new Set()
    for (const key of checkedKeys) {
      for (const pid of obj.findParentIds(chapters.value, key)) {
        set.add(pid)
      }
    }
    defaultExpandedChapters.value = [...set]
  }

  return {
    initChapterData,
    chapterRef,
    chapterSearchText,
    chapters,
    chapterFilter,
    defaultExpandedChapters,
  }
}
