"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = void 0;

var _react = _interopRequireWildcard(require("react"));

var _reactDom = _interopRequireDefault(require("react-dom"));

var _classnames = _interopRequireDefault(require("classnames"));

var _enlarge = _interopRequireDefault(require("./icon/enlarge"));

var _shrink = _interopRequireDefault(require("./icon/shrink"));

var _leftRotate = _interopRequireDefault(require("./icon/left-rotate"));

var _rightRotate = _interopRequireDefault(require("./icon/right-rotate"));

var _tooltip = _interopRequireDefault(require("../tooltip"));

var _loading = _interopRequireDefault(require("./image/loading.gif"));

var _getLocale = require("../../utils/getLocale");

require("./index.css");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

var prefix = 'titaui-img-viewer';
var ImgViewer = /*#__PURE__*/(0, _react.forwardRef)(function (_ref, ref) {
  var data = _ref.data,
      _ref$showDownload = _ref.showDownload,
      showDownload = _ref$showDownload === void 0 ? true : _ref$showDownload;

  var _useState = (0, _react.useState)(false),
      _useState2 = _slicedToArray(_useState, 2),
      visible = _useState2[0],
      setVisible = _useState2[1];

  var _useState3 = (0, _react.useState)(0),
      _useState4 = _slicedToArray(_useState3, 2),
      currentIndex = _useState4[0],
      setCurrnetIndex = _useState4[1];

  var _useState5 = (0, _react.useState)(data[0]),
      _useState6 = _slicedToArray(_useState5, 2),
      currentImgData = _useState6[0],
      setCurrentImgData = _useState6[1];

  var _useState7 = (0, _react.useState)(0),
      _useState8 = _slicedToArray(_useState7, 2),
      currentRotateDeg = _useState8[0],
      setCurrentRotateDeg = _useState8[1];

  var _useState9 = (0, _react.useState)(1),
      _useState10 = _slicedToArray(_useState9, 2),
      currentScale = _useState10[0],
      setCurrentScale = _useState10[1];

  var _useState11 = (0, _react.useState)(true),
      _useState12 = _slicedToArray(_useState11, 2),
      isLoading = _useState12[0],
      setIsLoading = _useState12[1];

  var _useState13 = (0, _react.useState)(0),
      _useState14 = _slicedToArray(_useState13, 2),
      moveX = _useState14[0],
      setMoveX = _useState14[1];

  var _useState15 = (0, _react.useState)(0),
      _useState16 = _slicedToArray(_useState15, 2),
      moveY = _useState16[0],
      setMoveY = _useState16[1];

  var imgRef = (0, _react.useRef)(document.createElement('img'));
  var DragRef = (0, _react.useRef)(document.createElement('div'));

  var showPreview = function showPreview() {
    var index = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
    setCurrnetIndex(index);
    setCurrentImgData(data[index]);
    setVisible(true);
  };

  var hidePreview = function hidePreview() {
    setVisible(false);
  };

  var handlePreImgClick = function handlePreImgClick() {
    if (currentIndex === 0) return;
    setIsLoading(true);
    setCurrentImgData(data[currentIndex - 1]);
    setCurrnetIndex(currentIndex - 1);
    setCurrentScale(1);
    setCurrentRotateDeg(0);
  };

  var handleNextImgClick = function handleNextImgClick() {
    if (currentIndex === data.length - 1) return;
    setIsLoading(true);
    setCurrentImgData(data[currentIndex + 1]);
    setCurrnetIndex(currentIndex + 1);
    setCurrentScale(1);
    setCurrentRotateDeg(0);
  };

  var handleLeftRotate = function handleLeftRotate() {
    setCurrentRotateDeg(currentRotateDeg - 90);
  };

  var handleMouseDownImg = function handleMouseDownImg(e) {
    e.preventDefault();
    var downX = e.clientX;
    var downY = e.clientY; // 因为这个moveX不闭包的话在拖动的时候他就 一直累加

    var beforeX = moveX;
    var beforeY = moveY;

    DragRef.current.onmousemove = function (e1) {
      //获取x和y
      var nx = e1.clientX;
      var ny = e1.clientY; // //计算移动后的左偏移量和顶部的偏移量

      var nl = nx - downX + beforeX;
      var nt = ny - downY + beforeY;
      setMoveX(nl);
      setMoveY(nt);
    };
  };

  var handleMouseUpImg = function handleMouseUpImg(e) {
    e.preventDefault();
    DragRef.current.onmousemove = null;
  };

  var handleRightRotate = function handleRightRotate() {
    setCurrentRotateDeg(currentRotateDeg + 90);
  };

  var handleEnlarge = function handleEnlarge() {
    if (currentScale === 5) return;
    setCurrentScale(Number((currentScale + 0.1).toFixed(1)));
  };

  var handleShrink = function handleShrink() {
    if (currentScale === 0.1) return;
    setCurrentScale(Number((currentScale - 0.1).toFixed(1)));
  };

  (0, _react.useImperativeHandle)(ref, function () {
    return {
      show: showPreview,
      hide: hidePreview
    };
  });
  (0, _react.useEffect)(function () {
    var timer = setInterval(function () {
      if (imgRef.current.complete) {
        setIsLoading(false);
        clearInterval(timer);
      }
    }, 500);
  }, [currentIndex]);

  var renderPreviewer = function renderPreviewer() {
    if (!visible) return null;
    return /*#__PURE__*/_react["default"].createElement("div", {
      className: (0, _classnames["default"])(prefix, 'document-mouse-event-ignore')
    }, /*#__PURE__*/_react["default"].createElement("div", {
      className: "".concat(prefix, "__header")
    }, /*#__PURE__*/_react["default"].createElement("span", {
      className: "".concat(prefix, "__header-file-name")
    }, /*#__PURE__*/_react["default"].createElement(_tooltip["default"].Text, {
      text: currentImgData && currentImgData.fileName || '',
      isPercent: true,
      minusWidth: 60
    })), /*#__PURE__*/_react["default"].createElement("span", null, showDownload && currentImgData && currentImgData.downloadUrl && /*#__PURE__*/_react["default"].createElement("a", {
      className: "".concat(prefix, "__header-download"),
      href: (currentImgData === null || currentImgData === void 0 ? void 0 : currentImgData.downloadUrl) || 'javascript:;'
    }, /*#__PURE__*/_react["default"].createElement("i", {
      className: (0, _classnames["default"])('tu-icon-APP-xiazai', "".concat(prefix, "__header-download-icon"))
    }), (0, _getLocale.getLocale)('Mod_Download')), /*#__PURE__*/_react["default"].createElement("span", {
      className: (0, _classnames["default"])('tu-icon-close', "".concat(prefix, "__header-close")),
      onClick: hidePreview
    }))), /*#__PURE__*/_react["default"].createElement("div", {
      className: "".concat(prefix, "__body"),
      ref: DragRef,
      onMouseDown: handleMouseDownImg,
      onMouseUp: handleMouseUpImg
    }, /*#__PURE__*/_react["default"].createElement("span", {
      className: (0, _classnames["default"])("".concat(prefix, "__body-operate-btn"), "".concat(prefix, "__body-operate-btn--left"), _defineProperty({}, "".concat(prefix, "__body-operate-btn--disable"), currentIndex === 0)),
      onClick: handlePreImgClick
    }, /*#__PURE__*/_react["default"].createElement("i", {
      className: "tu-icon-left"
    })), /*#__PURE__*/_react["default"].createElement("span", {
      className: (0, _classnames["default"])("".concat(prefix, "__body-operate-btn"), "".concat(prefix, "__body-operate-btn--right"), _defineProperty({}, "".concat(prefix, "__body-operate-btn--disable"), currentIndex === data.length - 1)),
      onClick: handleNextImgClick
    }, /*#__PURE__*/_react["default"].createElement("i", {
      className: "tu-icon-APP-xi"
    })), isLoading && /*#__PURE__*/_react["default"].createElement("div", {
      className: "".concat(prefix, "__body--loading")
    }, /*#__PURE__*/_react["default"].createElement("img", {
      src: _loading["default"],
      alt: ""
    })), /*#__PURE__*/_react["default"].createElement("div", null, /*#__PURE__*/_react["default"].createElement("img", {
      className: "".concat(prefix, "__body-img"),
      ref: imgRef,
      alt: "",
      src: (currentImgData === null || currentImgData === void 0 ? void 0 : currentImgData.previewUrl) || (currentImgData === null || currentImgData === void 0 ? void 0 : currentImgData.bigImageUrl),
      style: {
        transform: "scale(".concat(currentScale, ") rotate(").concat(currentRotateDeg, "deg) "),
        left: "".concat(moveX, "px"),
        top: "".concat(moveY, "px")
      }
    }))), /*#__PURE__*/_react["default"].createElement("div", {
      className: "".concat(prefix, "__footer")
    }, /*#__PURE__*/_react["default"].createElement(_tooltip["default"], {
      overlay: (0, _getLocale.getLocale)('OKR_Ali_Butt_Narrow'),
      placement: "top"
    }, /*#__PURE__*/_react["default"].createElement("span", {
      className: "".concat(prefix, "__footer-btn"),
      onClick: handleShrink
    }, /*#__PURE__*/_react["default"].createElement(_shrink["default"], null))), /*#__PURE__*/_react["default"].createElement(_tooltip["default"], {
      overlay: (0, _getLocale.getLocale)('OKR_Ali_Butt_Enlarge'),
      placement: "top"
    }, /*#__PURE__*/_react["default"].createElement("span", {
      className: "".concat(prefix, "__footer-btn"),
      onClick: handleEnlarge
    }, /*#__PURE__*/_react["default"].createElement(_enlarge["default"], null))), /*#__PURE__*/_react["default"].createElement(_tooltip["default"], {
      overlay: "\u987A\u65F6\u9488\u65CB\u8F6C",
      placement: "top"
    }, /*#__PURE__*/_react["default"].createElement("span", {
      className: "".concat(prefix, "__footer-btn"),
      onClick: handleRightRotate
    }, /*#__PURE__*/_react["default"].createElement(_rightRotate["default"], null))), /*#__PURE__*/_react["default"].createElement(_tooltip["default"], {
      overlay: "\u9006\u65F6\u9488\u65CB\u8F6C",
      placement: "top"
    }, /*#__PURE__*/_react["default"].createElement("span", {
      className: "".concat(prefix, "__footer-btn"),
      onClick: handleLeftRotate
    }, /*#__PURE__*/_react["default"].createElement(_leftRotate["default"], null)))));
  };

  return /*#__PURE__*/_reactDom["default"].createPortal(renderPreviewer(), document.body);
});
var _default = ImgViewer;
exports["default"] = _default;