<template>
    <div :class="prefixCls">
        <div :class="`${prefixCls}-logo`" v-if="showLogoSlot">
            <slot name="logo"></slot>
        </div>
        <ul :class="`${prefixCls}-container`" style="display: flex">
            <Scroller ref="scroller">
                <slot></slot>
            </Scroller>
        </ul>
    </div>
</template>
<script>
    import Scroller from '../../base/scroller/'
    import { findComponentsUpward, findComponentsDownward } from '../../../utils/assist'

    const prefixCls = 'yy-menu'
    export default {
        name: 'YYMenu',
        components: {
            Scroller
        },
        props: {
            activeName: { // 当前激活MenuItem
                type: [String, Number]
            },
            openNames: { // 当前展开Submenu
                type: Array,
                default () {
                    return []
                }
            },
            accordion: { // 是否开启手风琴模式
                type: Boolean,
                default: false
            }
        },
        data() {
            return {
                prefixCls: prefixCls,
                currentActiveName: '',
                openedNames: [],
                showLogoSlot: false
            }
        },
        watch: {
            openNames: {
                immediate: true,
                handler:  function (names) {
                    this.openedNames = names
                }
            },
            activeName: {
                immediate: true,
                handler:  function (name) {
                    this.updateActiveName(name)
                }
            }
        },
        methods: {
            updateActiveName(name) { // 更新当前激活导航
                this.currentActiveName = name
            },
            updateOpened() { // 更新当前打开submenu
                const items = findComponentsDownward(this, 'YYSubmenu')
                if (items.length) {
                    items.forEach(item => {
                        item.opened = !!(this.openedNames.indexOf(item.name) > -1)
                    })
                }
            },
            handleSelect(name) { // 暴露点击事件
                this.updateActiveName(name)
                this.$emit('on-select', name)
            },
            handleOpenChange(name) { // 暴露展开事件
                this.$refs.scroller.updateScroll()
                const items = findComponentsDownward(this, 'YYSubmenu')
                this.openedNames = items.filter(item => item.opened).map(item => item.name)
                this.$emit('on-open-change', this.openedNames)
            }
        },
        mounted() {
            this.showLogoSlot = !!this.$slots.logo
            this.updateOpened()
        }
    }
</script>