import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray";
import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _createClass from "@babel/runtime/helpers/esm/createClass";
import _possibleConstructorReturn from "@babel/runtime/helpers/esm/possibleConstructorReturn";
import _getPrototypeOf from "@babel/runtime/helpers/esm/getPrototypeOf";
import _assertThisInitialized from "@babel/runtime/helpers/esm/assertThisInitialized";
import _inherits from "@babel/runtime/helpers/esm/inherits";
import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
import React, { Children, Component } from 'react';
import PropTypes from 'prop-types';
import Dots from './dots';
import SmallImgIndex from './SmallImgIndex';
import ArrowBtn from './ArrowBtn';
import { getElementLeft } from '../util/xyPosition';
import easyToMap from '../util/easyToMap';

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

  /** *
   * params:
   *  type: 轮播图切换类型。
   *  dots: 底部显示跳转点的类型：目前存在 dots(点) smallImg(缩略图片) 若为空则不显示。
   *  time: number类型，划过一张幻灯片的时间。
   *
   * */
  function Carousel(props) {
    var _this;

    _classCallCheck(this, Carousel);

    _this = _possibleConstructorReturn(this, _getPrototypeOf(Carousel).call(this, props));

    _defineProperty(_assertThisInitialized(_this), "arrowClick", function (width, nextBool) {
      var switchType = _this.props.switchType; // 图片正在移动，则返回

      if (_this.animated) {
        return;
      } // 图片目前已经到最后一张,则移动到第一张


      var targetIndex;
      var _this$state = _this.state,
          len = _this$state.len,
          activeIndex = _this$state.activeIndex;

      if (nextBool) {
        if (activeIndex === len) {
          targetIndex = 1;
        } else {
          targetIndex = activeIndex + 1;
        }
      } else if (activeIndex === 1) {
        targetIndex = len;
      } else {
        targetIndex = activeIndex - 1;
      }

      _this.setState({
        activeIndex: targetIndex,
        next: nextBool
      });

      if (switchType === 'custom') {
        _this.customAnimation(nextBool);
      }

      _this.customAnimation(nextBool);

      _this.imgDotsSlide(targetIndex);
    });

    _defineProperty(_assertThisInitialized(_this), "imgDotsSlide", function (currentIndex) {
      var imgWidth = _this.props.imgWidth;
      var _this$props = _this.props,
          smallImgWidth = _this$props.smallImgWidth,
          _this$props$width = _this$props.width,
          width = _this$props$width === void 0 ? imgWidth : _this$props$width,
          imgGap = _this$props.imgGap;
      var len = _this.state.len;
      _this.myIndex = parseInt(currentIndex, 10); // 得到需要移动到的位置

      var distance = ((smallImgWidth + imgGap) * len - width) / len; // 单位距离

      var transformX = distance * (0 - _this.myIndex);

      if (_this.myIndex <= 3) {
        transformX = 0;
      } else if (_this.myIndex >= len - 3) {
        transformX = -distance * len;
      }

      if (len * smallImgWidth + (len - 1) * imgGap <= width) {
        _this.setState({
          activeIndex: _this.myIndex
        });

        return;
      }

      _this.setState({
        smallIndexLeft: transformX,
        activeIndex: _this.myIndex
      });
    });

    _defineProperty(_assertThisInitialized(_this), "handleMouseListener", function (event) {
      var _this$props2 = _this.props,
          dotsDisplayType = _this$props2.dotsDisplayType,
          arrowDisplayType = _this$props2.arrowDisplayType;

      var typeOfSlideBtn = function typeOfSlideBtn(type, prevState) {
        var btnState = '';

        switch (type) {
          case 'hover':
            btnState = !prevState;
            break;

          case 'display':
            btnState = true;
            break;

          case 'hidden':
            btnState = false;
            break;

          default:
            return;
        }

        return btnState;
      };

      var arrowDisplay = typeOfSlideBtn(arrowDisplayType, _this.state.arrowDisplay);
      var displayDots = typeOfSlideBtn(dotsDisplayType, _this.state.displayDots);

      _this.setState({
        arrowDisplay: arrowDisplay,
        displayDots: displayDots
      });

      if (event.type === 'mouseenter') {
        _this.stop();
      }

      if (event.type === 'mouseleave') {
        _this.play();
      }
    });

    _defineProperty(_assertThisInitialized(_this), "mouseOver", function () {
      var switchType = _this.props.switchType;

      if (switchType === 'glimmer') {
        _this.container.addEventListener('mousemove', _this.touchAreaToSlide, false);
      }
    });

    _defineProperty(_assertThisInitialized(_this), "getMousePos", function (event) {
      var e = event || window.event;
      var scrollX = document.documentElement.scrollLeft || document.body.scrollLeft;
      var scrollY = document.documentElement.scrollTop || document.body.scrollTop;
      var x = e.pageX || e.clientX + scrollX;
      var y = e.pageY || e.clientY + scrollY;
      return {
        x: x,
        y: y
      };
    });

    _defineProperty(_assertThisInitialized(_this), "touchAreaToSlide", function (e) {
      // 获取当前鼠标点击的横坐标
      var x = _this.getMousePos(e).x; // 减去父容器的横坐标位置，得到点击位置相对于父容器的区域


      var offsetX = x - getElementLeft(_this.container);

      switch (_this.onJudgeArea(offsetX)) {
        case 'left':
          if (_this.state.activeIndex !== 1) {
            _this.container.style.cursor = 'url("http://static.ws.126.net/utf8/bjzw/img/leftArrow.png") 16 30, auto';
          } else {
            _this.container.style.cursor = 'default';
          }

          break;

        case 'center':
          _this.container.style.cursor = 'zoom-out';
          break;

        case 'right':
          if (_this.state.activeIndex !== _this.props.imgList.length) {
            _this.container.style.cursor = 'url("http://static.ws.126.net/utf8/bjzw/img/rightArrow.png") 16 30, auto';
          } else {
            _this.container.style.cursor = 'default';
          }

          break;

        default:
      }
    });

    _defineProperty(_assertThisInitialized(_this), "play", function () {
      var imgWidth = _this.props.imgWidth;
      var _this$props3 = _this.props,
          _this$props3$interval = _this$props3.interval,
          interval = _this$props3$interval === void 0 ? 3000 : _this$props3$interval,
          _this$props3$width = _this$props3.width,
          width = _this$props3$width === void 0 ? imgWidth : _this$props3$width;
      _this.timer = setTimeout(function () {
        _this.arrowClick(width, true);

        _this.play();
      }, interval);
    });

    _defineProperty(_assertThisInitialized(_this), "stop", function () {
      clearTimeout(_this.timer);
    });

    _defineProperty(_assertThisInitialized(_this), "dotClick", function (currentIndex, type) {
      var _this$props$switchTyp = _this.props.switchType,
          switchType = _this$props$switchTyp === void 0 ? 'custom' : _this$props$switchTyp;

      if (_this.animated) {
        return;
      }

      _this.myIndex = parseInt(currentIndex, 10); // 得到需要移动到的位置

      var next = _this.myIndex - _this.state.activeIndex > 0;

      switch (switchType) {
        // case 'slide':
        //     const offset = -imgWidth * (this.myIndex - this.state.activeIndex) // 判断出需要偏移的位移量
        //     this.animate(offset, next) // 去移动
        //     break
        case 'glimmer':
          break;

        case 'custom':
          _this.customAnimation(next, true, currentIndex);

          break;

        default:
          return;
      }

      _this.imgDotsSlide(_this.myIndex);

      _this.scrollToRightPosition(_this.carousel);
    });

    _defineProperty(_assertThisInitialized(_this), "handleGlimmerClick", function (e, item) {
      var onClick = _this.props.onClick;

      var x = _this.getMousePos(e).x;

      var offsetX = x - getElementLeft(_this.container);

      switch (_this.onJudgeArea(offsetX)) {
        case 'left':
          if (_this.state.activeIndex !== 1) {
            _this.dotClick(_this.state.activeIndex - 1);
          }

          break;

        case 'center':
          onClick(item);
          break;

        case 'right':
          if (_this.state.activeIndex !== _this.props.imgList.length) {
            _this.dotClick(_this.state.activeIndex + 1);
          }

          break;

        default:
          return;
      }

      _this.scrollToRightPosition(_this.carousel);
    });

    _defineProperty(_assertThisInitialized(_this), "scrollToRightPosition", function (element) {
      var y = _this.getElementTop(element) - document.documentElement.scrollTop || document.body.scrollTop;

      if (y < 0) {
        var _window = window,
            pageXOffset = _window.pageXOffset,
            scrollTo = _window.scrollTo;
        scrollTo(pageXOffset, _this.getElementTop(_this.carousel));
      }
    });

    _defineProperty(_assertThisInitialized(_this), "getElementTop", function (element) {
      var actualTop = element.offsetTop;
      var current = element.offsetParent;

      while (current !== null) {
        actualTop += current.offsetTop;
        current = current.offsetParent;
      }

      return actualTop;
    });

    _defineProperty(_assertThisInitialized(_this), "onJudgeArea", function (offsetX) {
      var imgWidth = _this.props.imgWidth;
      var _this$props$width2 = _this.props.width,
          width = _this$props$width2 === void 0 ? imgWidth : _this$props$width2;

      if (offsetX >= 0 && offsetX <= width / 4) {
        return 'left';
      }

      if (offsetX >= width / 4 && offsetX <= width / 4 * 3) {
        return 'center';
      }

      if (offsetX >= width / 4 * 3) {
        return 'right';
      }
    });

    _defineProperty(_assertThisInitialized(_this), "prefixBroswerHack", function (jsStyle) {
      var allStyle = [jsStyle];
      var prefixBroswer = ['Webkit', 'ms', 'O'];
      prefixBroswer.forEach(function (item) {
        allStyle.push(_defineProperty({}, item + Object.keys(jsStyle)[0].replace(/( |^)[a-z]/g, function (L) {
          return L.toUpperCase();
        }), Object.values(jsStyle)[0]));
      });
      return allStyle;
    });

    _defineProperty(_assertThisInitialized(_this), "customAnimation", function (next, isJump, currentIndex) {
      var _this$props4 = _this.props,
          imgWidth = _this$props4.imgWidth,
          imgHeight = _this$props4.imgHeight;
      var _this$props5 = _this.props,
          _this$props5$width = _this$props5.width,
          width = _this$props5$width === void 0 ? imgWidth : _this$props5$width,
          _this$props5$height = _this$props5.height,
          height = _this$props5$height === void 0 ? imgHeight : _this$props5$height,
          time = _this$props5.time;
      var _this$state2 = _this.state,
          activeIndex = _this$state2.activeIndex,
          len = _this$state2.len;
      var customInnerStyle = {
        width: (len + 2) * width,
        height: height
      };
      var animationTarget = activeIndex;
      _this.animated = true;

      if (activeIndex === 1) {
        if (next) {
          // 向右滚动到最后一幅
          animationTarget = len + 1;
        }
      } else if (activeIndex === len) {
        if (!next) {
          animationTarget = 0;
        }
      }

      if (isJump) {
        animationTarget = currentIndex;
      }

      Object.assign.apply(Object, [customInnerStyle].concat(_toConsumableArray(_this.prefixBroswerHack({
        transform: "translate3d(".concat(-animationTarget * width, "px, 0px, 0px)")
      })), _toConsumableArray(_this.prefixBroswerHack({
        transition: "transform ".concat(time, "s ease-in-out 0s")
      }))));

      _this.setState({
        customAnimationCss: customInnerStyle
      });
    });

    _defineProperty(_assertThisInitialized(_this), "stopTransition", function () {
      var _this$props6 = _this.props,
          imgWidth = _this$props6.imgWidth,
          imgHeight = _this$props6.imgHeight;
      var _this$props7 = _this.props,
          _this$props7$width = _this$props7.width,
          width = _this$props7$width === void 0 ? imgWidth : _this$props7$width,
          _this$props7$height = _this$props7.height,
          height = _this$props7$height === void 0 ? imgHeight : _this$props7$height;
      var _this$state3 = _this.state,
          activeIndex = _this$state3.activeIndex,
          len = _this$state3.len,
          next = _this$state3.next;
      _this.animated = false;

      if (activeIndex === 1 && next || activeIndex === len && !next) {
        var customInnerStyle = {
          width: (len + 2) * width,
          height: height
        };
        Object.assign.apply(Object, [customInnerStyle].concat(_toConsumableArray(_this.prefixBroswerHack({
          transform: "translate3d(".concat(-activeIndex * width, "px, 0px, 0px)")
        })), _toConsumableArray(_this.prefixBroswerHack({
          transition: "transform 0s ease-in-out 0s"
        }))));

        _this.setState({
          customAnimationCss: customInnerStyle
        });
      }
    });

    _this.index = 1;
    _this.animated = false;
    var _this$props8 = _this.props,
        _imgWidth = _this$props8.imgWidth,
        _imgHeight = _this$props8.imgHeight;

    var _this$props9 = _this.props,
        _this$props9$width = _this$props9.width,
        _width = _this$props9$width === void 0 ? _imgWidth : _this$props9$width,
        _this$props9$height = _this$props9.height,
        _height = _this$props9$height === void 0 ? _imgHeight : _this$props9$height,
        _this$props9$children = _this$props9.children,
        children = _this$props9$children === void 0 ? [] : _this$props9$children,
        autoPlay = _this$props9.autoPlay,
        _time = _this$props9.time;

    _this.state = {
      activeIndex: 1,
      // 当前显示的图片
      len: 0,
      autoPlay: autoPlay,
      arrowDisplay: false,
      customAnimationCss: Object.assign.apply(Object, [{
        width: (children.length + 2) * _width,
        height: _height
      }].concat(_toConsumableArray(_this.prefixBroswerHack({
        transform: "translate3d(".concat(-_width, "px, 0px, 0px)")
      })), _toConsumableArray(_this.prefixBroswerHack({
        transition: "transform ".concat(_time, "s ease-in-out 0s")
      }))))
    };
    return _this;
  }

  _createClass(Carousel, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      var _this$props10 = this.props,
          imgList = _this$props10.imgList,
          switchType = _this$props10.switchType,
          children = _this$props10.children,
          autoPlay = _this$props10.autoPlay;

      if (switchType === 'custom') {
        this.carousel.addEventListener('mouseenter', this.handleMouseListener, false);
        this.carousel.addEventListener('mouseleave', this.handleMouseListener, false);
        this.customInner.addEventListener('transitionend', this.stopTransition, false);
      }

      this.setState({
        len: switchType === 'custom' ? children.length : imgList.length,
        activeIndex: this.props.activeIndex
      });
      switchType === 'glimmer' && this.mouseOver();
      autoPlay && this.play();
    }
  }, {
    key: "componentWillReceiveProps",
    value: function componentWillReceiveProps() {
      var _this2 = this;

      if (!this.state.autoPlay) {
        var _this$props11 = this.props,
            imgList = _this$props11.imgList,
            autoPlay = _this$props11.autoPlay,
            switchType = _this$props11.switchType,
            children = _this$props11.children;
        this.setState({
          len: switchType === 'custom' ? children.length : imgList.length,
          autoPlay: autoPlay
        }, function () {
          _this2.state.autoPlay && _this2.play();
        });
      }
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      if (this.state.autoPlay) {
        this.stop();
        clearTimeout(this.timer);
      }

      this.carousel.removeEventListener('mouseenter', this.handleMouseListener, false);
      this.carousel.removeEventListener('mouseleave', this.handleMouseListener, false);

      if (this.props.switchType === 'glimmer') {
        this.container.removeEventListener('mousemove', this.touchAreaToSlide);
      }
    } // 箭头点击

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

      var _this$props12 = this.props,
          imgWidth = _this$props12.imgWidth,
          imgHeight = _this$props12.imgHeight;
      var _this$props13 = this.props,
          prefixCls = _this$props13.prefixCls,
          imgList = _this$props13.imgList,
          _this$props13$width = _this$props13.width,
          width = _this$props13$width === void 0 ? imgWidth : _this$props13$width,
          _this$props13$height = _this$props13.height,
          height = _this$props13$height === void 0 ? imgHeight : _this$props13$height,
          orientation = _this$props13.orientation,
          switchType = _this$props13.switchType,
          imgIndexDisplay = _this$props13.imgIndexDisplay,
          arrowDisplayType = _this$props13.arrowDisplayType,
          children = _this$props13.children;
      var _this$state4 = this.state,
          arrowDisplay = _this$state4.arrowDisplay,
          activeIndex = _this$state4.activeIndex,
          displayDots = _this$state4.displayDots,
          smallIndexLeft = _this$state4.smallIndexLeft,
          len = _this$state4.len,
          customAnimationCss = _this$state4.customAnimationCss;
      var arrowStyle = {
        display: 'none'
      };

      if (arrowDisplay) {
        arrowStyle.display = 'block';
      }

      var smallImgList = this.props.smallImgList || imgList;
      smallImgList = smallImgList.length ? smallImgList : children ? easyToMap(children.length) : [];
      var DotsPorps = {
        smallImgList: smallImgList,
        len: len,
        orientation: orientation,
        activeIndex: activeIndex,
        handleClick: this.dotClick,
        display: displayDots
      };
      var smallImgIndexProps = {};
      var warpCarouselStyle = {};
      var carouselStyle = {};
      var containerStyle = {};
      var displayArrow = false;
      var childrenLen;

      switch (switchType) {
        case 'glimmer':
          carouselStyle = {
            width: "".concat(width, "px"),
            overflow: 'hidden',
            display: 'flex',
            flexDirection: 'column',
            justifyContent: 'center'
          };
          containerStyle = {
            width: "".concat(width, "px"),
            overflow: 'initial',
            borderRadius: 0
          };
          smallImgIndexProps = {
            smallImgList: smallImgList,
            len: len,
            orientation: orientation,
            activeIndex: activeIndex,
            handleClick: this.dotClick,
            display: imgIndexDisplay,
            left: smallIndexLeft,
            imgContainerWidth: width
          };
          break;

        case 'custom':
          warpCarouselStyle = {
            height: imgIndexDisplay ? "".concat(height + 65, "px") : "".concat(height, "px")
          };
          carouselStyle = {
            width: "".concat(width, "px"),
            height: "".concat(height, "px")
          };
          containerStyle = {
            width: "".concat(width, "px"),
            height: "".concat(height, "px")
          };
          displayArrow = len !== 1 && arrowDisplayType !== 'hidden';
          childrenLen = children.length;
          break;

        default:
          break;
      }

      return React.createElement("div", {
        className: prefixCls,
        style: warpCarouselStyle
      }, React.createElement("div", {
        className: "".concat(prefixCls, "-warp"),
        ref: function ref(carousel) {
          return _this3.carousel = carousel;
        },
        style: carouselStyle
      }, React.createElement("div", {
        className: "container",
        ref: function ref(container) {
          return _this3.container = container;
        },
        style: containerStyle
      }, switchType === 'glimmer' && React.createElement("div", {
        className: "container-glimmer",
        style: {
          width: '640px',
          overflow: 'hidden'
        }
      }, React.createElement("div", {
        className: "container-glimmer-li",
        onClick: function onClick(e) {
          return _this3.handleGlimmerClick(e, imgList[activeIndex - 1]);
        }
      }, React.createElement("img", {
        src: imgList[activeIndex - 1].img,
        alt: imgList[activeIndex - 1].alt
      }))), switchType === 'custom' && React.createElement("div", {
        className: "container-custom",
        style: carouselStyle
      }, React.createElement("div", {
        className: "container-custom-inner",
        ref: function ref(e) {
          _this3.customInner = e;
        },
        style: customAnimationCss
      }, len && React.cloneElement(children[childrenLen - 1], {
        className: "".concat(children[childrenLen - 1].props.className, " custom-slide-slick"),
        style: {
          width: width,
          height: height
        }
      }), Children.map(children, function (item) {
        var reactCloneElement = React.cloneElement(item, {
          className: "".concat(children[0].props.className, " custom-slide-slick"),
          style: {
            width: width,
            height: height
          }
        });
        return reactCloneElement;
      }), len && React.cloneElement(children[0], {
        className: "".concat(children[0].props.className, " custom-slide-slick"),
        style: {
          width: width,
          height: height
        }
      }))), switchType === 'custom' && React.createElement(Dots, DotsPorps)), displayArrow && React.createElement(ArrowBtn, {
        arrowDisplay: arrowDisplay,
        direction: "left-arrow",
        arrowClick: this.arrowClick,
        imgWidth: width
      }), displayArrow && React.createElement(ArrowBtn, {
        arrowDisplay: arrowDisplay,
        direction: "right-arrow",
        arrowClick: this.arrowClick,
        imgWidth: width
      }), React.createElement(SmallImgIndex, smallImgIndexProps)));
    }
  }]);

  return Carousel;
}(Component);

