<template>
    <Popover
        :tag="MenuItem"
        :animation="collapseTransition"
        :trigger="rootMenu.trigger"
        :index="index"
        :route="route"
        :arrow="false"
        ref="popover"
        :lazy="false"
        :popover-class="[bem('popover'), popoverClass]"
        :placement="placement"
        v-bind="$attrs"
        v-on="$listeners"
        :modifiers="{ offset: { offset  }}"
    >
        <slot name="title">{{title}}</slot>
        <ul :class="bem()" slot="content" v-if="!hideMenu">
            <slot/>
        </ul>
    </Popover>
</template>

<script>
import { createComponentName, componentMixin } from '../_utils/component';
import createCollapseTransition from '../_utils/collapse-transition';
import MenuItem from './Item';
import Popover from '../Popover';

export default {
    name: createComponentName('sub-menu'),
    components: { Popover },
    mixins: [componentMixin],
    inject: ['menuBus', 'rootMenu'],
    props: {
        title: {
            type: String,
        },
        index: {
            type: [String, Number],
            required: true,
        },
        route: {
            type: String,
        },
        hideMenu: {
            type: Boolean,
            default: false,
        },
        offset: {
            type: String,
            default: '0',
        },
        placement: {
            type: String,
            default: 'bottom',
        },
        popoverClass: {
            type: String,
        }
    },
    data() {
        return {
            MenuItem,
        };
    },
    beforeCreate() {
        this.collapseTransition = createCollapseTransition();
    },
    mounted() {
        this.menuBus.on('sub-menu:toggle', this.onToggle);
    },
    destroyed() {
        this.menuBus.removeListener('sub-menu:toggle', this.onToggle);
    },
    methods: {
        onToggle(index, toggle) {
            if (this.index === index && this.$refs.popover) {
                this.$refs.popover.isShowPopper = toggle;
            }
        },
        close() {
            this.$refs.popover.isShowPopper = false;
        },
    },
};
</script>

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

.@{sub-menu} {
    font-size: 15px;
    margin: 0 1.333em;
    display: inline-block;
    color: #333;
    will-change: height;
    padding: 0;
    margin: 0;

    li {
        display: block;
        padding: 0 36px;
        line-height: 3;
        margin: 0;
        font-size: 14px;
    }
}

.@{sub-menu}__popover {
    background: #fff;
    box-shadow: 0 3px 8px hsla(0,0%,71%,.35);
    padding: 13.5px 0;
}
</style>
