import { resolveDirective as _resolveDirective, createVNode as _createVNode } from "vue";
import { normalizeClass } from "@vue/shared";
import { defineComponent, getCurrentInstance, nextTick, cloneVNode } from "vue";
import { getComponent, isValidElement } from '../_util/props-util';
import useMemo from "../_util/hooks/useMemo";
import Trigger from "../trigger";
import placements from "./placements";
import tooltipProps from "../tooltip/tooltipProps";
const prefixCls = 'x-dropdown';
const Dropdown = defineComponent({
  name: prefixCls,
  props: { ...tooltipProps,
    placement: {
      type: String,
      default: 'bottomLeft'
    },
    popup: [String, Number, Object, Array]
  },
  emits: ['update:visible', 'visibleChange'],
  slots: ['popup'],

  setup(props, {
    emit,
    slots
  }) {
    const {
      proxy: vm
    } = getCurrentInstance();
    const visibleRef = useMemo(() => props.visible);

    function onContextmenu(e) {
      if (!props.trigger.includes('contextmenu')) return;
      visibleRef.value = false;
      nextTick(() => visibleRef.value = true);
    }

    function onPopupVisibleChange(visible) {
      visibleRef.value = visible;
      emit('update:visible', visible);
      emit('visibleChange', visible);
    }

    function onClick() {
      onPopupVisibleChange(false);
    }

    function preventContextmenu(e) {
      if (!props.trigger.includes('contextmenu')) return;
      e.preventDefault();
    }

    return () => {
      const {
        trigger,
        placement,
        builtinPlacements,
        disabled
      } = props;
      const popupClass = normalizeClass([`${prefixCls} ${prefixCls}-placement-${props.placement}`, props.popupClass]);

      function getPopup() {
        const popupProps = {
          selectable: false,
          onClick,
          onContextmenu: preventContextmenu
        };
        let popup = getComponent(vm, 'popup');
        popup = Array.isArray(popup) ? popup[0] : popup;
        popup = isValidElement(popup) ? popup : _createVNode("div", null, [popup]);
        popup = cloneVNode(popup, popupProps);
        return popup;
      }

      const triggerProps = {
        prefixCls,
        action: disabled ? '' : trigger,
        popup: getPopup(),
        popupVisible: visibleRef.value,
        popupClass: popupClass,
        popupTransitionName: `${prefixCls}-placement-${props.placement}`,
        popupAlign: props.align,
        popupPlacement: placement,
        builtinPlacements: builtinPlacements || placements,
        getPopupContainer: props.getPopupContainer,
        onPopupVisibleChange,
        mouseEnterDelay: props.mouseEnterDelay,
        mouseLeaveDelay: props.mouseLeaveDelay,
        popupStyle: props.popupStyle,
        alignPoint: trigger.includes('contextmenu'),
        onContextmenu
      };
      return _createVNode(Trigger, triggerProps, slots);
    };
  }

});

Dropdown.install = app => {
  app.component(Dropdown.name, Dropdown);
};

export default Dropdown;