_defineProperty(Carousel, "propTypes", {
  /**
   * 轮播组件的宽度
   * */
  width: PropTypes.number,

  /**
   * 轮播组件的高度
   * */
  height: PropTypes.number,

  /**
   * @ignore
   * */
  imgWidth: PropTypes.number,

  /**
   * @ignore
   * */
  imgHeight: PropTypes.number,

  /**
   * 自动切换轮播的时间
   * */
  interval: PropTypes.number,

  /**
   * 是否自动播放
   * */
  autoPlay: PropTypes.bool,

  /**
   * dot显示的方式：
   * display(一直显示),
   * hover(hover时候显示),
   * hidden(一直隐藏)
   * */
  dotsDisplayType: PropTypes.oneOf(['display', 'hover', 'hidden']),

  /**
   * pre next按钮显示的方式：
   * display(一直显示),
   * hover(hover时候显示),
   * hidden(一直隐藏)
   * */
  arrowDisplayType: PropTypes.oneOf(['display', 'hover', 'hidden']),

  /**
   * 类名前缀
   * */
  prefixCls: PropTypes.string,

  /**
   * @ignore
   * */
  switchType: PropTypes.string,

  /**
   * @ignore
   * */
  smallImgWidth: PropTypes.number,

  /**
   * @ignore
   * */
  imgGap: PropTypes.number,

  /**
   * @ignore
   * */
  activeIndex: PropTypes.number,

  /**
   * @ignore
   * */
  imgList: PropTypes.array,

  /**
   * 轮播组件渲染的自定义子元素
   * */
  children: PropTypes.node,

  /**
   * 子元素过渡的时间
   * */
  time: PropTypes.number
});

_defineProperty(Carousel, "defaultProps", {
  prefixCls: 'ne-carousel',
  imgList: [],
  time: 0.6,
  interval: 3000,
  // 切换间隔时间
  autoPlay: false,
  // 是否自动播放
  switchType: 'custom',
  // 切换轮播的类型
  dotsDisplayType: 'hover',
  // 底部圆点显示的类型
  arrowDisplayType: 'hover',
  // 左右箭头切换的类型
  smallImgWidth: 64,
  // 类型为glimmer时候的小图尺寸
  imgGap: 8,
  // 类型为glimmer时候的图片间隔
  activeIndex: 1 // 当前活动的图片

});

export default Carousel;