<template>
  <div
    v-tooltip.right.fixed.viewport="xMenu.collapsed ? label : ''"
    :class="[wrapperClass, {'is-active': active}]"
    @click="selectItem()"
    @mousedown="$emit('mousedown', value)"
  >
    <slot name="icon">
      <i v-if="icon" :class="[wrapperClass + '-icon', icon]"></i>
    </slot>
    <span :class="[wrapperClass + '-label']">
      <slot>{{ label }}</slot>
    </span>
    <span :class="[wrapperClass + '-right-icon']">
      <slot name="right-icon">
        <i v-if="rightIcon" :class="[rightIcon]"></i>
      </slot>
    </span>
    <slot name="link">
      <router-link v-if="xMenu.router && value" class="router-link-a" :title="label" :to="value" :replace="replace"></router-link>
    </slot>
  </div>
</template>
<script>
import { LIB_NAME } from '../../../../src/util'

const wrapperClass = `${LIB_NAME}-menu-item`

export default {
  name: 'xMenuItem',
  inject: ['xMenu'],
  props: {
    icon: {
      type: String,
      default: ''
    },

    rightIcon: {
      type: String,
      default: ''
    },

    // 菜单文本
    label: { // eslint-disable-line
      type: String
    },

    // 菜单绑定的唯一值
    // router模式下为当前菜单对应的路由
    value: { // eslint-disable-line
      type: [Number, String]
    },

    // router模式下通过replace跳转路由
    replace: {
      type: Boolean,
      default: false
    },

    // 匹配规则
    rules: { // eslint-disable-line
      type: [Array, RegExp, Function]
    }
  },

  data() {
    return {
      wrapperClass
    }
  },

  computed: {

    // 判断当前是否选中
    active() {
      const v = this.value
      const { defaultActive } = this.xMenu
      const rules = this.rules

      if (v !== null || v !== undefined || v !== '') {
        if (v === defaultActive) {
          return true
        }

        if (rules) {
          if (rules instanceof Function) {
            return rules(v, this.$route)
          }
          if (rules instanceof Array) {
            return rules.findIndex(o => defaultActive.indexOf(o) > -1) > -1
          }
          if (rules instanceof RegExp) {
            return !!rules.test(defaultActive)
          }
        }
      }
      return false
    }
  },

  created() {

  },

  methods: {

    // 选中当前item
    selectItem() {
      const xMenu = this.xMenu
      if (this.value === null || this.value === undefined || this.value === '') {
        this.$emit('click', this.value)
      } else {
        xMenu.change(this.value)
        this.$emit('click', this.value)
      }
    }
  }
}
</script>
