import { defineComponent, reactive, ref, computed, provide, createVNode, Fragment } from 'vue';
import { useTheme } from '../_theme/useTheme';
import Preview from './preview.js';
import { PREVIEW_PROVIDE_KEY } from './props';

let prevOverflow = '';
const previewGroupProps = {
  hideOnClickModal: {
    type: Boolean,
    default: false
  }
};
var previewGroup = defineComponent({
  name: 'FPreviewGroup',
  props: previewGroupProps,
  setup(props, _ref) {
    let {
      slots
    } = _ref;
    useTheme();
    const previewUrls = reactive({});
    const curIndex = ref();
    const isGroup = ref(true);
    const isShowPreview = ref(false);
    const setCurrent = val => {
      curIndex.value = val;
    };
    const previewUrlsKeys = computed(() => Object.keys(previewUrls));
    const currentPreviewIndex = computed(() => previewUrlsKeys.value.indexOf(String(curIndex.value)));
    const registerImage = param => {
      previewUrls[param.id] = param;
      return () => {
        delete previewUrls[param.id];
      };
    };
    const setShowPreview = () => {
      prevOverflow = document.body.style.overflow;
      document.body.style.overflow = 'hidden';
      isShowPreview.value = true;
    };
    const closeViewer = () => {
      document.body.style.overflow = prevOverflow;
      isShowPreview.value = false;
    };
    const next = () => {
      if (currentPreviewIndex.value < previewUrlsKeys.value.length - 1) {
        setCurrent(previewUrlsKeys.value[currentPreviewIndex.value + 1]);
      } else {
        setCurrent(previewUrlsKeys.value[previewUrlsKeys.value.length - currentPreviewIndex.value - 1]);
      }
    };
    const prev = () => {
      if (currentPreviewIndex.value > 0) {
        setCurrent(previewUrlsKeys.value[String(currentPreviewIndex.value - 1)]);
      } else {
        setCurrent(previewUrlsKeys.value[previewUrlsKeys.value.length - currentPreviewIndex.value - 1]);
      }
    };
    provide(PREVIEW_PROVIDE_KEY, {
      isGroup,
      prev,
      next,
      registerImage,
      curIndex,
      setCurrent,
      setShowPreview
    });
    return () => {
      var _slots$default;
      return createVNode(Fragment, null, [(_slots$default = slots.default) === null || _slots$default === void 0 ? void 0 : _slots$default.call(slots), isShowPreview.value && createVNode(Preview, {
        "src": previewUrls[curIndex.value].url,
        "name": previewUrls[curIndex.value].name,
        "size": previewUrls[curIndex.value].size,
        "download": previewUrls[curIndex.value].download,
        "hideOnClickModal": props.hideOnClickModal,
        "onClose": closeViewer
      }, null)]);
    };
  }
});

export { previewGroup as default, previewGroupProps };
