import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import { createVNode as _createVNode } from "vue";
import { computed, defineComponent, onMounted, onUnmounted, reactive, ref, watch } from 'vue';
import classnames from '../../_util/classNames';
import Dialog from '../../vc-dialog';
import { dialogPropTypes } from '../../vc-dialog/IDialogPropTypes';
import { getOffset } from '../../vc-util/Dom/css';
import addEventListener from '../../vc-util/Dom/addEventListener';
import KeyCode from '../../_util/KeyCode';
import { warning } from '../../vc-util/warning';
import useFrameSetState from './hooks/useFrameSetState';
import getFixScaleEleTransPosition from './getFixScaleEleTransPosition';
import PreviewOperations from './PreviewOperations';
import CloseFilled from '@pf-ui/pf-icons-vue/CloseFilled';
import { context } from './PreviewGroup';
var initialPosition = {
  x: 0,
  y: 0
};
var ScaleRange = 0.08;
export var previewProps = _objectSpread(_objectSpread({}, dialogPropTypes()), {}, {
  src: String,
  alt: String,
  rootClassName: String,
  icons: {
    type: Object,
    default: function _default() {
      return {};
    }
  },
  minScale: {
    type: Number,
    default: 0.1
  },
  maxScale: {
    type: Number,
    default: 50
  }
});
var Preview = defineComponent({
  name: 'Preview',
  inheritAttrs: false,
  props: previewProps,
  emits: ['close', 'afterClose'],
  setup: function setup(props, _ref) {
    var emit = _ref.emit,
      attrs = _ref.attrs;
    var scale = ref(1);
    var rotate = ref(0);
    var _useFrameSetState = useFrameSetState(initialPosition),
      _useFrameSetState2 = _slicedToArray(_useFrameSetState, 2),
      position = _useFrameSetState2[0],
      setPosition = _useFrameSetState2[1];
    var onClose = function onClose() {
      return emit('close');
    };
    var imgRef = ref();
    var originPositionRef = reactive({
      originX: 0,
      originY: 0,
      deltaX: 0,
      deltaY: 0
    });
    var isMoving = ref(false);
    var groupContext = context.inject();
    var previewUrls = groupContext.previewUrls,
      current = groupContext.current,
      isPreviewGroup = groupContext.isPreviewGroup,
      setCurrent = groupContext.setCurrent;
    var previewGroupCount = computed(function () {
      return previewUrls.value.size;
    });
    var previewUrlsKeys = computed(function () {
      return Array.from(previewUrls.value.keys());
    });
    var currentPreviewIndex = computed(function () {
      return previewUrlsKeys.value.indexOf(current.value);
    });
    var combinationSrc = computed(function () {
      return isPreviewGroup.value ? previewUrls.value.get(current.value) : props.src;
    });
    var showLeftOrRightSwitches = computed(function () {
      return isPreviewGroup.value && previewGroupCount.value > 1;
    });
    var lastWheelZoomDirection = ref({
      wheelDirection: 0
    });
    var rotateMap = reactive({});
    var rotateSaveDisabled = computed(function () {
      return rotate.value % 360 === (rotateMap[combinationSrc.value] || 0);
    });
    var onAfterClose = function onAfterClose() {
      scale.value = 1;
      rotate.value = 0;
      setPosition(initialPosition);
      emit('afterClose');
    };
    var setScale = function setScale(value) {
      scale.value = value;
      setPosition(initialPosition);
    };
    var onZoomIn = function onZoomIn() {
      if (scale.value < props.maxScale) {
        var _scale = scale.value + ScaleRange;
        scale.value = _scale > props.maxScale ? props.maxScale : _scale;
      }
      setPosition(initialPosition);
    };
    var onZoomOut = function onZoomOut() {
      if (scale.value > props.minScale) {
        var _scale = scale.value - ScaleRange;
        scale.value = _scale > props.minScale ? _scale : props.minScale;
      }
      setPosition(initialPosition);
    };
    var onRotateRight = function onRotateRight() {
      rotate.value += 90;
    };
    var onRotateLeft = function onRotateLeft() {
      rotate.value -= 90;
    };
    var initRotateValue = function initRotateValue() {
      rotate.value = rotateMap[combinationSrc.value] || 0;
    };
    var onRotateSave = function onRotateSave() {
      var rotateValue = rotate.value % 360;
      rotateMap[combinationSrc.value] = rotateValue;
    };
    var handleSwitchLeft = function handleSwitchLeft() {
      var nextIndex = currentPreviewIndex.value > 0 ? currentPreviewIndex.value - 1 : previewUrlsKeys.value.length - 1;
      setCurrent(previewUrlsKeys.value[nextIndex]);
      initRotateValue();
    };
    var handleSwitchRight = function handleSwitchRight() {
      var nextIndex = currentPreviewIndex.value < previewGroupCount.value - 1 ? currentPreviewIndex.value + 1 : 0;
      setCurrent(previewUrlsKeys.value[nextIndex]);
      initRotateValue();
    };
    var wrapClassName = classnames(_defineProperty({}, "".concat(props.prefixCls, "-moving"), isMoving.value));
    var onMouseUp = function onMouseUp() {
      if (props.visible && isMoving.value) {
        var width = imgRef.value.offsetWidth * scale.value;
        var height = imgRef.value.offsetHeight * scale.value;
        var _getOffset = getOffset(imgRef.value),
          left = _getOffset.left,
          top = _getOffset.top;
        var isRotate = rotate.value % 180 !== 0;
        isMoving.value = false;
        var fixState = getFixScaleEleTransPosition(isRotate ? height : width, isRotate ? width : height, left, top);
        if (fixState) {
          setPosition(_objectSpread({}, fixState));
        }
      }
    };
    var onMouseDown = function onMouseDown(event) {
      // Only allow main button
      if (event.button !== 0) return;
      event.preventDefault();
      // Without this mask close will abnormal
      event.stopPropagation();
      originPositionRef.deltaX = event.pageX - position.x;
      originPositionRef.deltaY = event.pageY - position.y;
      originPositionRef.originX = position.x;
      originPositionRef.originY = position.y;
      isMoving.value = true;
    };
    var onMouseMove = function onMouseMove(event) {
      if (props.visible && isMoving.value) {
        setPosition({
          x: event.pageX - originPositionRef.deltaX,
          y: event.pageY - originPositionRef.deltaY
        });
      }
    };
    var onWheelMove = function onWheelMove(event) {
      if (!props.visible) return;
      event.preventDefault();
      var wheelDirection = event.deltaY;
      lastWheelZoomDirection.value = {
        wheelDirection: wheelDirection
      };
    };
    var onKeyDown = function onKeyDown(event) {
      if (!props.visible || !showLeftOrRightSwitches.value) return;
      event.preventDefault();
      if (event.keyCode === KeyCode.LEFT) {
        handleSwitchLeft();
      } else if (event.keyCode === KeyCode.RIGHT) {
        handleSwitchRight();
      }
    };
    var onDoubleClick = function onDoubleClick() {
      if (props.visible) {
        if (scale.value !== 1) {
          scale.value = 1;
        }
        if (position.x !== initialPosition.x || position.y !== initialPosition.y) {
          setPosition(initialPosition);
        }
      }
    };
    var removeListeners = function removeListeners() {};
    onMounted(function () {
      watch([function () {
        return props.visible;
      }, isMoving], function (_ref2) {
        var _ref3 = _slicedToArray(_ref2, 1),
          newVisible = _ref3[0];
        newVisible && initRotateValue();
        removeListeners();
        var onTopMouseUpListener;
        var onTopMouseMoveListener;
        var onMouseUpListener = addEventListener(window, 'mouseup', onMouseUp, false);
        var onMouseMoveListener = addEventListener(window, 'mousemove', onMouseMove, false);
        var onScrollWheelListener = addEventListener(window, 'wheel', onWheelMove, {
          passive: false
        });
        var onKeyDownListener = addEventListener(window, 'keydown', onKeyDown, false);
        try {
          // Resolve if in iframe lost event
          /* istanbul ignore next */
          if (window.top !== window.self) {
            onTopMouseUpListener = addEventListener(window.top, 'mouseup', onMouseUp, false);
            onTopMouseMoveListener = addEventListener(window.top, 'mousemove', onMouseMove, false);
          }
        } catch (error) {
          /* istanbul ignore next */
          warning(false, "[vc-image] ".concat(error));
        }
        removeListeners = function removeListeners() {
          onMouseUpListener.remove();
          onMouseMoveListener.remove();
          onScrollWheelListener.remove();
          onKeyDownListener.remove();
          /* istanbul ignore next */
          if (onTopMouseUpListener) onTopMouseUpListener.remove();
          /* istanbul ignore next */
          if (onTopMouseMoveListener) onTopMouseMoveListener.remove();
        };
      }, {
        flush: 'post',
        immediate: true
      });
      watch([lastWheelZoomDirection], function () {
        var wheelDirection = lastWheelZoomDirection.value.wheelDirection;
        if (wheelDirection > 0) {
          onZoomOut();
        } else if (wheelDirection < 0) {
          onZoomIn();
        }
      });
    });
    onUnmounted(function () {
      removeListeners();
    });
    return function () {
      var visible = props.visible,
        prefixCls = props.prefixCls,
        rootClassName = props.rootClassName;
      return _createVNode(Dialog, _objectSpread(_objectSpread({}, attrs), {}, {
        "transitionName": "zoom",
        "maskTransitionName": "fade",
        "closable": false,
        "maskClosable": false,
        "keyboard": true,
        "prefixCls": prefixCls,
        "onClose": onClose,
        "afterClose": onAfterClose,
        "visible": visible,
        "wrapClassName": wrapClassName,
        "rootClassName": rootClassName,
        "getContainer": props.getContainer
      }), {
        default: function _default() {
          return [_createVNode("div", {
            "class": "".concat(props.prefixCls, "-close"),
            "onClick": onClose
          }, [_createVNode(CloseFilled, {
            "class": "".concat(props.prefixCls, "-close-icon")
          }, null)]), _createVNode("div", {
            "class": "".concat(props.prefixCls, "-img-wrapper"),
            "style": {
              transform: "translate3d(".concat(position.x, "px, ").concat(position.y, "px, 0)")
            }
          }, [_createVNode("img", {
            "onMousedown": onMouseDown,
            "onDblclick": onDoubleClick,
            "ref": imgRef,
            "class": "".concat(props.prefixCls, "-img"),
            "src": combinationSrc.value,
            "alt": props.alt,
            "style": {
              transform: "scale3d(".concat(scale.value, ", ").concat(scale.value, ", 1) rotate(").concat(rotate.value, "deg)")
            }
          }, null)]), _createVNode(PreviewOperations, {
            "prefixCls": props.prefixCls,
            "onScaleSelect": setScale,
            "onZoomIn": onZoomIn,
            "onZoomOut": onZoomOut,
            "onRotateRight": onRotateRight,
            "onRotateLeft": onRotateLeft,
            "onRotateSave": onRotateSave,
            "onSwitchLeft": handleSwitchLeft,
            "onSwitchRight": handleSwitchRight,
            "rotateSaveDisabled": rotateSaveDisabled.value,
            "isGroup": showLeftOrRightSwitches.value,
            "groupCount": previewGroupCount.value,
            "currentIndex": currentPreviewIndex.value
          }, null)];
        }
      });
    };
  }
});
export default Preview;