<template>
    <a-tree-select
        :value="value"
        show-search
        style="width: 100%"
        :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
        placeholder="Please select"
        :tree-data="treeData"
        allow-clear
        tree-default-expand-all
        :replaceFields="replaceFields"
        @change="onChange"
    />
</template>

<script>
import api from '@/api/organization';
import { arrayToTree } from '@/utils';

export default {
    model: {
        prop: 'value',
        event: 'change',
    },
    props: {
        value: Number,
        showMenu: Boolean,
        getName: Function,
    },
    data() {
        return {
            treeData: [],
            replaceFields: {
                title: 'orgName',
                key: 'orgId',
                value: 'orgId',
            },
        };
    },
    async mounted() {
        const rawData = await api.getOrganizationList();
        const newData = rawData.map((i) => ({
            ...i,
        }));
        const newArr = new arrayToTree({
            data: newData,
            rootValue: 0,
            parentKey: 'parentOrgId',
            key: 'orgId',
        }).treeData;
        this.treeData = [...newArr];
    },
    methods: {
        onChange(value, label, extra) {
            this.getName && this.getName(label);
            this.$emit('change', value);
        },
    },
};
</script>
