<template>
  <Button ref="vucButton"
          :class="btnClass"
          v-bind="$attrs"
          @click="handleBtnClick"
          @mouseenter.native="handleMouseenter"
          @mouseleave.native="handleMouseleave">
    <template>
      <slot></slot>
      <Icon :class="{'ivu-icon-suffix':true,'ivu-icon-expanded':expanded}"
            v-if="menus.length>0"
            type="ios-arrow-down" />
    </template>
  </Button>
</template>

<script>
export default {
  name: 'VucButton',
  props: {
    trigger: {
      type: String,
      default: 'click'
    },
    menus: {
      type: Array,
      default: () => []
    }
  },
  data () {
    return {
      tipInstance: null,
      expanded: false,
      enter: false
    }
  },
  computed: {

    btnClass () {
      return [
        'vuc-button',
        this.menus.length > 0 ? 'button-menu' : ''
      ]
    }
  },
  methods: {
    clearTime () {
      // if (window.btnMenuTimeId && window.btnMenuTimeId !== null) {
      clearTimeout(window.btnMenuTimeId)
      window.btnMenuTimeId = null
      // }
    },
    handleMouseenter () {
      if (this.trigger === 'hover') {
        this.enter = true
        this.handleBtnClick()
      }
    },
    handleMouseleave () {
      let _this = this
      _this.enter = false
      if (this.tipInstance) {
        window.btnMenuTimeId = setTimeout(() => {
          _this.tipInstance.hiddenTip()
          _this.clearTime()
        }, 1000)
      }
    },
    handleBtnClick () {
      let _this = this
      if (this.menus && this.menus.length === 0) {
        this.$emit('click')
      } else {
        this.clearTime()
        this.tipInstance = this.$vucdlg.tip({
          target: this.$refs.vucButton.$el || this.$refs.vucButton,
          placements: ['bottom', 'top', 'right', 'left'],
          // msg: '信息内容',
          list: this.menus,
          handler: (os, item) => {
            if (os === 'ok') {
              this.$emit('click', item)
            }
          },
          hide () {
            _this.expanded = false
          },
          show () {
            if (_this.enter) {
              _this.expanded = true
            }
          },
          mouseenter () {
            _this.clearTime()
          },
          mouseleave () {
            _this.handleMouseleave()
          }
        })
      }
    }
  }
}
</script>
<style lang="less">
@import './vuc-button.less';
</style>
