<template>
  <Popup
    v-bind="popupProps"
    :show="isShow"
    @change="onShowChangeHandler"
  >
    <template v-slot:trigger>
      <!-- @slot 触发下拉列表显示的元素。 注意： 必须是一个元素或者或者组件 -->
      <slot />
    </template>

    <!-- @slot 下拉列表，通常是 <hive-dropdown-menu> 组件 -->
    <slot name="dropdown" />
  </Popup>
</template>

<script>
import Popup from '../popup';

const name = 'hive-dropdown';
export default {
  name,
  components: {
    Popup
  },
  inheritAttrs: false,
  provide() {
    return {
      hiveDropdown: this
    };
  },
  props: {
    /**
     * 是否显示下拉框
     */
    show: Boolean,
    /**
     * 选项点击后是否隐藏 dropdown
     */
    hideAfterItemClick: { type: Boolean, default: true }
  },
  data() {
    return {
      isShow: this.show
    };
  },
  computed: {
    popupProps() {
      const { direction, width } = this.$attrs;
      let triggerType;
      let popupClass;
      if (this.$attrs.triggerType) triggerType = this.$attrs.triggerType;
      if (this.$attrs['trigger-type']) triggerType = this.$attrs['trigger-type'];
      if (this.$attrs.popupClass) popupClass = this.$attrs.popupClass;
      if (this.$attrs['popup-class']) popupClass = this.$attrs['popup-class'];

      const props = {
        triggerType: triggerType || 'click',
        width: width || this.popupWidthHanlder,
        popupClass: `${popupClass || ''} hive-dropdown`,
        direction: direction || 'bottom center'
      };
      return props;
    },
    triggerType() {
      return this.$attrs.triggerType || this.$attrs['trigger-type'];
    }
  },
  watch: {
    show(val) {
      if (this.triggerType === 'manual') {
        this.isShow = val;
      }
    }
  },
  created() {
    this.$on('dropdown-item:click', this.onDropDownItemClick);
  },
  methods: {
    popupWidthHanlder(trigger) {
      return trigger.offsetWidth;
    },
    onShowChangeHandler(visible) {
      if (this.triggerType !== 'manual') {
        this.isShow = visible;
      }
      this.$emit('change', visible);
    },
    onDropDownItemClick(index) {
      if (this.hideAfterItemClick && this.triggerType !== 'manual') this.isShow = false;
      /**
       * item点击回调
       * @param {Number} index 被点击item的index
       */
      this.$emit('item-click', index);
    }
  }
};
</script>
