import _extends from "@babel/runtime/helpers/extends";
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/objectWithoutPropertiesLoose";
var _excluded = ["speed", "autoplay", "loop", "picUrls", "height", "delay"];
import * as React from 'react';
import { useEffect, useRef, useState } from 'react';
import "./index.scss";
var DCSlider = function DCSlider(_ref) {
  var _ref$speed = _ref.speed,
    speed = _ref$speed === void 0 ? 500 : _ref$speed,
    autoplay = _ref.autoplay,
    loop = _ref.loop,
    _ref$picUrls = _ref.picUrls,
    picUrls = _ref$picUrls === void 0 ? [] : _ref$picUrls,
    height = _ref.height,
    delay = _ref.delay,
    otherProps = _objectWithoutPropertiesLoose(_ref, _excluded);
  var _useState = useState(0),
    currentIndex = _useState[0],
    setCurrentIndex = _useState[1];
  var autoplayRef = useRef(null);

  // 切换到下一张
  var nextSlide = function nextSlide() {
    if (currentIndex < picUrls.length - 1) {
      setCurrentIndex(currentIndex + 1);
    } else if (loop) {
      setCurrentIndex(0);
    } else {
      stopAutoplay();
    }
  };

  // 启动自动播放
  var startAutoplay = function startAutoplay() {
    if (autoplay && !autoplayRef.current) {
      autoplayRef.current = setInterval(function () {
        nextSlide();
      }, delay);
    }
  };

  // 停止自动播放
  var stopAutoplay = function stopAutoplay() {
    if (autoplayRef.current) {
      clearInterval(autoplayRef.current);
      autoplayRef.current = null;
    }
  };
  useEffect(function () {
    startAutoplay();
    return function () {
      return stopAutoplay();
    };
  }, [autoplay, currentIndex]);
  return /*#__PURE__*/React.createElement("div", _extends({
    className: "carousel",
    style: {
      height: height ? height + "px" : 'auto'
    }
  }, otherProps), /*#__PURE__*/React.createElement("div", {
    className: "carousel__wrapper",
    style: {
      transform: "translateX(-" + currentIndex * 100 + "%)",
      transitionDuration: speed + "ms"
    }
  }, picUrls.map(function (url, index) {
    return /*#__PURE__*/React.createElement("div", {
      key: index,
      className: "carousel__slide"
    }, /*#__PURE__*/React.createElement("img", {
      src: url,
      alt: "Slide " + index,
      style: {
        height: height ? height + "px" : '100%'
      }
    }));
  })));
};
export default DCSlider;