<template>
    <div class="tree_wrapper scrollbar">
        <el-tree
            :data="treeList"
            :props="defaultProps"
            node-key="id"
            :default-expanded-keys="['']"
            :current-node-key="nodeChecked"
            :expand-on-click-node="false"
            :default-expand-all="true"
            @node-click="handleNodeClick"
        ></el-tree>
    </div>
</template>

<script>
import { mapMutations } from 'vuex'
export default {
    name: 'OrganizeSelector',
    props: {
        // 默认选中的选项
        defaultChecked: {
            type: Object,
            default: () => {
                return {}
            }
        }
    },
    data () {
        return {
            defaultProps: {
                children: 'children',
                label: 'fullname'
            },
            treeList: [],
            nodeChecked: ''
        }
    },
    watch: {
        defaultChecked: {
            deep: true,
            handler (data) {
                if (data && Object.keys(data).length) {
                    this.nodeChecked = data.id
                }
            }
        }
    },
    created () {
        this.fetchOrganzieTree()
    },
    methods: {
        // 获取组织架构树
        fetchOrganzieTree () {
            this.$api.commonApi.getOrganizeTree().then(res => {
                this.$handleResponse(res).then(data => {
                    this.treeList = [data]
                    this.saveOrganize(this.treeList)
                    this.$emit('hasGetGroup', this.treeList) // 已获取组织架构
                })
            })
        },
        // 点击节点
        handleNodeClick (data) {
            this.$emit('nodeClick', data)
        },
        ...mapMutations(['saveOrganize'])
    }
}
</script>

<style lang="less" scoped>
.tree_wrapper {
    height: calc(100% - 35px);
    overflow-y: auto;
}
</style>
