"use strict";

function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _react = _interopRequireWildcard(require("react"));
var _classnames = _interopRequireDefault(require("classnames"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); }
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
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(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
// 参考：https://github.com/sachinchoolur/lightGallery/blob/master/src/plugins/thumbnail/lg-thumbnail-settings.ts
// https://github.com/sachinchoolur/lightGallery/blob/master/src/plugins/thumbnail/lg-thumbnail.ts

var isDragging = false;
var translateX = 0;
var thumbDragUtils = {
  cords: {
    startX: 0,
    endX: 0
  },
  isMoved: false,
  newTranslateX: 0,
  startTime: new Date(),
  endTime: new Date(),
  touchMoveTime: 0
};
var thumbClickable = true;
var thumbnailSwipeThreshold = 10;
var Thumbnail = function Thumbnail(props) {
  var _props$thumbWidth = props.thumbWidth,
    thumbWidth = _props$thumbWidth === void 0 ? 100 : _props$thumbWidth,
    _props$thumbMargin = props.thumbMargin,
    thumbMargin = _props$thumbMargin === void 0 ? 5 : _props$thumbMargin,
    thumbCurrent = props.thumbCurrent,
    children = props.children,
    galleryCount = props.galleryCount,
    onClickThumbItem = props.onClickThumbItem,
    _props$currentPagerPo = props.currentPagerPosition,
    currentPagerPosition = _props$currentPagerPo === void 0 ? 'middle' : _props$currentPagerPo;
  var $thumbOuter = (0, _react.useRef)();
  var $thumbGroup = (0, _react.useRef)();
  var _useState = (0, _react.useState)(0),
    _useState2 = _slicedToArray(_useState, 2),
    thumbOuterWidth = _useState2[0],
    setThumbOuterWidth = _useState2[1];
  var _useState3 = (0, _react.useState)(0),
    _useState4 = _slicedToArray(_useState3, 2),
    thumbTotalWidth = _useState4[0],
    setThumbTotalWidth = _useState4[1];
  var init = function init() {
    var _$thumbOuter$current;
    setThumbOuterWidth($thumbOuter === null || $thumbOuter === void 0 || (_$thumbOuter$current = $thumbOuter.current) === null || _$thumbOuter$current === void 0 ? void 0 : _$thumbOuter$current.clientWidth);
    setThumbTotalWidth(galleryCount * (thumbWidth + thumbMargin));
    // Thumbnail animation value
    translateX = 0;
  };
  var destroy = function destroy() {
    thumbDragUtils = {
      cords: {
        startX: 0,
        endX: 0
      },
      isMoved: false,
      newTranslateX: 0,
      startTime: new Date(),
      endTime: new Date(),
      touchMoveTime: 0
    };
  };
  var onThumbMouseDown = function onThumbMouseDown(e) {
    if (thumbTotalWidth > thumbOuterWidth) {
      // execute only on .lg-object
      e.preventDefault();
      thumbDragUtils.cords.startX = e.pageX;
      thumbDragUtils.startTime = new Date();
      thumbClickable = false;
      isDragging = true;
      //
      // // ** Fix for webkit cursor issue https://code.google.com/p/chromium/issues/detail?id=26723
      // this.core.outer.get().scrollLeft += 1;
      // this.core.outer.get().scrollLeft -= 1;
      //
      if ($thumbOuter.current) {
        $thumbOuter.current.classList.remove('spec-image-preview-grab');
        $thumbOuter.current.classList.add('spec-image-preview-grabbing');
      }
    }
  };
  var onThumbMouseMove = function onThumbMouseMove(e) {
    if (isDragging) {
      thumbDragUtils.cords.endX = e.pageX;
      thumbDragUtils = onThumbTouchMove(thumbDragUtils);
    }
  };
  var onThumbMouseUp = function onThumbMouseUp(e) {
    if (thumbDragUtils.isMoved) {
      thumbDragUtils = onThumbTouchEnd(thumbDragUtils);
    } else {
      thumbClickable = true;
    }
    if (isDragging) {
      var _$thumbOuter$current2, _$thumbOuter$current3;
      isDragging = false;
      $thumbOuter === null || $thumbOuter === void 0 || (_$thumbOuter$current2 = $thumbOuter.current) === null || _$thumbOuter$current2 === void 0 || _$thumbOuter$current2.classList.remove('spec-image-preview-grabbing');
      $thumbOuter === null || $thumbOuter === void 0 || (_$thumbOuter$current3 = $thumbOuter.current) === null || _$thumbOuter$current3 === void 0 || _$thumbOuter$current3.classList.add('spec-image-preview-grab');
    }
  };
  var onThumbTouchMove = function onThumbTouchMove(thumbDragUtils) {
    thumbDragUtils.newTranslateX = translateX;
    thumbDragUtils.isMoved = true;
    thumbDragUtils.touchMoveTime = new Date().valueOf();
    thumbDragUtils.newTranslateX -= thumbDragUtils.cords.endX - thumbDragUtils.cords.startX;
    thumbDragUtils.newTranslateX = getPossibleTransformX(thumbDragUtils.newTranslateX);

    // move current slide
    setTranslate(thumbDragUtils.newTranslateX);
    $thumbOuter.current.classList.add('spec-image-preview-dragging');
    return thumbDragUtils;
  };
  var onTouchStart = function onTouchStart(e) {
    if (thumbTotalWidth > thumbOuterWidth) {
      e.preventDefault();
      thumbDragUtils.cords.startX = e.targetTouches[0].pageX;
      thumbClickable = false;
      thumbDragUtils.startTime = new Date();
    }
  };
  var onTouchMove = function onTouchMove(e) {
    if (thumbTotalWidth > thumbOuterWidth) {
      e.preventDefault();
      thumbDragUtils.cords.endX = e.targetTouches[0].pageX;
      thumbDragUtils = onThumbTouchMove(thumbDragUtils);
    }
  };
  var onTouchEnd = function onTouchEnd() {
    if (thumbDragUtils.isMoved) {
      thumbDragUtils = onThumbTouchEnd(thumbDragUtils);
    } else {
      thumbClickable = true;
    }
  };
  var onThumbTouchEnd = function onThumbTouchEnd(thumbDragUtils) {
    thumbDragUtils.isMoved = false;
    thumbDragUtils.endTime = new Date();
    $thumbOuter.current.classList.remove('spec-image-preview-dragging');
    var touchDuration = thumbDragUtils.endTime.valueOf() - thumbDragUtils.startTime.valueOf();
    var distanceXnew = thumbDragUtils.cords.endX - thumbDragUtils.cords.startX;
    var speedX = Math.abs(distanceXnew) / touchDuration;
    // Some magical numbers
    // Can be improved
    if (speedX > 0.15 && thumbDragUtils.endTime.valueOf() - thumbDragUtils.touchMoveTime < 30) {
      speedX += 1;
      if (speedX > 2) {
        speedX += 1;
      }
      speedX = speedX + speedX * (Math.abs(distanceXnew) / thumbOuterWidth);
      $thumbGroup.current.style.transitionDuration = Math.min(speedX - 1, 2) + 'settings';
      distanceXnew = distanceXnew * speedX;
      translateX = getPossibleTransformX(translateX - distanceXnew);
      setTranslate(translateX);
    } else {
      translateX = thumbDragUtils.newTranslateX;
    }
    if (Math.abs(thumbDragUtils.cords.endX - thumbDragUtils.cords.startX) < thumbnailSwipeThreshold) {
      thumbClickable = true;
    }
    return thumbDragUtils;
  };
  var getPossibleTransformX = function getPossibleTransformX(left) {
    if (left > thumbTotalWidth - thumbOuterWidth) {
      left = thumbTotalWidth - thumbOuterWidth;
    }
    if (left < 0) {
      left = 0;
    }
    return left;
  };
  var setTranslate = function setTranslate(value) {
    // console.log('偏移量', -value)
    $thumbGroup.current.style.transform = 'translate3d(-' + value + 'px, 0px, 0px)';
  };
  var animateThumb = function animateThumb(index) {
    // $thumbGroup.current.style.transitionDuration = '400ms'
    var position = 0;
    switch (currentPagerPosition) {
      case 'left':
        position = 0;
        break;
      case 'middle':
        position = thumbOuterWidth / 2 - thumbWidth / 2;
        break;
      case 'right':
        position = thumbOuterWidth - thumbWidth;
    }
    translateX = (thumbWidth + thumbMargin) * index - 1 - position;
    if (translateX > thumbTotalWidth - thumbOuterWidth) {
      translateX = thumbTotalWidth - thumbOuterWidth;
    }
    if (translateX < 0) {
      translateX = 0;
    }
    setTranslate(translateX);
  };
  (0, _react.useEffect)(function () {
    init();
    return function () {
      destroy();
    };
  }, [$thumbOuter === null || $thumbOuter === void 0 ? void 0 : $thumbOuter.current, $thumbGroup === null || $thumbGroup === void 0 ? void 0 : $thumbGroup.current, thumbWidth, thumbMargin, galleryCount]);

  // 计算转到中间位置
  // const slideThumbToMiddle = () => {
  //   const order = thumbCurrent + 1
  //   // 当前图片块距离
  //   const halfWidth = (thumbWidth + thumbMargin) / 2
  //   const curDistance = order * (thumbWidth + thumbMargin) - halfWidth
  //   const pageNum = Math.ceil((order * (thumbWidth + thumbMargin) / thumbOuterWidth))
  //   const totalPage = Math.ceil(thumbTotalWidth / thumbOuterWidth)
  //   const centerPosition = thumbOuterWidth / 2  // 中心点
  //   if (isNaN(pageNum)) {
  //     return
  //   }
  //   if (curDistance < centerPosition) {
  //     console.log('Rule1，位置小于中心点，不设偏移量')
  //     thumbDragUtils.newTranslateX = 0
  //   } else {
  //     console.log('thumbTotalWidth - curDistance', thumbTotalWidth - curDistance)
  //     if ((thumbTotalWidth - curDistance) < centerPosition) {
  //       console.log('Rule3,已经不足空间转到中间点了')
  //       thumbDragUtils.newTranslateX = thumbTotalWidth - thumbOuterWidth
  //     } else {
  //       console.log('Rule2,直接跳转到中间点')
  //       thumbDragUtils.newTranslateX = curDistance - centerPosition
  //     }
  //   }
  //   setTranslate(thumbDragUtils.newTranslateX)
  // }
  (0, _react.useEffect)(function () {
    // 判断是不是在中间
    animateThumb(thumbCurrent);
  }, [thumbCurrent, thumbTotalWidth, thumbOuterWidth, thumbMargin]);
  return /*#__PURE__*/_react.default.createElement("div", {
    className: 'spec-image-preview-thumb-outer spec-image-preview-thumb-align-middle spec-image-preview-grab  spec-image-preview-animate-thumb',
    ref: $thumbOuter
  }, /*#__PURE__*/_react.default.createElement("div", {
    className: 'spec-image-preview-thumb spec-image-preview-thumb-group',
    style: {
      transitionDuration: '300ms',
      width: galleryCount * (thumbWidth + thumbMargin) + 'px',
      position: 'relative',
      transform: 'translate3d(0px, 0px, 0px)'
    },
    ref: $thumbGroup,
    onMouseDown: onThumbMouseDown,
    onMouseUp: onThumbMouseUp,
    onMouseMove: onThumbMouseMove,
    onTouchStart: onTouchStart,
    onTouchMove: onTouchMove,
    onTouchEnd: onTouchEnd
  }, _react.default.Children.map(children, function (item, index) {
    var imgNode; // = item.type !== 'img' ? item.props.children : item
    if (item.type === 'img') {
      imgNode = item;
    } else if (item.props.children) {
      if (Object.prototype.toString.call(item.props.children) === '[object Array]') {
        // 多个子节点，只取img标签
        imgNode = item.props.children.find(function (cItem) {
          return cItem.type === 'img';
        });
      }
      if (Object.prototype.toString.call(item.props.children) === '[object Object]') {
        imgNode = item.props.children;
      }
    } else {
      // 没有标签
      imgNode = {};
    }
    // 单个子节点
    // console.log('children=>item', item.props.children)
    return /*#__PURE__*/_react.default.createElement("div", {
      className: (0, _classnames.default)('spec-image-preview-thumb-item', thumbCurrent === index ? 'active' : ''),
      "data-item-id": index,
      style: {
        width: thumbWidth + 'px',
        height: '80px',
        marginRight: '5px'
      },
      onClick: function onClick(e) {
        if (thumbClickable) {
          onClickThumbItem === null || onClickThumbItem === void 0 || onClickThumbItem('number', index);
        }
      }
    }, /*#__PURE__*/_react.default.createElement("img", _extends({
      src: item.props['data-src' || 'src']
    }, imgNode.props, {
      "data-item-id": index,
      onMouseDown: function onMouseDown(evt) {
        return evt.preventDefault();
      }
    })));
  })));
};
var _default = exports.default = Thumbnail;