<template>
  <div>
    <Search @Func="SearchFunc" />
    <el-tree
      :data="data"
      :props="defaultProps"
      :filter-node-method="filterNode"
      ref="tree"
      @node-click="handleNodeClick"
    ></el-tree>
  </div>
</template>
<script>
const Search = () => import("@/components/Search/index");
import Home from '@/api/home'
export default {
  components: {
    Search
  },
  props: {
    Data: {
      type: Object,
      default: () => ({})
    }
  },
  data () {
    return {
      data: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      }
    }
  },
  created () {
    this.TreeData();
  },
  methods: {
    // 过滤 目录
    SearchFunc (data) {
      this.$refs.tree.filter(data);
    },
    filterNode (value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 请求树形数据
    TreeData () {
      try {
        Home.knowledgebase_tree().then(res => {
          let { data } = res;
          data = data.map(item => {
            let obj = { id: item.id, label: item.name }
            obj["children"] = item.chapters.map(it => {
              let objc = { id: it.id, label: it.name, subject_id: it.subject_id };
              return objc;
            })
            return obj;
          })
          this.data = data;
        }
        )
      } catch (err) {
        console.error(`数据处理错误：${err}`)
      }
    },
    handleNodeClick (data) {
      if (!data.children) {
        this.$emit("Func", { chapter: data.id, limit: 1, page: 1 })
      }
    }
  }
}
</script>