import obj from '#/utils/obj'

export function useKnowledge() {
  const { editQuestion } = inject('sharedData') as any
  const knowledgeRef = ref()
  const knowledgeSearchText = ref('')
  const knowledgeList = ref([] as any)
  const defaultExpandedKnowledge = ref([] as any)
  watch(
    () => knowledgeSearchText.value,
    (v) => {
      // eslint-disable-next-line unicorn/no-array-callback-reference
      knowledgeRef.value.filter(v)
    },
  )
  const handleKnowledgeCheck = (knowledge: any, checked: boolean) => {
    if (checked) {
      // 取消之前选中的节点
      knowledgeRef.value.setCheckedKeys([knowledge.id])
    }
  }

  // 初始化数据
  const initKnowledgeData = async () => {
    const checkedKeys = editQuestion.value.knowledgeIds || []
    // 设置知识点选中
    knowledgeRef.value.setCheckedKeys(checkedKeys)

    const set = new Set()
    for (const key of checkedKeys) {
      for (const pid of obj.findParentIds(knowledgeList.value, key)) {
        set.add(pid)
      }
    }
    defaultExpandedKnowledge.value = [...set]
  }
  return {
    knowledgeRef,
    knowledgeSearchText,
    knowledgeList,
    handleKnowledgeCheck,
    initKnowledgeData,
    defaultExpandedKnowledge,
  }
}
