<template>
    <ul :class="bem()">
        <slot/>
    </ul>
</template>

<script>
import { createComponentName, componentMixin } from '../_utils/component';
import Event from 'eventemitter3';

export default {
    name: createComponentName('menu'),
    mixins: [componentMixin],
    model: {
        prop: 'indexPath',
        event: 'change',
    },
    props: {
        defaultIndexPath: {
            type: Array,
            default: () => [],
        },
        indexPath: {
            type: Array,

        },
        trigger: {
            type: String,
            default: 'hover',
        },
        router: {
            type: Boolean,
            default: false,
        },
    },
    provide() {
        this.menuBus = new Event();
        return {
            menuBus: this.menuBus,
            rootMenu: this,
        };
    },
    data() {
        return {
            innerIndexPath: this.indexPath || this.defaultIndexPath,
        };
    },
    computed: {
        activeIndexPath: {
            get() {
                return this.indexPath || this.innerIndexPath;
            },
            set(value) {
                this.$emit('change', value);
                this.innerIndexPath = value;
            },
        },
    },
    mounted() {
        this.menuBus.on('menu-item:select', this.onSelect);
    },
    destroyed() {
        this.menuBus.removeListener('menu-item:select', this.onSelect);
    },
    methods: {
        open(index) {
            this.menuBus.emit('sub-menu:toggle', index, true);
        },
        close(index) {
            this.menuBus.emit('sub-menu:toggle', index, false);
        },
        onSelect(index, indexPath) {
            this.activeIndexPath = indexPath;
            this.$emit('select', index, indexPath);
        },
    },
};
</script>

<style lang="less">
@import '../_styles/base.less';

@b: ~'@{prefix}-menu';

.@{b} {
    padding: 0;
    font-size: 14px;
}

</style>
