import * as commonUtils             from '@/utils/common';

export default function(pageId) {
    return {
        methods: {
            syncExpandedKeys(payload) {
                let {data, isExpand} = payload;
                if (isExpand) {
                    if (this.tree.expandedKeys.indexOf(data.id) === -1) {
                        this.tree.expandedKeys.push(data.id);
                    }
                } else {
                    this.tree.expandedKeys.splice(this.tree.expandedKeys.indexOf(data.id), 1);
                }
            },
            getParentChildrenCount(parentId) {
                function getChildrenCount(item, parentId) {
                    if (item.id === parentId) {
                        return item.children.length;
                    } else {
                        if (item.children.length !== 0) {
                            for (const child of item.children) {
                                return getChildrenCount(child, parentId);
                            }
                        }
                    }
                    return undefined;
                }

                for (const item of this.tree.treeData) {
                    if (item.id === parentId) {
                        return item.children.length;
                    } else {
                        if (item.children.length !== 0) {
                            for (const child of item.children) {
                                let count = getChildrenCount(child, parentId);
                                if(count) {
                                    return count;
                                }
                            }
                        }
                    }
                }
            }
        },
        watch: {
            'tree.expandedKeys': {
                handler(newV, oldV) {
                    commonUtils.saveCache(pageId, 'expandedKeys', newV);
                },
            }
        }
    };
};
