<template>
    <div class="tree-pack">
        <el-input
            placeholder="请输入搜索关键字"
            prefix-icon="el-icon-search"
            v-model="filterText"
            class="mb-10">
        </el-input>
        <el-tree
            :current-node-key="treeConfig.choseFirstNodeToggle ? choseFirstNode() : ''"
            class="filter-tree"
            default-expand-all
            highlight-current
            :filter-node-method="filterNode"
            ref="tree"
            empty-text="暂无分类数据"
            :data="treeConfig.data"
            node-key="id"
            :props="{ children: 'children', label: 'name' }"
            @node-click="doTreeNodeClick"
            :expand-on-click-node="false">
        </el-tree>
    </div>
</template>

<script>
import { setTimeout } from 'timers';
export default {
    props: {
        // 树组件数据
        treeConfig: {
            type: Object,
            required: true
        }
    },
    data () {
        return {
            // 树组件过滤字段
            filterText: ''
        }
    },
    methods: {
        // 树节点点击事件
        doTreeNodeClick (treeNodeValue) {
            this.$emit('doTreeNodeClick', treeNodeValue)
        },
        // 树节点过滤函数
        filterNode (value, data) {
            if (!value) return true;
            return data.name.indexOf(value) !== -1
        },
        // 选中当前第一个树级节点
        choseFirstNode () {
            if (this.treeConfig.data.length > 0) {
                setTimeout(() => {
                    this.$emit('doTreeNodeClick', this.treeConfig.data[0])
                    this.$refs.tree.setCurrentKey(this.treeConfig.data[0].id)
                }, 0)
            }
        }
    },
    watch: {
        filterText (val) {
            this.$refs.tree.filter(val)
        },
        treeConfig (newVal, oldVal) {
            this.oldVal = newVal
        }
    }
}
</script>

<style lang="scss" scoped>

</style>
