import _defineProperty from 'babel-runtime/helpers/defineProperty';
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/pagination/Pagination.jsx';
/**
 * Pagination.jsx
 *
 * @Author: jruif
 * @Date: 2017/7/14 上午11:44
 */

import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import Button from '../button';
import Input from '../input';
import scrollTo from '../util/scrollTo';
import Select from '../select';
import omit from '../util/omit';

/**
 * Pagination
 * */

var Pagination = function (_React$Component) {
    _inherits(Pagination, _React$Component);

    function Pagination(props, context) {
        var _this2 = this;

        _classCallCheck(this, Pagination);

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

        _this.onSelectPageSize = function (e, value) {
            var onChangePageSize = _this.props.onChangePageSize;

            _this.scrollToTop();
            if (onChangePageSize) onChangePageSize(value);
        };

        _this.getTotalPage = function () {
            var _this$props = _this.props,
                total = _this$props.total,
                pageSize = _this$props.pageSize,
                totalPage = _this$props.totalPage;

            return totalPage || Math.ceil(total / pageSize);
        };

        _this.onInputPage = function (e) {
            var onChangePage = _this.props.onChangePage;

            var target = e.target;
            var value = Number(target.value);
            var totalPage = _this.getTotalPage();
            var validValue = isNaN(value) || value < 1 ? '' : value > totalPage ? totalPage : value;
            _this.setState({
                inputPage: validValue
            });
            if (onChangePage) onChangePage(validValue);
        };

        _this.quickJumpPage = function () {
            var inputPage = _this.state.inputPage;

            if (inputPage > 0 && inputPage <= _this.getTotalPage()) {
                _this.jumpPage(inputPage);
            }
        };

        _this.jumpPage = function (next) {
            var onChange = _this.props.onChange;

            _this.setState({
                current: next
            });
            _this.scrollToTop(function () {
                onChange(next);
            });
        };

        _this.scrollToTop = function (callback) {
            var _this$props2 = _this.props,
                scrollToTop = _this$props2.scrollToTop,
                scrollTime = _this$props2.scrollTime,
                tweenName = _this$props2.tweenName,
                scrollToValue = _this$props2.scrollToValue;

            if (scrollToTop) {
                var _window = window,
                    pageYOffset = _window.pageYOffset;

                scrollTo(pageYOffset, scrollToValue, scrollTime, tweenName, function () {
                    callback && callback();
                });
            } else {
                callback && callback();
            }
        };

        _this.prev = function () {
            var page = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1;

            if (_this.hasPrev()) {
                _this.jumpPage(_this.state.current - page);
            }
        };

        _this.next = function () {
            var page = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1;

            if (_this.hasNext(page)) {
                _this.jumpPage(_this.state.current + page);
            }
        };

        _this.hasPrev = function () {
            return _this.state.current > 1;
        };

        _this.hasNext = function () {
            return _this.calcPage() - _this.state.current > 0;
        };

        _this.calcPage = function (p) {
            var _pageSize = p;
            var _this$props3 = _this.props,
                total = _this$props3.total,
                totalPage = _this$props3.totalPage,
                pageSize = _this$props3.pageSize;

            var _totalPage = 0;
            // 有默认值
            if (_pageSize === void 0) {
                _pageSize = pageSize;
            }
            if (totalPage === 0) {
                if (total !== 0) {
                    _totalPage = Math.ceil(total / _pageSize);
                }
            } else {
                _totalPage = totalPage;
            }
            return _totalPage;
        };

        _this.renderPreBtn = function (index) {
            var _classNames;

            var _this$props4 = _this.props,
                btnProp = _this$props4.btnProp,
                prefixCls = _this$props4.prefixCls,
                isCompact = _this$props4.isCompact,
                size = _this$props4.size;

            var current = _this.state.current;
            var isCurrent = index === current;
            return React.createElement(
                Button,
                Object.assign({
                    hollow: isCompact,
                    size: size
                }, omit(btnProp, ['className']), {
                    className: classNames((_classNames = {}, _defineProperty(_classNames, '' + btnProp.className, btnProp.className), _defineProperty(_classNames, prefixCls + '-btn-active', isCurrent), _classNames)),
                    onClick: function onClick() {
                        return _this.jumpPage(index);
                    },
                    type: isCurrent ? 'primary' : 'secondary', __source: {
                        fileName: _jsxFileName,
                        lineNumber: 300
                    },
                    __self: _this2
                }),
                index
            );
        };

        _this.state = {
            current: props.current,
            inputPage: ''
        };
        return _this;
    }

    _createClass(Pagination, [{
        key: 'componentWillReceiveProps',
        value: function componentWillReceiveProps(nextProps) {
            if ('current' in nextProps) {
                this.setState({
                    current: nextProps.current
                });
            }

            if ('pageSize' in nextProps) {
                var newState = {};
                var current = this.state.current;
                var newCurrent = this.calcPage(nextProps.pageSize);
                current = current > newCurrent ? newCurrent : current;
                if (!('current' in nextProps)) {
                    newState.current = current;
                }
                newState.pageSize = nextProps.pageSize;
                newState.totalPage = nextProps.totalPage;
                this.setState(newState);
            }
        }
    }, {
        key: 'render',
        value: function render() {
            var _this3 = this,
                _classNames2;

            var _props = this.props,
                total = _props.total,
                totalPage = _props.totalPage,
                pageSize = _props.pageSize,
                showTotal = _props.showTotal,
                showQuickJump = _props.showQuickJump,
                showSelectPageSize = _props.showSelectPageSize,
                prefixCls = _props.prefixCls,
                showWhenOnlyOne = _props.showWhenOnlyOne,
                size = _props.size,
                btnProp = _props.btnProp,
                prev = _props.prev,
                next = _props.next,
                className = _props.className,
                showPer = _props.showPer,
                isCompact = _props.isCompact,
                pageSizeOptions = _props.pageSizeOptions;


            btnProp.size = btnProp.size || size;

            var elementPage = [];

            totalPage = Number(totalPage);
            total = Number(total);
            pageSize = Number(pageSize);

            var current = this.state.current;

            if (totalPage === 0 && total === 0) {
                return null;
            } else if (total !== 0) {
                //默认值为0
                totalPage = Math.ceil(total / pageSize);
            }
            if (totalPage < 9) {
                for (var i = 0; i < totalPage; i++) {
                    elementPage.push(React.createElement(
                        'li',
                        { key: 'page-' + i, __source: {
                                fileName: _jsxFileName,
                                lineNumber: 353
                            },
                            __self: this
                        },
                        this.renderPreBtn(i + 1)
                    ));
                }
            } else {
                var left = Math.max(1, current - 2);
                var right = Math.min(current + 2, totalPage);
                if (current - 1 <= 2) {
                    right = 1 + 4;
                }

                if (totalPage - current <= 2) {
                    left = totalPage - 4;
                }

                for (var _i = left; _i <= right; _i++) {
                    elementPage.push(React.createElement(
                        'li',
                        { key: 'page-' + _i, __source: {
                                fileName: _jsxFileName,
                                lineNumber: 367
                            },
                            __self: this
                        },
                        this.renderPreBtn(_i)
                    ));
                }
                if (current - 1 >= 4) {
                    elementPage.unshift(React.createElement(
                        'li',
                        { key: 'ellipsis-1', __source: {
                                fileName: _jsxFileName,
                                lineNumber: 371
                            },
                            __self: this
                        },
                        React.createElement(Button, Object.assign({
                            hollow: isCompact
                        }, omit(btnProp, ['className']), {
                            className: (btnProp.className || '') + ' ellipsis-1',
                            icon: 'dot-3',
                            onClick: function onClick() {
                                return _this3.prev(4);
                            },
                            __source: {
                                fileName: _jsxFileName,
                                lineNumber: 372
                            },
                            __self: this
                        }))
                    ));
                }
                if (totalPage - current >= 4) {
                    elementPage.push(React.createElement(
                        'li',
                        { key: 'ellipsis-2', __source: {
                                fileName: _jsxFileName,
                                lineNumber: 384
                            },
                            __self: this
                        },
                        React.createElement(Button, Object.assign({
                            hollow: isCompact
                        }, omit(btnProp, ['className']), {
                            className: (btnProp.className || '') + ' ellipsis-2',
                            icon: 'dot-3',
                            onClick: function onClick() {
                                return _this3.next(4);
                            },
                            __source: {
                                fileName: _jsxFileName,
                                lineNumber: 385
                            },
                            __self: this
                        }))
                    ));
                }
                if (left !== 1) {
                    elementPage.unshift(React.createElement(
                        'li',
                        { key: 'page-first', __source: {
                                fileName: _jsxFileName,
                                lineNumber: 396
                            },
                            __self: this
                        },
                        this.renderPreBtn(1)
                    ));
                }
                if (right !== totalPage) {
                    elementPage.push(React.createElement(
                        'li',
                        { key: 'page-last', __source: {
                                fileName: _jsxFileName,
                                lineNumber: 399
                            },
                            __self: this
                        },
                        this.renderPreBtn(totalPage)
                    ));
                }
            }

            var classes = classNames(prefixCls, className, (_classNames2 = {}, _defineProperty(_classNames2, prefixCls + '-compact', isCompact), _defineProperty(_classNames2, prefixCls + '-' + btnProp.size, btnProp.size), _classNames2));

            return this.calcPage() <= 1 && !showWhenOnlyOne ? null : React.createElement(
                'ul',
                { className: classes, ref: 'pagination', __source: {
                        fileName: _jsxFileName,
                        lineNumber: 409
                    },
                    __self: this
                },
                React.createElement(
                    'li',
                    { className: 'pagination-previous', __source: {
                            fileName: _jsxFileName,
                            lineNumber: 410
                        },
                        __self: this
                    },
                    React.createElement(
                        Button,
                        Object.assign({ hollow: isCompact }, btnProp, { onClick: function onClick() {
                                return _this3.prev(1);
                            }, disabled: !this.hasPrev(), __source: {
                                fileName: _jsxFileName,
                                lineNumber: 411
                            },
                            __self: this
                        }),
                        prev
                    )
                ),
                showPer ? elementPage : null,
                React.createElement(
                    'li',
                    { className: 'pagination-next', __source: {
                            fileName: _jsxFileName,
                            lineNumber: 416
                        },
                        __self: this
                    },
                    React.createElement(
                        Button,
                        Object.assign({ hollow: isCompact }, btnProp, { onClick: function onClick() {
                                return _this3.next(1);
                            }, disabled: !this.hasNext(), __source: {
                                fileName: _jsxFileName,
                                lineNumber: 417
                            },
                            __self: this
                        }),
                        next
                    )
                ),
                showSelectPageSize && React.createElement(
                    'li',
                    {
                        __source: {
                            fileName: _jsxFileName,
                            lineNumber: 422
                        },
                        __self: this
                    },
                    React.createElement(Select, {
                        className: prefixCls + '-select',
                        defaultValue: pageSize,
                        onChange: this.onSelectPageSize,
                        size: btnProp.size,
                        options: pageSizeOptions.map(function (val) {
                            return {
                                label: val + '条/页',
                                value: val
                            };
                        }),
                        __source: {
                            fileName: _jsxFileName,
                            lineNumber: 423
                        },
                        __self: this
                    })
                ),
                !!total && showTotal && React.createElement(
                    'li',
                    {
                        __source: {
                            fileName: _jsxFileName,
                            lineNumber: 437
                        },
                        __self: this
                    },
                    React.createElement(
                        'span',
                        { className: 'show-total', __source: {
                                fileName: _jsxFileName,
                                lineNumber: 438
                            },
                            __self: this
                        },
                        '\u5171 ',
                        total,
                        ' \u6761'
                    )
                ),
                showQuickJump && React.createElement(
                    'li',
                    { className: 'pagination-quick', __source: {
                            fileName: _jsxFileName,
                            lineNumber: 442
                        },
                        __self: this
                    },
                    '\u7B2C',
                    ' ',
                    React.createElement(Input, {
                        className: prefixCls + '-input',
                        type: 'number',
                        onChange: this.onInputPage,
                        value: this.state.inputPage,
                        size: btnProp.size,
                        __source: {
                            fileName: _jsxFileName,
                            lineNumber: 444
                        },
                        __self: this
                    }),
                    ' ',
                    '\u9875',
                    ' ',
                    React.createElement(
                        Button,
                        Object.assign({}, btnProp, { onClick: this.quickJumpPage, __source: {
                                fileName: _jsxFileName,
                                lineNumber: 452
                            },
                            __self: this
                        }),
                        '\u8DF3\u8F6C'
                    )
                )
            );
        }
    }]);

    return Pagination;
}(React.Component);

