import { ref, watch, onBeforeUnmount, unref } from 'vue';
import getElementFromVueInstance from '../getElementFromVueInstance';

function useClickOutSide(watchList, callback) {
  let disabled = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
  const _watchList = Array.isArray(watchList) ? watchList : [watchList];
  let listened = false;
  const disabledRef = ref(disabled);
  function onGlobalMouseDown(event) {
    const target = event.target;
    if (_watchList.every(watchElement => {
      const element = getElementFromVueInstance(unref(watchElement));
      return element && !element.contains(target) && element !== target;
    })) {
      callback === null || callback === void 0 || callback();
    }
  }
  const destroy = () => {
    if (listened) {
      listened = false;
      // 事件捕获
      window.removeEventListener('click', onGlobalMouseDown, true);
    }
  };
  watch(disabledRef, () => {
    if (disabledRef.value) {
      destroy();
    } else if (!listened) {
      listened = true;
      window.addEventListener('click', onGlobalMouseDown, true);
    }
  }, {
    immediate: true
  });
  onBeforeUnmount(destroy);
  return destroy;
}

export { useClickOutSide as default };
