import _defineProperty from 'babel-runtime/helpers/defineProperty';
import _toConsumableArray from 'babel-runtime/helpers/toConsumableArray';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _createClass from 'babel-runtime/helpers/createClass';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
var _jsxFileName = 'src/carousel/Carousel.jsx';
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';
// import './carousel.scss';

var Carousel = function (_Component) {
    _inherits(Carousel, _Component);

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

        var _this = _possibleConstructorReturn(this, (Carousel.__proto__ || Object.getPrototypeOf(Carousel)).call(this, props));

        _initialiseProps.call(_this);

        _this.index = 1;
        _this.animated = false;
        var _this$props = _this.props,
            imgWidth = _this$props.imgWidth,
            imgHeight = _this$props.imgHeight;
        var _this$props2 = _this.props,
            _this$props2$width = _this$props2.width,
            width = _this$props2$width === undefined ? imgWidth : _this$props2$width,
            _this$props2$height = _this$props2.height,
            height = _this$props2$height === undefined ? imgHeight : _this$props2$height,
            _this$props2$children = _this$props2.children,
            children = _this$props2$children === undefined ? [] : _this$props2$children,
            autoPlay = _this$props2.autoPlay,
            time = _this$props2.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(' + -width + 'px, 0px, 0px)' })), _toConsumableArray(_this.prefixBroswerHack({ transition: 'transform ' + time + 's ease-in-out 0s' }))))
        };
        return _this;
    }

    _createClass(Carousel, [{
        key: 'componentDidMount',
        value: function componentDidMount() {
            var _props = this.props,
                imgList = _props.imgList,
                switchType = _props.switchType,
                children = _props.children,
                autoPlay = _props.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 _props2 = this.props,
                    imgList = _props2.imgList,
                    autoPlay = _props2.autoPlay,
                    switchType = _props2.switchType,
                    children = _props2.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);
            }
        }

        // 箭头点击


        // 轮播dots


        // 根据类型判断是否显示切换按钮


        // 得到鼠标的位置


        // glimmer点击的区域


        // glimmer的点击触发


        // 跳转到正确的位置


        // 得到目标元素的顶部


        // 判断区域


        // 为js里面的css加各个浏览器的前缀


        // 动画开启


        // 滑动停止时候的触发事件

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

            var _props3 = this.props,
                imgWidth = _props3.imgWidth,
                imgHeight = _props3.imgHeight;
            var _props4 = this.props,
                prefixCls = _props4.prefixCls,
                imgList = _props4.imgList,
                _props4$width = _props4.width,
                width = _props4$width === undefined ? imgWidth : _props4$width,
                _props4$height = _props4.height,
                height = _props4$height === undefined ? imgHeight : _props4$height,
                orientation = _props4.orientation,
                switchType = _props4.switchType,
                imgIndexDisplay = _props4.imgIndexDisplay,
                arrowDisplayType = _props4.arrowDisplayType,
                children = _props4.children;
            var _state = this.state,
                arrowDisplay = _state.arrowDisplay,
                activeIndex = _state.activeIndex,
                displayDots = _state.displayDots,
                smallIndexLeft = _state.smallIndexLeft,
                len = _state.len,
                customAnimationCss = _state.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 = void 0;
            switch (switchType) {
                case 'glimmer':
                    carouselStyle = {
                        width: width + 'px',
                        overflow: 'hidden',
                        display: 'flex',
                        flexDirection: 'column',
                        justifyContent: 'center'
                    };
                    containerStyle = {
                        width: 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 ? height + 65 + 'px' : height + 'px'
                    };
                    carouselStyle = {
                        width: width + 'px',
                        height: height + 'px'
                    };
                    containerStyle = {
                        width: width + 'px',
                        height: height + 'px'
                    };
                    displayArrow = len !== 1 && arrowDisplayType !== 'hidden';
                    childrenLen = children.length;
                    break;
                default:
                    break;
            }
            return React.createElement(
                'div',
                { className: prefixCls, style: warpCarouselStyle, __source: {
                        fileName: _jsxFileName,
                        lineNumber: 557
                    },
                    __self: this
                },
                React.createElement(
                    'div',
                    { className: prefixCls + '-warp', ref: function ref(carousel) {
                            return _this3.carousel = carousel;
                        }, style: carouselStyle, __source: {
                            fileName: _jsxFileName,
                            lineNumber: 558
                        },
                        __self: this
                    },
                    React.createElement(
                        'div',
                        { className: 'container', ref: function ref(container) {
                                return _this3.container = container;
                            }, style: containerStyle, __source: {
                                fileName: _jsxFileName,
                                lineNumber: 559
                            },
                            __self: this
                        },
                        switchType === 'glimmer' && React.createElement(
                            'div',
                            { className: 'container-glimmer', style: { width: '640px', overflow: 'hidden' }, __source: {
                                    fileName: _jsxFileName,
                                    lineNumber: 561
                                },
                                __self: this
                            },
                            React.createElement(
                                'div',
                                {
                                    className: 'container-glimmer-li',
                                    onClick: function onClick(e) {
                                        return _this3.handleGlimmerClick(e, imgList[activeIndex - 1]);
                                    }, __source: {
                                        fileName: _jsxFileName,
                                        lineNumber: 562
                                    },
                                    __self: this
                                },
                                React.createElement('img', { src: imgList[activeIndex - 1].img, alt: imgList[activeIndex - 1].alt, __source: {
                                        fileName: _jsxFileName,
                                        lineNumber: 565
                                    },
                                    __self: this
                                })
                            )
                        ),
                        switchType === 'custom' && React.createElement(
                            'div',
                            { className: 'container-custom', style: carouselStyle, __source: {
                                    fileName: _jsxFileName,
                                    lineNumber: 570
                                },
                                __self: this
                            },
                            React.createElement(
                                'div',
                                {
                                    className: 'container-custom-inner',
                                    ref: function ref(e) {
                                        _this3.customInner = e;
                                    },
                                    style: customAnimationCss, __source: {
                                        fileName: _jsxFileName,
                                        lineNumber: 571
                                    },
                                    __self: this
                                },
                                len && React.cloneElement(children[childrenLen - 1], {
                                    className: children[childrenLen - 1].props.className + ' custom-slide-slick',
                                    style: { width: width, height: height }
                                }),
                                Children.map(children, function (item) {
                                    var reactCloneElement = React.cloneElement(item, {
                                        className: children[0].props.className + ' custom-slide-slick',
                                        style: { width: width, height: height }
                                    });
                                    return reactCloneElement;
                                }),
                                len && React.cloneElement(children[0], {
                                    className: children[0].props.className + ' custom-slide-slick',
                                    style: { width: width, height: height }
                                })
                            )
                        ),
                        switchType === 'custom' && React.createElement(Dots, Object.assign({}, DotsPorps, {
                            __source: {
                                fileName: _jsxFileName,
                                lineNumber: 598
                            },
                            __self: this
                        }))
                    ),
                    displayArrow && React.createElement(ArrowBtn, {
                        arrowDisplay: arrowDisplay,
                        direction: 'left-arrow',
                        arrowClick: this.arrowClick,
                        imgWidth: width,
                        __source: {
                            fileName: _jsxFileName,
                            lineNumber: 601
                        },
                        __self: this
                    }),
                    displayArrow && React.createElement(ArrowBtn, {
                        arrowDisplay: arrowDisplay,
                        direction: 'right-arrow',
                        arrowClick: this.arrowClick,
                        imgWidth: width,
                        __source: {
                            fileName: _jsxFileName,
                            lineNumber: 609
                        },
                        __self: this
                    }),
                    React.createElement(SmallImgIndex, Object.assign({}, smallImgIndexProps, {
                        __source: {
                            fileName: _jsxFileName,
                            lineNumber: 616
                        },
                        __self: this
                    }))
                )
            );
        }
    }]);

    return Carousel;
}(Component);

