<template>
    <a-tree
        :checkedKeys="value"
        :selectable="false"
        checkable
        :replaceFields="replaceFields"
        :tree-data="treeData"
        class="tw-overflow-y-auto"
        :expandedKeys.sync="expandedKeys"
        v-bind="$attrs"
        v-on="$listeners"
    />
</template>

<script>
import { getMenuDataApi } from '@/api';
import { convertListToTree } from '@/utils';

export default {
    model: {
        prop: 'value',
        event: 'check',
    },
    props: {
        value: [Object, Array],
        showMenu: Boolean,
        defaultCheckedKeys: Array,
    },
    data() {
        return {
            treeData: [],
            replaceFields: {
                title: 'menuName',
                key: 'menuId',
            },
            expandedKeys: [],
        };
    },
    async mounted() {
        // 使用 缓存
        this.rawData = await getMenuDataApi(true);
        this.treeData = convertListToTree(this.rawData, !this.showMenu);
        this.$emit('check', this.defaultCheckedKeys);
        this.expandedKeys = this.defaultCheckedKeys;
    },

    watch: {
        defaultCheckedKeys(val) {
            this.$emit('check', val);
            this.expandedKeys = val;
        },
    },

    methods: {
        get() {
            if (Array.isArray(this.value)) return this.rawData.filter(m => this.value.includes(m.menuId));
            return [];
        },
    },
};
</script>
