<template>
  <div :class="'ipub-dropdown ' + (active?'active':'')"
       @mouseleave="handleMouseleave"
       @mouseover="handleMouseover">
    <span @click="handleClick"
          class="ipub-dropdown__title">
      <slot name="title">{{title}}</slot>
    </span>
    <div v-show="warp"
         class="ipub-dropdown__warp ipub-shadow">
      <div class="ipub-dropdown__warp__item">
        <slot name="menus">
          <ipub-menus :menus="menus"
                      :nameLabel="nameLabel"
                      :hrefLabel="hrefLabel"></ipub-menus>
        </slot>
      </div>
    </div>
  </div>
</template>

<script>
import IpubMenus from '../../menus/src/main'
export default {
  name: 'IpubDropdown',
  components: {
    IpubMenus
  },
  props: {
    title: {
      type: String,
      default: ''
    },
    menus: {
      type: Array,
      default () {
        return []
      }
    },
    nameLabel: {
      type: String,
      default: 'name'
    },
    hrefLabel: {
      type: String,
      default: 'href'
    },
    trigger: {
      type: String,
      default: 'hover',
      validator: function (value) {
        // 这个值必须匹配下列字符串中的一个
        return ['hover', 'click'].indexOf(value) !== -1
      }
    },
    warp: {
      type: Boolean,
      default: true
    }
  },
  data () {
    return {
      active: false
    }
  },
  methods: {
    handleClick () {
      if (this.trigger !== 'click') {
        return
      }
      this.active = !this.active
      if (this.active) {
        setTimeout(() => {
          const fun = () => {
            this.active = false
            document.removeEventListener('click', fun)
          }
          document.addEventListener('click', fun)
        }, 0);
      }
    },
    handleMouseover () {
      if (this.trigger !== 'hover') {
        return
      }
      this.active = true
    },
    handleMouseleave () {
      if (this.trigger !== 'hover') {
        return
      }
      this.active = false
    }
  }
}
</script>

