<template>
  <div>
    <el-select ref='stlectTree' v-model="treeSelectText" placeholder="请选择或者输入工程名称" clearable filterable :filter-method="filterMethod" 
    @clear="clearInput" size="mini">
        <el-option :value="treeValue.id" :label="treeValue.label" style="max-width: 260px;height: auto;padding:0;">
            <el-tree :data="datas"
                :props="defaultProps"
                :expand-on-click-node="false"
                node-key="pbsTree"
                highlight-current
                @node-click="nodeClick"
                :filter-node-method="filterNode"
                ref="tree" 
            />
        </el-option>
    </el-select>
  </div>
</template>
<script>
export default {
    name:"commonTree",//显示工程树
    data() {
      return {
        treeSelectText: '',
		treeValue: {},
        datas: [],
        defaultProps: {
            children: 'children',
            label: 'name'
        }
      }
    },
    created(){
        this.getPbsTree()
    },
    methods: {
        async getPbsTree(){
            const res = await this.$PortApi.pbsTreeList_api();
            const { code, result } = res.data;
            if (code === 1) {
                function formatTree (obj) {
                    const copyedObj = JSON.parse(JSON.stringify(obj)); // 深拷贝源数据
                    return copyedObj.filter((parent) => {
                        const findChildren = copyedObj.filter(
                            (child) => (parent.id === child.pid&&child.levelname!="分部工程（专业）")
                        );
                        findChildren.length > 0
                            ? (parent.children = findChildren)
                            : delete (parent.children = []);
                        return parent.pid === null; // 返回顶层，依据实际情况判断这里的返回值
                    });
                }
                if(result[0])
                    this.datas=formatTree(result[0].structures);
            } else {
                this.$message.error("信息获取失败");
            }
        },
        // 点击tree节点
        nodeClick(item) {
            const { id, name,code } = item
            this.treeValue.id = id;
            this.treeValue.label= name;
            this.treeSelectText = name
            this.$refs.stlectTree.blur()
            //项目改变
            let emitInfo=item
            this.$emit('changeProjectName',emitInfo)
        },
        // 搜索逻辑
        filterMethod(value) {
            this.$refs.tree.filter(value)
        },
        // tree节点过滤
        filterNode(value, data) {
            if (!value) return true
            return data.name.indexOf(value) !== -1
        },
        clearInput(){
            this.$refs.tree.filter("")
            //项目改变
            this.$emit('changeProjectName',"")
        }
    }
}
</script>

<style lang="scss">
</style>