<template>
  <li :class="classes">
    <div class="uif-sub-menu-title" @click="handleClick">
      <slot name="title">{{title}}</slot>
      <u-icon class="uif-sub-menu-icon" type="chevron-bottom"></u-icon>
    </div>
    <u-slide-down v-model="active"><slot></slot></u-slide-down>
  </li>
</template>

<script>
import UIcon from '@uif/core/lib/components/icon'
import USlideDown from '@uif/core/lib/components/slide-down'
import {findParentComponents, findChildComponents} from '@uif/core/lib/utils/findComponents'
import {forEach} from '@uif/core/lib/utils/array'

export default {
  name: 'u-sub-menu',
  components: { USlideDown, UIcon },
  props: {
    name: {
      type: [String, Number],
      default: ''
    },
    title: {
      type: String
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      accordion: false,
      active: false
    }
  },
  computed: {
    classes () {
      return [
        'uif-sub-menu',
        {
          'uif-sub-menu-active': this.active,
          'uif-sub-menu-disabled': this.disabled
        }
      ]
    }
  },
  methods: {
    handleClick () {
      if (!this.disabled) {
        this.active = !this.active
        // 检查手风琴模式
        this.handleAccordion()
      } else {
        // 关闭所有子嵌套组件
        this.closeSubMenus()
      }
    },
    handleAccordion () {
      if (this.accordion) {
        forEach(findParentComponents(this, ['u-menu', 'u-sub-menu']), ref => {
          forEach(findChildComponents(ref, 'u-sub-menu'), ref => {
            ref.active = ref === this
          })
        })
      }
    },
    closeSubMenus () {
      forEach(findChildComponents(this, 'u-sub-menu'), ref => {
        ref.active = false
      })
    }
  }
}
</script>
