import _extends from "@babel/runtime/helpers/extends";
import _toConsumableArray from "@babel/runtime/helpers/toConsumableArray";
import _defineProperty from "@babel/runtime/helpers/defineProperty";
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";

var _window, _window2, _window3, _window4, _window5, _window6;

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

import { useDrag } from '@use-gesture/react';
import { createBEM } from '@zarm-design/bem';
import React, { useEffect, useState } from 'react';
import Button from '../button';
import Carousel from '../carousel';
import { ConfigContext } from '../config-provider';
import Loading from '../loading';
import PinchZoom from '../pinch-zoom';
import Popup from '../popup';
import { canUseDOM } from '../utils/dom';
import formatImages from './utils/formatImages';
import LOAD_STATUS from './utils/loadStatus';
import showOriginButton from './utils/showOriginButton';
var imageStyle = {
  maxWidth: canUseDOM && ((_window = window) === null || _window === void 0 ? void 0 : _window.innerWidth) <= ((_window2 = window) === null || _window2 === void 0 ? void 0 : _window2.innerHeight) ? (_window3 = window) === null || _window3 === void 0 ? void 0 : _window3.innerWidth : undefined,
  maxHeight: canUseDOM && ((_window4 = window) === null || _window4 === void 0 ? void 0 : _window4.innerHeight) <= ((_window5 = window) === null || _window5 === void 0 ? void 0 : _window5.innerWidth) ? (_window6 = window) === null || _window6 === void 0 ? void 0 : _window6.innerHeight : undefined
};

var Content = function Content(props) {
  var minScale = props.minScale,
      maxScale = props.maxScale,
      imgSrc = props.imgSrc;

  var _useState = useState(false),
      _useState2 = _slicedToArray(_useState, 2),
      loaded = _useState2[0],
      setLoaded = _useState2[1];

  var style = loaded ? _objectSpread(_objectSpread({}, imageStyle), {}, {
    display: 'block'
  }) : imageStyle;

  var _React$useContext = React.useContext(ConfigContext),
      prefixCls = _React$useContext.prefixCls;

  var bem = createBEM('image-preview', {
    prefixCls: prefixCls
  });
  return /*#__PURE__*/React.createElement(React.Fragment, null, !loaded ? /*#__PURE__*/React.createElement("div", {
    className: bem('loading')
  }, /*#__PURE__*/React.createElement(Loading, {
    type: "spinner",
    size: "lg"
  })) : null, /*#__PURE__*/React.createElement(PinchZoom, {
    minScale: minScale,
    maxScale: maxScale
  }, /*#__PURE__*/React.createElement("img", {
    src: imgSrc,
    alt: "",
    draggable: false,
    style: style,
    onLoad: function onLoad() {
      return setLoaded(true);
    }
  })));
};

