<template>
  <div
    :class="classes"
    @mouseenter="handleMouseenter"
    @mouseleave="handleMouseleave"
    v-click-outside="onClickoutside"
  >
    <div @click="handleClick" :class="prefixCls + '-btn'">
      <slot></slot>
    </div>
    <transition name="transition-dropdown">
      <Panel :class="placementCls" :width="width" :height="height" v-show="currentVisible">
        <slot name="list"></slot>
      </Panel>
    </transition>
  </div>
</template>
<script>
const prefixCls = "lion-dropdown";
import { oneOf } from "../../utils/assist.js";
import * as vClickOutside from "v-click-outside-x";
import Panel from "../panel/panel";
export default {
  name: "LionDropdown",
  directives: {
    clickOutside: vClickOutside.directive
  },
  components: { Panel },
  props: {
    trigger: {
      validator(value) {
        return oneOf(value, ["click", "hover"]);
      },
      default: "hover"
    },
    visible: {
      type: Boolean,
      default: false
    },
    time: {
      type: [String, Number],
      default: 150
    },
    width: {
        type: [Number,String],
        default:''
    },
    height: {
        type: [Number,String],
        default:''
    },
    placement: {
      validator(value) {
        return oneOf(value,['left', 'middle','right'])
      },
      default: 'left'
    }
  },
  data() {
    return {
      prefixCls: prefixCls,
      currentVisible: this.visible
    };
  },
  computed: {
    classes() {
      return [
        prefixCls
      ]
    },
    placementCls() {
      return [
        prefixCls+'-'+this.placement
      ]
    }
  },
  methods: {
    onClickoutside(e) {
      if (this.trigger === "hover") return false;
      this.currentVisible = false;
    },
    handleMouseenter() {
      if (this.trigger !== "hover") return false;
      if (this.timeout) clearTimeout(this.timeout);
      this.timeout = setTimeout(() => {
        this.currentVisible = true;
      }, this.time);
    },
    handleMouseleave() {
        if (this.trigger !== "hover") return false;
        if(this.timeout) {
            clearTimeout(this.timeout);
            this.timeout = setTimeout(() => {
                this.currentVisible = false;
            }, this.time)
        }
    },
    handleClick() {
        this.currentVisible = !this.currentVisible;
    }
  }
};
</script>