"use strict";

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

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

var _propTypes = _interopRequireDefault(require("prop-types"));

var _finger = _interopRequireDefault(require("./assets/libs/finger.js"));

var _transform = _interopRequireDefault(require("./assets/libs/transform.js"));

var _components = require("./assets/libs/components.js");

var _singleton = _interopRequireDefault(require("./assets/libs/singleton.js"));

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

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

function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

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; }

var MARGIN = 30;

var noop = function noop() {};

function aliPaySdkReady(callback) {
  // 如果 jsbridge 已经注入则直接调用
  if (window.AlipayJSBridge) {
    // eslint-disable-next-line no-unused-expressions
    callback && callback();
  } else {
    // 如果没有注入则监听注入的事件
    document.addEventListener('AlipayJSBridgeReady', callback, false);
  }
}

var ImageViewer =
/*#__PURE__*/
function (_Component) {
  _inherits(ImageViewer, _Component);

  function ImageViewer(props) {
    var _this;

    _classCallCheck(this, ImageViewer);

    _this = _possibleConstructorReturn(this, _getPrototypeOf(ImageViewer).call(this));

    _defineProperty(_assertThisInitialized(_this), "initScale", 1);

    _defineProperty(_assertThisInitialized(_this), "screenWidth", window.innerWidth || window.screen.availWidth);

    _defineProperty(_assertThisInitialized(_this), "screenHeight", window.innerHeight || window.screen.availHeight);

    _defineProperty(_assertThisInitialized(_this), "list", null);

    _defineProperty(_assertThisInitialized(_this), "ob", null);

    _defineProperty(_assertThisInitialized(_this), "focused", null);

    _defineProperty(_assertThisInitialized(_this), "init", function () {
      var firstShow = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
      // eslint-disable-next-line prefer-const
      var _this$props = _this.props,
          imagelist = _this$props.imagelist,
          initCallback = _this$props.initCallback,
          _this$props$current = _this$props.current,
          current = _this$props$current === void 0 ? 0 : _this$props$current;

      if (current > imagelist.length - 1) {
        current = imagelist.length - 1;
      }

      _this.arrLength = imagelist.length;
      _this.list = _this.refs.imagelist;

      if (firstShow) {
        (0, _transform["default"])(_this.list);

        _this.setState({
          initTitle: document.title
        });
      }

      _this.changeIndex(current, false);

      _this.setState({
        current: current
      });

      _this.bindStyle(current); // eslint-disable-next-line no-unused-expressions


      initCallback && initCallback();
    });

    _defineProperty(_assertThisInitialized(_this), "changeTitle", function (title) {
      if (!title) title = "".concat(_this.state.current + 1, " / ").concat(_this.arrLength);
      var userAgent = navigator.userAgent.toLowerCase();

      if (window.ehopenapi) {
        var ehopenapi = window.ehopenapi;
        ehopenapi.configTitle({
          title: title
        });
      } else if (userAgent.match(/Alipay/i) == 'alipay') {
        aliPaySdkReady(function () {
          window.AlipayJSBridge.call('setTitle', {
            title: title
          });
        });
      } else {
        document.title = title;
      }
    });

    _defineProperty(_assertThisInitialized(_this), "onOrientationChange", function () {
      // 方向改变后新的innerHeight生效需要delay
      setTimeout(function () {
        _this.screenWidth = window.innerWidth || window.screen.availWidth;
        _this.screenHeight = window.innerHeight || window.screen.availHeight;

        _this.changeIndex(_this.state.current);
      }, 100);
    });

    _defineProperty(_assertThisInitialized(_this), "onSingleTap", function () {
      // eslint-disable-next-line no-unused-expressions
      _this.props.close && _this.props.close();
    });

    _defineProperty(_assertThisInitialized(_this), "onPressMove", function (evt) {
      var current = _this.state.current;

      _this.endAnimation();

      if (!_this.focused) {
        if (current === 0 && evt.deltaX > 0 || current === _this.arrLength - 1 && evt.deltaX < 0) {
          _this.list.translateX += evt.deltaX / 3;
        } else {
          _this.list.translateX += evt.deltaX;
        }
      }
    });

    _defineProperty(_assertThisInitialized(_this), "onSwipe", function (evt) {
      var direction = evt.direction;
      var current = _this.state.current;

      if (_this.focused) {
        return false;
      }

      switch (direction) {
        case 'Left':
          // eslint-disable-next-line no-unused-expressions
          current < _this.arrLength - 1 && ++current && _this.bindStyle(current);
          break;

        case 'Right':
          // eslint-disable-next-line no-unused-expressions
          current > 0 && current-- && _this.bindStyle(current);
          break;

        default:
          // do nothing
          break;
      }

      _this.changeIndex(current);
    });

    _defineProperty(_assertThisInitialized(_this), "onPicPressMove", function (evt) {
      var deltaX = evt.deltaX,
          deltaY = evt.deltaY;

      var isLongPic = _this.ob.getAttribute('long');

      var _this$ob = _this.ob,
          scaleX = _this$ob.scaleX,
          width = _this$ob.width;

      if (scaleX <= 1 || evt.touches.length > 1) {
        _this.focused = false;
        return;
      }

      if (_this.ob && _this.checkBoundary(deltaX, deltaY)) {
        // eslint-disable-next-line no-unused-expressions
        !isLongPic && (_this.ob.translateX += deltaX);
        _this.ob.translateY += deltaY;

        if (isLongPic && scaleX * width === _this.screenWidth) {
          _this.focused = false;
        }
      } else {
        _this.focused = false;
      } // 超过原尺寸，不允许切换


      if (scaleX > 1) {
        _this.focused = true;
      }
    });

    _defineProperty(_assertThisInitialized(_this), "onPinch", function (evt) {
      if (_this.props.disablePinch || _this.ob.getAttribute('long')) {
        return false;
      }

      _this.ob.style.webkitTransition = 'cubic-bezier(.25,.01,.25,1)';
      var _this$ob2 = _this.ob,
          originX = _this$ob2.originX,
          originY = _this$ob2.originY;
      var originX2 = evt.center.x - _this.screenWidth / 2 - document.body.scrollLeft;
      var originY2 = evt.center.y - _this.screenHeight / 2 - document.body.scrollTop;
      _this.ob.originX = originX2;
      _this.ob.originY = originY2;
      _this.ob.translateX = _this.ob.translateX + (originX2 - originX) * _this.ob.scaleX;
      _this.ob.translateY = _this.ob.translateY + (originY2 - originY) * _this.ob.scaleY;
      _this.ob.scaleX = _this.ob.scaleY = _this.initScale * evt.scale;
    });

    _defineProperty(_assertThisInitialized(_this), "onRotate", function (evt) {
      if (!_this.props.enableRotate || _this.ob.getAttribute('rate') >= 3.5) {
        return false;
      }

      _this.ob.style.webkitTransition = 'cubic-bezier(.25,.01,.25,1)';
      _this.ob.rotateZ += evt.angle;
    });

    _defineProperty(_assertThisInitialized(_this), "onLongTap", function () {
      // eslint-disable-next-line no-unused-expressions
      _this.props.longTap && _this.props.longTap();
    });

    _defineProperty(_assertThisInitialized(_this), "onMultipointEnd", function () {
      // translate to normal
      _this.changeIndex(_this.state.current);

      if (!_this.ob) {
        return;
      }

      _this.ob.style.webkitTransition = '300ms ease';
      var maxScale = _this.props.maxScale;

      var isLongPic = _this.ob.getAttribute('long'); // scale to normal


      if (_this.ob.scaleX < 1) {
        _this.restore(false);
      }

      if (_this.ob.scaleX > maxScale && !isLongPic) {
        _this.setScale(maxScale);
      } // rotate to normal


      var rotation = _this.ob.rotateZ % 360;

      var rate = _this.ob.getAttribute('rate');

      if (rotation < 0) {
        rotation = 360 + rotation;
      }

      _this.ob.rotateZ = rotation;

      if (rotation > 0 && rotation < 45) {
        _this.ob.rotateZ = 0;
      } else if (rotation >= 315) {
        _this.ob.rotateZ = 360;
      } else if (rotation >= 45 && rotation < 135) {
        _this.ob.rotateZ = 90;

        _this.setScale(rate);
      } else if (rotation >= 135 && rotation < 225) {
        _this.ob.rotateZ = 180;
      } else if (rotation >= 225 && rotation < 315) {
        _this.ob.rotateZ = 270;

        _this.setScale(rate);
      }
    });

    _defineProperty(_assertThisInitialized(_this), "onDoubleTap", function (evt) {
      if (_this.props.disableDoubleTap) {
        return false;
      }

      var origin = evt.origin;
      var originX = origin[0] - _this.screenWidth / 2 - document.body.scrollLeft;
      var originY = origin[1] - _this.screenHeight / 2 - document.body.scrollTop;

      var isLongPic = _this.ob.getAttribute('long');

      if (_this.ob.scaleX === 1) {
        // eslint-disable-next-line no-unused-expressions,no-multi-assign
        !isLongPic && (_this.ob.translateX = _this.ob.originX = originX); // eslint-disable-next-line no-unused-expressions,no-multi-assign

        !isLongPic && (_this.ob.translateY = _this.ob.originY = originY);

        _this.setScale(isLongPic ? _this.screenWidth / _this.ob.width : _this.props.maxScale);
      } else {
        _this.ob.translateX = _this.ob.originX;
        _this.ob.translateY = _this.ob.originY;

        _this.setScale(1);
      }
    });

    _defineProperty(_assertThisInitialized(_this), "bindStyle", function (current) {
      _this.setState({
        current: current
      }, function () {
        // eslint-disable-next-line no-unused-expressions
        _this.ob && _this.restore();
        _this.ob = document.getElementById("view".concat(current));

        if (_this.ob && !_this.ob.scaleX) {
          (0, _transform["default"])(_this.ob);
        } // ease hide page number


        var page = _this.refs.page;

        if (page) {
          page.classList.remove('hide');
          setTimeout(function () {
            page.classList.add('hide');
          }, 2000);
        }
      });
    });

    _defineProperty(_assertThisInitialized(_this), "changeIndex", function (current) {
      var ease = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
      // eslint-disable-next-line no-unused-expressions
      ease && (_this.list.style.webkitTransition = '300ms ease');
      _this.list.translateX = -current * (_this.screenWidth + _this.props.gap); // eslint-disable-next-line no-unused-expressions

      _this.props.changeIndex && _this.props.changeIndex(current);
    });

    _defineProperty(_assertThisInitialized(_this), "setScale", function (size) {
      _this.ob.style.webkitTransition = '300ms ease-in-out'; // eslint-disable-next-line no-multi-assign

      _this.ob.scaleX = _this.ob.scaleY = size;
    });

    _defineProperty(_assertThisInitialized(_this), "restore", function () {
      var rotate = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
      // eslint-disable-next-line no-multi-assign
      _this.ob.translateX = _this.ob.translateY = 0; // eslint-disable-next-line no-unused-expressions

      !!rotate && (_this.ob.rotateZ = 0); // eslint-disable-next-line no-multi-assign

      _this.ob.scaleX = _this.ob.scaleY = 1; // eslint-disable-next-line no-multi-assign

      _this.ob.originX = _this.ob.originY = 0;
    });

    _defineProperty(_assertThisInitialized(_this), "endAnimation", function () {
      _this.list.style.webkitTransition = '0'; // eslint-disable-next-line no-unused-expressions

      _this.ob && _this.ob.style && (_this.ob.style.webkitTransition = '0');
    });

    _defineProperty(_assertThisInitialized(_this), "checkBoundary", function () {
      var deltaX = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
      var deltaY = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
      var _this$ob3 = _this.ob,
          scaleX = _this$ob3.scaleX,
          translateX = _this$ob3.translateX,
          translateY = _this$ob3.translateY,
          originX = _this$ob3.originX,
          originY = _this$ob3.originY,
          width = _this$ob3.width,
          height = _this$ob3.height;

      var rate = _this.ob.getAttribute('rate');

      if (scaleX !== 1 || scaleX !== rate) {
        // include long picture
        var rangeLeft = (scaleX - 1) * (width / 2 + originX) + originX;
        var rangeRight = -(scaleX - 1) * (width / 2 - originX) + originX;
        var rangeUp = (scaleX - 1) * (height / 2 + originY) + originY;
        var rangeDown = -(scaleX - 1) * (height / 2 - originY) + originY;

        if (translateX + deltaX <= rangeLeft && translateX + deltaX >= rangeRight && translateY + deltaY <= rangeUp && translateY + deltaY >= rangeDown) {
          return true;
        }
      }

      return false;
    });

    _this.arrLength = props.imagelist.length;
    _this.state = {
      current: props.current,
      initTitle: ''
    };
    _this.onOrientationChange = _this.onOrientationChange.bind(_assertThisInitialized(_this));
    return _this;
  }

  _createClass(ImageViewer, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      if (this.props.visible) this.init(true);
      window.addEventListener('orientationchange', this.onOrientationChange);
    }
  }, {
    key: "componentDidUpdate",
    value: function componentDidUpdate(prevProps) {
      var _this$props2 = this.props,
          visible = _this$props2.visible,
          imagelist = _this$props2.imagelist,
          close = _this$props2.close;
      if (visible && !prevProps.visible) this.init(true);
      if (!visible && prevProps.visible) this.changeTitle(this.state.initTitle);

      if (visible) {
        if (imagelist.length !== prevProps.imagelist.length) {
          if (imagelist.length === 0) {
            close();
          } else {
            this.init(false);
          }
        }

        this.changeTitle();
      }
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      this.changeTitle(this.state.initTitle);
      window.removeEventListener('orientationchange', this.onOrientationChange);
    }
  }, {
    key: "onMultipointStart",
    value: function onMultipointStart() {
      this.initScale = this.ob.scaleX;
    } // eslint-disable-next-line consistent-return

  }, {
    key: "render",
    value: function render() {
      var _this2 = this;

      var _this$props3 = this.props,
          visible = _this$props3.visible,
          gap = _this$props3.gap,
          deletable = _this$props3.deletable,
          onDelete = _this$props3.onDelete;
      return visible ? _react["default"].createElement("div", {
        className: "imageview"
      }, _react["default"].createElement(_finger["default"], {
        onSingleTap: this.onSingleTap,
        onPressMove: this.onPressMove,
        onSwipe: this.onSwipe
      }, _react["default"].createElement("ul", {
        ref: "imagelist",
        className: "imagelist"
      }, this.props.imagelist.map(function (item, i) {
        return _react["default"].createElement("li", {
          className: "imagelist-item",
          style: {
            marginRight: "".concat(gap, "px")
          },
          key: "img".concat(i)
        }, _react["default"].createElement(_finger["default"], {
          onPressMove: _this2.onPicPressMove,
          onMultipointStart: _this2.onMultipointStart,
          onLongTap: _this2.onLongTap,
          onPinch: _this2.onPinch,
          onRotate: _this2.onRotate,
          onMultipointEnd: _this2.onMultipointEnd,
          onDoubleTap: _this2.onDoubleTap
        }, _react["default"].createElement(_components.CenterImage, {
          id: "view".concat(i),
          className: "imagelist-item-img",
          lazysrc: item,
          index: i,
          current: _this2.state.current
        })));
      }))), deletable ? _react["default"].createElement("div", {
        className: "imageview-delete-bar"
      }, _react["default"].createElement("i", {
        className: "imageview-del-icon iconfont icon-Electronic_invoice_t1",
        onClick: function onClick() {
          return onDelete(_this2.state.current);
        }
      }, "\uE690")) : null) : null;
    }
  }]);

  return ImageViewer;
}(_react.Component);

_defineProperty(ImageViewer, "defaultProps", {
  gap: MARGIN,
  current: 0,
  // disablePageNum: false,
  // desc: '',
  maxScale: 2,
  deletable: false,
  close: noop,
  onDelete: noop
});

_defineProperty(ImageViewer, "propTypes", {
  gap: _propTypes["default"].number,
  maxScale: _propTypes["default"].number,
  current: _propTypes["default"].number,
  imagelist: _propTypes["default"].array.isRequired,
  // desc: PropTypes.string,
  // disablePageNum: PropTypes.bool,
  disablePinch: _propTypes["default"].bool,
  enableRotate: _propTypes["default"].bool,
  disableDoubleTap: _propTypes["default"].bool,
  longTap: _propTypes["default"].func,
  close: _propTypes["default"].func,
  changeIndex: _propTypes["default"].func,
  initCallback: _propTypes["default"].func,
  visible: _propTypes["default"].bool,
  deletable: _propTypes["default"].bool,
  onDelete: _propTypes["default"].func
});

var SingleImgView = new _singleton["default"](ImageViewer);
exports.SingleImgView = SingleImgView;
var _default = ImageViewer;
exports["default"] = _default;