import _defineProperty from '@babel/runtime/helpers/esm/defineProperty';
import { defineComponent, ref, inject, computed, onBeforeUnmount, watch, resolveComponent, openBlock, createBlock, Teleport, withDirectives, createElementVNode, normalizeClass, normalizeStyle, withModifiers, createCommentVNode, createVNode, createElementBlock, toDisplayString, vShow } from 'vue';
import { useEventListener } from '@vueuse/core';
import getPrefixCls from '../_util/getPrefixCls';
import { noop, requestAnimationFrame } from '../_util/utils';
import PopupManager from '../_util/popupManager';
import { LeftOutlined, RightOutlined, CloseOutlined, ReloadOutlined, RotateLeftOutlined, SearchPlusOutlined, SearchMinusOutlined, DownloadOutlined } from '../icon';
import { CLOSE_EVENT } from '../_util/constants';
import { useConfig } from '../config-provider';
import { PREVIEW_PROVIDE_KEY } from './props';
import usePreviewImageDrag from './useDrag';

function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
const prefixCls = getPrefixCls('preview');
const previewProps = {
  show: {
    type: Boolean,
    default: true
  },
  hideOnClickModal: {
    type: Boolean,
    default: false
  },
  src: {
    type: String,
    default: ''
  },
  download: {
    type: Boolean,
    default: false
  },
  getContainer: {
    type: Function
  },
  size: Object,
  name: String
};
var script = defineComponent({
  name: 'FPreview',
  components: {
    LeftOutlined,
    RightOutlined,
    CloseOutlined,
    ReloadOutlined,
    RotateLeftOutlined,
    SearchPlusOutlined,
    SearchMinusOutlined,
    DownloadOutlined
  },
  props: previewProps,
  emits: [CLOSE_EVENT],
  setup(props, _ref) {
    let {
      emit
    } = _ref;
    const containerRef = ref();
    const clientHeight = document.documentElement.clientHeight;
    const clientWidth = document.documentElement.clientWidth;
    const zIndex = ref(PopupManager.nextZIndex());
    const transform = ref({
      scale: 1,
      rotateDeg: 0,
      offsetX: 0,
      offsetY: 0,
      enableTransition: false
    });
    const {
      isGroup,
      next,
      prev
    } = inject(PREVIEW_PROVIDE_KEY, {
      isGroup: ref(false),
      next: noop,
      prev: noop
    });
    const config = useConfig();
    const getContainer = computed(() => {
      var _config$getContainer;
      return props.getContainer || ((_config$getContainer = config.getContainer) === null || _config$getContainer === void 0 ? void 0 : _config$getContainer.value);
    });
    const previewStyle = computed(() => {
      const {
        scale,
        rotateDeg,
        offsetX,
        offsetY,
        enableTransition
      } = transform.value;
      const style = {
        transform: [`translate(${offsetX}px, ${offsetY}px)`, `scale(${scale})`, `rotate(${rotateDeg}deg)`].join(' '),
        transition: enableTransition ? 'transform .3s' : ''
      };
      if (props.size.height > clientHeight || props.size.width > clientWidth) {
        if (props.size.height / props.size.width >= clientHeight / clientWidth) {
          style.height = `${clientHeight}px`;
          style.width = 'auto';
        } else {
          style.width = `${clientWidth}px`;
          style.height = 'auto';
        }
      }
      return style;
    });
    const handleActions = (action, option) => {
      const {
        zoomRate,
        rotateDeg,
        enableTransition
      } = _objectSpread({
        zoomRate: 1.1,
        rotateDeg: 90,
        enableTransition: true
      }, option);
      switch (action) {
        case 'zoomOut':
          if (transform.value.scale < 0.2) {
            break;
          }
          transform.value.scale = Number.parseFloat((transform.value.scale / zoomRate).toFixed(3));
          break;
        case 'zoomIn':
          transform.value.scale = Number.parseFloat((transform.value.scale * zoomRate).toFixed(3));
          break;
        case 'rotateLeft':
          transform.value.rotateDeg -= rotateDeg;
          break;
        case 'rotateRight':
          transform.value.rotateDeg += rotateDeg;
          break;
      }
      transform.value.enableTransition = enableTransition;
    };
    const reset = () => {
      transform.value = {
        scale: 1,
        rotateDeg: 0,
        offsetX: 0,
        offsetY: 0,
        enableTransition: false
      };
    };
    let rafId;
    useEventListener(containerRef, 'wheel', e => {
      e.preventDefault();
      rafId = requestAnimationFrame(() => {
        const delta = e.deltaY ? e.deltaY : e.detail;
        handleActions(delta < 0 ? 'zoomIn' : 'zoomOut', {
          enableTransition: false
        });
      });
    }, {
      passive: false
    });
    onBeforeUnmount(() => {
      if (rafId) {
        cancelAnimationFrame(rafId);
      }
    });
    const {
      isDragging,
      handleMouseDown
    } = usePreviewImageDrag(transform);
    const handleClose = () => {
      emit(CLOSE_EVENT);
    };
    watch(() => props.src, () => {
      reset();
    });
    return {
      containerRef,
      prefixCls,
      handleClose,
      isGroup,
      prev,
      next,
      handleActions,
      previewStyle,
      zIndex,
      isDragging,
      handleMouseDown,
      getContainer
    };
  }
});

