<template>
  <div :class="[wrapperClass, {'is-collapsed': collapsed}]">
    <slot></slot>
  </div>
</template>
<script>
import { LIB_NAME, findComponentsDownward } from '../../../../src/util'

const wrapperClass = `${LIB_NAME}-menu`

export default {
  name: 'xMenu',

  provide() {
    return {
      'xMenu': this
    }
  },

  props: {

    // 当前激活的菜单，和菜单的value对应
    value: {
      type: [String, Number],
      default: ''
    },

    // 是否使用 vue-router 的模式，启用该模式会在激活导航时以 value 作为 path 进行路由跳转
    router: {
      type: Boolean,
      default: false
    },

    // 菜单收起
    collapsed: {
      type: Boolean,
      default: false
    }
  },

  data() {
    return {

      wrapperClass,

      // 当前选中的菜单栏
      defaultActive: '',

      items: []
    }
  },

  created() {
    if (this.router && this.$route) {
      this.defaultActive = this.$route.path
      this.$watch('$route.path', (v) => {
        this.setValue(v)
      })
    } else {
      this.defaultActive = this.value
      this.$watch('value', (v) => {
        this.setValue(v)
      })
    }
  },

  mounted() {
    this.setGroupActive()
  },

  methods: {

    // 设置默认选中菜单
    setValue(v) {
      if (v !== this.defaultActive) {
        this.defaultActive = v
        this.setGroupActive()
      }
    },

    change(v) {
      this.setValue(v)
      this.$emit('on-change', this.defaultActive)
      this.$emit('input', this.defaultActive)
    },

    // 设置当前选中的分组
    setGroupActive() {
      const filter = this.$children.filter(o => o.$vnode.tag.indexOf('xMenuItemGroup') > -1)
      filter.forEach(o => {
        if (o.rules) {
          o.isActive = !!o.rules.test(this.defaultActive)
        } else {
          const find = findComponentsDownward(o, 'xMenuItem').find(o => o.active)
          o.isActive = !!find
        }
      })
    }
  }
}
</script>
