<template>
    <el-input v-model="keyword" placeholder="请输入知识点名称" clearable prefix-icon="Search" style="margin-bottom: 20px"/>
    <el-tree ref="treeRef" v-if="knowledges.length" :data="knowledges" :props="{ label: 'name', children: 'children' }"
             :expand-on-click-node="false" :filter-node-method="filterNode" node-key="id" highlight-current
             default-expand-all :show-checkbox="allowMultiple" @node-click="handleNodeClick" @check="handleNodeCheck"/>
</template>

<script setup name="KnowledgeTree">
import {useInjectPaperKnowledgeCondition} from "@/views/dz/papers/hooks/usePaperKnowledgeCondition.js";

const props = defineProps({
    allowMultiple: Boolean
})

const treeRef = ref(null)
const keyword = ref('')
const {knowledges, knowledgeNode, knowledgeCheckNodes, onKnowledgeRemove} = useInjectPaperKnowledgeCondition()
const filterNode = function (value, data) {
    if (!value) return true
    return data.name.indexOf(value) !== -1
}

const handleNodeClick = function (data) {
    knowledgeNode.value = data
}

const handleNodeCheck = function (data, {checkedNodes}) {
    // 多选时，只保留叶子节点
    knowledgeCheckNodes.value = checkedNodes.filter(k => !!!k.children?.length)
}

watch(keyword, val => {
    treeRef.value.filter(val)
})
onKnowledgeRemove((k) => {
    treeRef.value.setChecked(k, false, false)
})
</script>

<style scoped>

</style>