const _hoisted_1 = ["download", "href"];
const _hoisted_2 = ["src"];
function render(_ctx, _cache, $props, $setup, $data, $options) {
  var _ctx$getContainer, _ctx$getContainer2;
  const _component_CloseOutlined = resolveComponent("CloseOutlined");
  const _component_LeftOutlined = resolveComponent("LeftOutlined");
  const _component_RightOutlined = resolveComponent("RightOutlined");
  const _component_SearchMinusOutlined = resolveComponent("SearchMinusOutlined");
  const _component_SearchPlusOutlined = resolveComponent("SearchPlusOutlined");
  const _component_DownloadOutlined = resolveComponent("DownloadOutlined");
  const _component_RotateLeftOutlined = resolveComponent("RotateLeftOutlined");
  const _component_ReloadOutlined = resolveComponent("ReloadOutlined");
  return openBlock(), createBlock(Teleport, {
    disabled: !((_ctx$getContainer = _ctx.getContainer) !== null && _ctx$getContainer !== void 0 && _ctx$getContainer.call(_ctx)),
    to: (_ctx$getContainer2 = _ctx.getContainer) === null || _ctx$getContainer2 === void 0 ? void 0 : _ctx$getContainer2.call(_ctx)
  }, [withDirectives(createElementVNode("div", {
    ref: "containerRef",
    class: normalizeClass(`${_ctx.prefixCls}`),
    style: normalizeStyle({
      zIndex: _ctx.zIndex
    }),
    onClick: _cache[8] || (_cache[8] = withModifiers($event => _ctx.hideOnClickModal && _ctx.handleClose(), ["self"]))
  }, [createCommentVNode(" close "), createElementVNode("div", {
    class: normalizeClass([`${_ctx.prefixCls}__close`, `${_ctx.prefixCls}__btn`]),
    onClick: _cache[0] || (_cache[0] = function () {
      return _ctx.handleClose && _ctx.handleClose(...arguments);
    })
  }, [createVNode(_component_CloseOutlined)], 2 /* CLASS */), createCommentVNode(" arrow "), _ctx.isGroup ? (openBlock(), createElementBlock("div", {
    key: 0,
    class: normalizeClass([`${_ctx.prefixCls}__arrow-left`, `${_ctx.prefixCls}__btn`]),
    onClick: _cache[1] || (_cache[1] = function () {
      return _ctx.prev && _ctx.prev(...arguments);
    })
  }, [createVNode(_component_LeftOutlined)], 2 /* CLASS */)) : createCommentVNode("v-if", true), _ctx.isGroup ? (openBlock(), createElementBlock("div", {
    key: 1,
    class: normalizeClass([`${_ctx.prefixCls}__arrow-right`, `${_ctx.prefixCls}__btn`]),
    onClick: _cache[2] || (_cache[2] = function () {
      return _ctx.next && _ctx.next(...arguments);
    })
  }, [createVNode(_component_RightOutlined)], 2 /* CLASS */)) : createCommentVNode("v-if", true), _ctx.name ? (openBlock(), createElementBlock("div", {
    key: 2,
    class: normalizeClass(`${_ctx.prefixCls}__name`)
  }, toDisplayString(`${_ctx.name}(${_ctx.size.width}x${_ctx.size.height})`), 3 /* TEXT, CLASS */)) : createCommentVNode("v-if", true), createCommentVNode(" toolBar "), createElementVNode("div", {
    class: normalizeClass(`${_ctx.prefixCls}__toolBar`)
  }, [createVNode(_component_SearchMinusOutlined, {
    class: normalizeClass(`${_ctx.prefixCls}-zoom-out`),
    onClick: _cache[3] || (_cache[3] = $event => _ctx.handleActions('zoomOut', {
      zoomRate: 1.2
    }))
  }, null, 8 /* PROPS */, ["class"]), createVNode(_component_SearchPlusOutlined, {
    class: normalizeClass(`${_ctx.prefixCls}-zoom-in`),
    onClick: _cache[4] || (_cache[4] = $event => _ctx.handleActions('zoomIn', {
      zoomRate: 1.2
    }))
  }, null, 8 /* PROPS */, ["class"]), _ctx.download ? (openBlock(), createElementBlock("a", {
    key: 0,
    download: _ctx.name || Date.now(),
    href: _ctx.src,
    target: "_blank",
    class: normalizeClass(`${_ctx.prefixCls}-download`)
  }, [createVNode(_component_DownloadOutlined)], 10 /* CLASS, PROPS */, _hoisted_1)) : createCommentVNode("v-if", true), createVNode(_component_RotateLeftOutlined, {
    class: normalizeClass(`${_ctx.prefixCls}-rotate-left`),
    onClick: _cache[5] || (_cache[5] = $event => _ctx.handleActions('rotateLeft'))
  }, null, 8 /* PROPS */, ["class"]), createVNode(_component_ReloadOutlined, {
    class: normalizeClass(`${_ctx.prefixCls}-rotate-right`),
    onClick: _cache[6] || (_cache[6] = $event => _ctx.handleActions('rotateRight'))
  }, null, 8 /* PROPS */, ["class"])], 2 /* CLASS */), createCommentVNode(" canvas "), createElementVNode("img", {
    class: normalizeClass({
      [`${_ctx.prefixCls}__canvas`]: true,
      'is-dragging': _ctx.isDragging
    }),
    src: _ctx.src,
    style: normalizeStyle(_ctx.previewStyle),
    onMousedown: _cache[7] || (_cache[7] = function () {
      return _ctx.handleMouseDown && _ctx.handleMouseDown(...arguments);
    })
  }, null, 46 /* CLASS, STYLE, PROPS, NEED_HYDRATION */, _hoisted_2)], 6 /* CLASS, STYLE */), [[vShow, _ctx.show]])], 8 /* PROPS */, ["disabled", "to"]);
}

script.render = render;
script.__file = "components/image/preview.vue";

export { script as default };
