<template>
    <a  v-if="to"
        :href="to"
        :target="target"
        :class="classes"
        :style="itemStyle"
        @click.exact="handleClickItem($event, false)"
        @click.ctrl="handleClickItem($event, true)"
        @click.meta="handleClickItem($event, true)"><slot></slot></a>
    <li v-else 
        :class="classes" 
        :style="itemStyle"
        @click.stop="handleClickItem"><slot></slot></li>
</template>
<script>
    import { oneOf } from '../../../utils/assist'
    import Mixin from './mixins/'

    const prefixCls = 'yy-menu'
    export default {
        name: 'YYMenuItem',
        mixins: [Mixin],
        props: {
            name: {
                type: [String, Number],
                required: true
            },
            to: {
                type: [String, Number]
            },
            replace: {
                type: Boolean,
                default: false
            },
            target: {
                type: String,
                validator(value) {
                    return oneOf(value, ['_blank', '_self', '_parent', '_top'])
                },
                default: '_self'
            },
            disabled: {
                type: Boolean,
                default: false
            }
        },
        data() {
            return {
                prefixCls: prefixCls
            }
        },
        computed: {
            classes() {
                return [
                    `${prefixCls}-item`,
                    {
                        [`${prefixCls}-item-active`]: this.menu.currentActiveName === this.name
                    }
                ]
            },
            itemStyle () {
                return this.hasParentSubmenu ? {
                    paddingLeft: 40 + (this.parentSubmenuNum - 1) * 16 + 'px'
                } : {}
            }
        },
        methods: {
            handleClickItem (event, newWin = false) {
                if (this.disabled) return
                // 点击先激活面板
                this.menu.handleSelect(this.name)
                this.handleCheckClick(event, newWin)
            },
            handleCheckClick (event, newWin = false) {
                if(!this.to) return
                if(this.target === '_blank') return
                event.preventDefault()
                this.handleClick(newWin)
            },
            handleClick (newWin = false) {
                if (newWin){
                    return window.open(this.to)
                } 
                const isRoute = this.$router
                if (isRoute) {
                    return this.replace ? this.$router.replace(this.to) : this.$router.push(this.to);
                }
                return window.location.href = this.to
            }
        }
    }
</script>
