<template>
    <view class="van-sidebar custom-class">
        <slot />
    </view>
</template>

<script>
import { VantComponent } from '../common/component';
export default {
    data() {
        return {};
    },
    '../sidebar-item/index': {
        name: 'sidebar-item',
        type: 'descendant',
        current: 'sidebar',

        linked() {
            this.setActive(this.activeKey);
        },

        unlinked() {
            this.setActive(this.activeKey);
        }
    },
    props: {
        activeKey: {
            type: Number,
            default: 0
        }
    },
    beforeCreate() {
        this.currentActive = -1;
    },
    methods: {
        setActive(activeKey) {
            const { children, currentActive } = this;
            if (!children.length) {
                return Promise.resolve();
            }
            this.currentActive = activeKey;
            const stack = [];
            if (currentActive !== activeKey && children[currentActive]) {
                stack.push(children[currentActive].setActive(false));
            }
            if (children[activeKey]) {
                stack.push(children[activeKey].setActive(true));
            }
            return Promise.all(stack);
        }
    },
    watch: {
        activeKey: {
            handler: function (activeKey) {
                const { children, currentActive } = this;
                if (!children.length) {
                    return Promise.resolve();
                }
                this.currentActive = activeKey;
                const stack = [];
                if (currentActive !== activeKey && children[currentActive]) {
                    stack.push(children[currentActive].setActive(false));
                }
                if (children[activeKey]) {
                    stack.push(children[activeKey].setActive(true));
                }
                return Promise.all(stack);
            },

            immediate: true
        }
    }
};
</script>
<style>
@import './index.css';
</style>