var ImagePreview = /*#__PURE__*/React.forwardRef(function (props, ref) {
  var visible = props.visible,
      activeIndex = props.activeIndex,
      onClose = props.onClose,
      showPagination = props.showPagination,
      minScale = props.minScale,
      maxScale = props.maxScale,
      className = props.className,
      style = props.style,
      mountContainer = props.mountContainer;

  var _useState3 = useState(formatImages(props.images)),
      _useState4 = _slicedToArray(_useState3, 2),
      images = _useState4[0],
      setImages = _useState4[1];

  var _useState5 = useState(activeIndex),
      _useState6 = _slicedToArray(_useState5, 2),
      currentIndex = _useState6[0],
      setCurrentIndex = _useState6[1];

  var _React$useContext2 = React.useContext(ConfigContext),
      prefixCls = _React$useContext2.prefixCls,
      locale = _React$useContext2.locale;

  var bem = createBEM('image-preview', {
    prefixCls: prefixCls
  });
  useEffect(function () {
    setImages(formatImages(props.images));
  }, [props.images, visible]);
  useEffect(function () {
    setCurrentIndex(activeIndex);
  }, [activeIndex]);

  var onChange = function onChange(index) {
    var _props$onChange;

    setCurrentIndex(index);
    (_props$onChange = props.onChange) === null || _props$onChange === void 0 ? void 0 : _props$onChange.call(props, index);
  };

  var loadOrigin = function loadOrigin(event) {
    var _images$currentIndex = images[currentIndex],
        originSrc = _images$currentIndex.originSrc,
        loaded = _images$currentIndex.loaded;

    if (loaded !== LOAD_STATUS.before || !originSrc) {
      return;
    }

    var newImages = _toConsumableArray(images);

    newImages[currentIndex].loaded = LOAD_STATUS.start;
    setImages(newImages);
    var img = new Image();

    img.onload = function () {
      var loadImages = _toConsumableArray(images);

      loadImages[currentIndex].loaded = LOAD_STATUS.end;
      loadImages[currentIndex].src = originSrc;
      setImages(loadImages);
      setTimeout(function () {
        var loadAfeterImages = _toConsumableArray(images);

        loadAfeterImages[currentIndex].loaded = LOAD_STATUS.after;
        setImages(loadAfeterImages);
      }, 0);
    };

    img.src = originSrc;
    event.stopPropagation();
    return false;
  };

  var bindEvent = useDrag(function (state) {
    if (state.tap && state.elapsedTime > 0) {
      onClose === null || onClose === void 0 ? void 0 : onClose();
    }
  });
  var loadEvent = useDrag(function (state) {
    if (state.tap && state.elapsedTime > 0) {
      loadOrigin(state.event);
    }
  });

  var renderImages = function renderImages() {
    return images.map(function (item, i) {
      return /*#__PURE__*/React.createElement("div", {
        className: bem('item'),
        key: +i
      }, /*#__PURE__*/React.createElement(Content, {
        imgSrc: item.src,
        minScale: minScale,
        maxScale: maxScale
      }));
    });
  };

  var renderPagination = function renderPagination() {
    if (visible && showPagination && images && images.length > 1) {
      return /*#__PURE__*/React.createElement("div", _extends({
        className: bem('pagination')
      }, bindEvent()), currentIndex + 1, " / ", images === null || images === void 0 ? void 0 : images.length);
    }

    return null;
  };

  var renderOriginButton = function renderOriginButton() {
    if ((images === null || images === void 0 ? void 0 : images.length) === 0) return;

    var _images = images === null || images === void 0 ? void 0 : images[currentIndex || 0],
        loaded = _images.loaded;

    if (loaded && showOriginButton(images, currentIndex) && loaded !== LOAD_STATUS.after && visible) {
      var _locale$ImagePreview;

      return /*#__PURE__*/React.createElement(Button, _extends({
        size: "xs",
        loading: loaded === LOAD_STATUS.start
      }, loadEvent()), (locale === null || locale === void 0 ? void 0 : locale.ImagePreview) && (locale === null || locale === void 0 ? void 0 : (_locale$ImagePreview = locale.ImagePreview) === null || _locale$ImagePreview === void 0 ? void 0 : _locale$ImagePreview[loaded]));
    }

    return null;
  };

  return /*#__PURE__*/React.createElement(Popup, {
    className: bem([className]),
    style: style,
    direction: "center",
    visible: visible,
    mountContainer: mountContainer,
    maskOpacity: 1
  }, /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("div", _extends({
    ref: ref,
    className: bem('content')
  }, bindEvent()), visible && (images !== null && images !== void 0 && images.length ? /*#__PURE__*/React.createElement(Carousel, {
    showPagination: false,
    onChange: onChange,
    activeIndex: currentIndex,
    swipeable: true
  }, renderImages()) : /*#__PURE__*/React.createElement(Loading, {
    type: "spinner",
    size: "lg"
  }))), /*#__PURE__*/React.createElement("div", {
    className: bem('footer')
  }, renderOriginButton(), renderPagination())));
});
ImagePreview.displayName = 'ImagePreview';
ImagePreview.defaultProps = {
  activeIndex: 0,
  showPagination: true,
  visible: false,
  minScale: 1,
  maxScale: 3
};
export default ImagePreview;