Pagination.propTypes = {
    /**
     * 数据总数，和totalPage二选一
     * */
    total: PropTypes.number,
    /**
     * 页数总数，和total二选一
     * */
    totalPage: PropTypes.number,
    /**
     * 每页大小
     * */
    pageSize: PropTypes.number,
    /**
     * 当前页码
     * */
    current: PropTypes.number,
    /**
     * 分页数组，例如：[10, 20, 40]
     * */
    pageSizeOptions: PropTypes.array,
    /**
     * 是否显示快速跳转
     * */
    showQuickJump: PropTypes.bool,
    /**
     * 是否显示每一页，为false的时候，只显示上下翻页按钮
     * */
    showPer: PropTypes.bool,
    /**
     * 是否数据总条数
     * */
    showTotal: PropTypes.bool,
    /**
     * 当只有一页的时候是否显示分页
     * */
    showWhenOnlyOne: PropTypes.bool,
    /**
     * 是否显示选择分页选择器
     * */
    showSelectPageSize: PropTypes.bool,
    /**
     * 是否显示为紧凑形式
     * */
    isCompact: PropTypes.bool,
    /**
     * 跳转页面，返回目标页码
     * */
    onChange: PropTypes.func,
    /**
     * 跳转输入框的change回调
     * */
    onChangePage: PropTypes.func,
    /**
     * 改变分页大小，返回改变后的数值
     * */
    onChangePageSize: PropTypes.func,
    /**
     * 是否跳到页面顶部
     * */
    scrollToTop: PropTypes.bool,
    /**
     * 缓动动画名，参考：http://easings.net/zh-cn
     'linear',
     'easeInQuad',
     'easeOutQuad',
     'easeInOutQuad',
     'easeInCubic',
     'easeOutCubic',
     'easeInOutCubic',
     'easeInQuart',
     'easeOutQuart',
     'easeInOutQuart',
     'easeInQuint',
     'easeOutQuint',
     'easeInOutQuint',
     'easeInSine',
     'easeOutSine',
     'easeInOutSine',
     'easeInExpo',
     'easeOutExpo',
     'easeInOutExpo',
     'easeInCirc',
     'easeOutCirc',
     'easeInOutCirc',
     'easeInElastic',
     'easeOutElastic',
     'easeInOutElastic',
     'easeInBack',
     'easeOutBack',
     'easeInOutBack',
     'easeInBounce',
     'easeOutBounce',
     'easeInOutBounce'
     * */
    tweenName: PropTypes.string,
    /**
     * 滚动时间，单位是ms
     * */
    scrollTime: PropTypes.number, // 800秒
    /**
     * 滚动到某一点坐标
     * */
    scrollToValue: PropTypes.number,
    /**
     * 分页中所有按钮的属性，同Button组件
     * */
    btnProp: PropTypes.object,
    /**
     * 优先级低于btnProp.size
     * */
    size: PropTypes.oneOf(['small', 'medium', 'large']),
    /**
     * 前一页按钮
     * */
    prev: PropTypes.oneOfType([PropTypes.string, PropTypes.element]),
    /**
     * 后一页按钮
     * */
    next: PropTypes.oneOfType([PropTypes.string, PropTypes.element]),
    /**
     * 组件前缀，可用来重置样式
     * */
    prefixCls: PropTypes.string,
    /**
     * 分页样式类
     * */
    className: PropTypes.string
};
Pagination.defaultProps = {
    total: 0,
    totalPage: 0,
    pageSize: 10,
    current: 1,
    showPer: true,
    isCompact: false,
    showQuickJump: false,
    showTotal: false,
    showSelectPageSize: false,
    showWhenOnlyOne: false,
    prefixCls: 'ne-pagination',
    scrollToTop: true,
    scrollTime: 800,
    scrollToValue: 0,
    tweenName: 'easeOutQuint',
    size: 'medium',
    btnProp: {},
    prev: '上一页',
    next: '下一页',
    pageSizeOptions: [10, 20, 50, 100],
    onChange: function onChange(next) {
        return next;
    }
};


export default Pagination;