Carousel.propTypes = {
    /**
     * 轮播组件的宽度
     * */
    width: PropTypes.number.isRequired,
    /**
     * 轮播组件的高度
     * */
    height: PropTypes.number.isRequired,
    /**
     * @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.isRequired,
    /**
     * 子元素过渡的时间
     * */
    time: PropTypes.number
};
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 };

var _initialiseProps = function _initialiseProps() {
    var _this4 = this;

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

        if (_this4.animated) {
            return;
        }
        // 图片目前已经到最后一张,则移动到第一张
        var targetIndex = void 0;
        var _state2 = _this4.state,
            len = _state2.len,
            activeIndex = _state2.activeIndex;

        if (nextBool) {
            if (activeIndex === len) {
                targetIndex = 1;
            } else {
                targetIndex = activeIndex + 1;
            }
        } else {
            if (activeIndex === 1) {
                targetIndex = len;
            } else {
                targetIndex = activeIndex - 1;
            }
        }
        _this4.setState({
            activeIndex: targetIndex,
            next: nextBool
        });
        if (switchType === 'custom') {
            _this4.customAnimation(nextBool);
        }
        _this4.customAnimation(nextBool);
        _this4.imgDotsSlide(targetIndex);
    };

    this.imgDotsSlide = function (currentIndex) {
        var imgWidth = _this4.props.imgWidth;
        var _props5 = _this4.props,
            smallImgWidth = _props5.smallImgWidth,
            _props5$width = _props5.width,
            width = _props5$width === undefined ? imgWidth : _props5$width,
            imgGap = _props5.imgGap;

        var len = _this4.state.len;
        _this4.myIndex = parseInt(currentIndex, 10); // 得到需要移动到的位置
        var distance = ((smallImgWidth + imgGap) * len - width) / len; // 单位距离
        var transformX = distance * (0 - _this4.myIndex);
        if (_this4.myIndex <= 3) {
            transformX = 0;
        } else if (_this4.myIndex >= len - 3) {
            transformX = -distance * len;
        }
        if (len * smallImgWidth + (len - 1) * imgGap <= width) {
            _this4.setState({
                activeIndex: _this4.myIndex
            });
            return;
        }
        _this4.setState({
            smallIndexLeft: transformX,
            activeIndex: _this4.myIndex
        });
    };

    this.handleMouseListener = function (event) {
        var _props6 = _this4.props,
            dotsDisplayType = _props6.dotsDisplayType,
            arrowDisplayType = _props6.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, _this4.state.arrowDisplay);
        var displayDots = typeOfSlideBtn(dotsDisplayType, _this4.state.displayDots);
        _this4.setState({
            arrowDisplay: arrowDisplay,
            displayDots: displayDots
        });
        if (event.type === 'mouseenter') {
            _this4.stop();
        }
        if (event.type === 'mouseleave') {
            _this4.play();
        }
    };

    this.mouseOver = function () {
        var switchType = _this4.props.switchType;

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

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

    this.touchAreaToSlide = function (e) {
        // 获取当前鼠标点击的横坐标
        var x = _this4.getMousePos(e).x;
        // 减去父容器的横坐标位置，得到点击位置相对于父容器的区域
        var offsetX = x - getElementLeft(_this4.container);
        switch (_this4.onJudgeArea(offsetX)) {
            case 'left':
                if (_this4.state.activeIndex !== 1) {
                    _this4.container.style.cursor = 'url("http://static.ws.126.net/utf8/bjzw/img/leftArrow.png") 16 30, auto';
                } else {
                    _this4.container.style.cursor = 'default';
                }
                break;
            case 'center':
                _this4.container.style.cursor = 'zoom-out';
                break;
            case 'right':
                if (_this4.state.activeIndex !== _this4.props.imgList.length) {
                    _this4.container.style.cursor = 'url("http://static.ws.126.net/utf8/bjzw/img/rightArrow.png") 16 30, auto';
                } else {
                    _this4.container.style.cursor = 'default';
                }
                break;
            default:
                return;
        }
    };

    this.play = function () {
        var imgWidth = _this4.props.imgWidth;
        var _props7 = _this4.props,
            _props7$interval = _props7.interval,
            interval = _props7$interval === undefined ? 3000 : _props7$interval,
            _props7$width = _props7.width,
            width = _props7$width === undefined ? imgWidth : _props7$width;

        _this4.timer = setTimeout(function () {
            _this4.arrowClick(width, true);
            _this4.play();
        }, interval);
    };

    this.stop = function () {
        clearTimeout(_this4.timer);
    };

    this.dotClick = function (currentIndex, type) {
        var _props$switchType = _this4.props.switchType,
            switchType = _props$switchType === undefined ? 'custom' : _props$switchType;

        if (_this4.animated) {
            return;
        }
        _this4.myIndex = parseInt(currentIndex, 10); // 得到需要移动到的位置
        var next = _this4.myIndex - _this4.state.activeIndex > 0 ? true : false;
        switch (switchType) {
            // case 'slide':
            //     const offset = -imgWidth * (this.myIndex - this.state.activeIndex) // 判断出需要偏移的位移量
            //     this.animate(offset, next) // 去移动
            //     break
            case 'glimmer':
                break;
            case 'custom':
                _this4.customAnimation(next, true, currentIndex);
                break;
            default:
                return;
        }
        _this4.imgDotsSlide(_this4.myIndex);
        _this4.scrollToRightPosition(_this4.carousel);
    };

    this.handleGlimmerClick = function (e, item) {
        var onClick = _this4.props.onClick;

        var x = _this4.getMousePos(e).x;
        var offsetX = x - getElementLeft(_this4.container);
        switch (_this4.onJudgeArea(offsetX)) {
            case 'left':
                if (_this4.state.activeIndex !== 1) {
                    _this4.dotClick(_this4.state.activeIndex - 1);
                }
                break;
            case 'center':
                onClick(item);
                break;
            case 'right':
                if (_this4.state.activeIndex !== _this4.props.imgList.length) {
                    _this4.dotClick(_this4.state.activeIndex + 1);
                }
                break;
            default:
                return;
        }
        _this4.scrollToRightPosition(_this4.carousel);
    };

    this.scrollToRightPosition = function (element) {
        var y = _this4.getElementTop(element) - document.documentElement.scrollTop || document.body.scrollTop;
        if (y < 0) {
            var _window = window,
                pageXOffset = _window.pageXOffset,
                scrollTo = _window.scrollTo;

            scrollTo(pageXOffset, _this4.getElementTop(_this4.carousel));
        }
    };

    this.getElementTop = function (element) {
        var actualTop = element.offsetTop;
        var current = element.offsetParent;
        while (current !== null) {
            actualTop += current.offsetTop;
            current = current.offsetParent;
        }
        return actualTop;
    };

    this.onJudgeArea = function (offsetX) {
        var imgWidth = _this4.props.imgWidth;
        var _props$width = _this4.props.width,
            width = _props$width === undefined ? imgWidth : _props$width;

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

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

    this.customAnimation = function (next, isJump, currentIndex) {
        var _props8 = _this4.props,
            imgWidth = _props8.imgWidth,
            imgHeight = _props8.imgHeight;
        var _props9 = _this4.props,
            _props9$width = _props9.width,
            width = _props9$width === undefined ? imgWidth : _props9$width,
            _props9$height = _props9.height,
            height = _props9$height === undefined ? imgHeight : _props9$height,
            time = _props9.time;
        var _state3 = _this4.state,
            activeIndex = _state3.activeIndex,
            len = _state3.len;

        var customInnerStyle = {
            width: (len + 2) * width,
            height: height
        };
        var animationTarget = activeIndex;
        _this4.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(_this4.prefixBroswerHack({ transform: 'translate3d(' + -animationTarget * width + 'px, 0px, 0px)' })), _toConsumableArray(_this4.prefixBroswerHack({ transition: 'transform ' + time + 's ease-in-out 0s' }))));
        _this4.setState({
            customAnimationCss: customInnerStyle
        });
    };

    this.stopTransition = function () {
        var _props10 = _this4.props,
            imgWidth = _props10.imgWidth,
            imgHeight = _props10.imgHeight;
        var _props11 = _this4.props,
            _props11$width = _props11.width,
            width = _props11$width === undefined ? imgWidth : _props11$width,
            _props11$height = _props11.height,
            height = _props11$height === undefined ? imgHeight : _props11$height;
        var _state4 = _this4.state,
            activeIndex = _state4.activeIndex,
            len = _state4.len,
            next = _state4.next;

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

export default Carousel;