<template>
  <div
    :class="_class"
    @mouseenter="onMouseenter"
    @mouseleave="onMouseleave"
    v-clickoutside="hidePop"
  >
    <div
      :class="_slotClass"
      @click="onSlotClick"
    >
      <slot />
    </div>

    <div
      :class="_popClass"
      :style="_popStyle"
    >
      <div
        :class="_contentClass"
        @click="onContentClick"
      >
        <slot name="content">
          {{ content }}
        </slot>
      </div>
      <div :class="_arrowClass" />
    </div>
  </div>
</template>

<script>
import clickoutside from 'utils-lib/dist/clickoutside';

const name = 'hive-poptip';

export default {
  name,
  directives: {
    clickoutside
  },
  props: {
    placement: {
      type: String,
      default: 'top'
    },
    content: String,
    trigger: {
      type: String,
      default: 'hover'
    },
    width: String
  },
  data() {
    return {
      visible: false
    };
  },
  computed: {
    _class() {
      return [
        name,
        {
          [`${name}-${this.placement}`]: this.placement
        }
      ];
    },
    _slotClass() {
      return [
        `${name}-slot`
      ];
    },
    _popClass() {
      return [
        `${name}-pop`,
        {
          visible: this.visible
        }
      ];
    },
    _popStyle() {
      return {
        width: this.width || null
      };
    },
    _contentClass() {
      return [
        `${name}-content`
      ];
    },
    _arrowClass() {
      return [
        `${name}-arrow`
      ];
    }
  },

  methods: {
    onMouseenter() {
      if (this.trigger === 'hover') {
        this.visible = true;
      }
    },
    onMouseleave() {
      if (this.trigger === 'hover') {
        this.visible = false;
      }
    },

    // 插槽点击
    onSlotClick() {
      if (this.trigger === 'click') {
        this.visible = !this.visible;
      }
    },

    hidePop() {
      this.visible = false;
    },

    // 气泡内容显示
    onContentClick({ target }) {
      let node = target;
      while (node) {
        // 如有关闭气泡属性
        if (node.dataset.closePoptip !== undefined) {
          this.hidePop();
          break;
        }
        if (node === this.$el) {
          break;
        }
        node = node.parentNode;
      }
    }
  }
};
</script>
