import _defineProperty from 'babel-runtime/helpers/defineProperty';
import _extends from 'babel-runtime/helpers/extends';
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/table/ItemTable.jsx',
    _this3 = this;

/**
 * fixTable.jsx
 *
 * @Author: apple
 * @Date: 2017/12/29 00:19
 */

import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import easyToMap from '../util/easyToMap';
import Icon from '../icon';
import TableHeader from './TableHeader';
import TableTbody from './TableTbody';
import ColGroup from './colGroup';
import TableHeaderRow from './TableHeaderRow';
import pubsub from '../util/observer';
import judgeBroswer from '../util/judgeBroswer';
import Checkbox from '../checkbox';

/**
 * @ignore
 * */

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

    function ItemTable(props, context) {
        _classCallCheck(this, ItemTable);

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

        _initialiseProps.call(_this);

        var _this$props = _this.props,
            dataSource = _this$props.dataSource,
            columns = _this$props.columns;

        var sortState = {};
        _this.rules = [];
        columns.forEach(function (item) {
            var sort = item.sort,
                key = item.key;

            if (sort) {
                sortState[key] = 'sort';
            }
        });
        _this.pubsubEvent = [];
        _this.state = {
            showExpandContent: [],
            checkboxArray: [],
            expandRowIds: [],
            data: dataSource,
            rowHeightArray: [],
            tdWidthArray: [],
            expandSumRow: 0,
            sortState: _extends({}, sortState)
        };
        return _this;
    }

    _createClass(ItemTable, [{
        key: 'componentDidMount',
        value: function componentDidMount() {
            var scroll = this.props.scroll;

            if (scroll.y) {
                this.scrollTbody.addEventListener('scroll', this.handleBodyScrollPosition, false);
                this.scrollTbody.addEventListener('mouseover', this.handleMouseOn, false);
            }
        }
    }, {
        key: 'componentWillReceiveProps',
        value: function componentWillReceiveProps(nextProps) {
            var _props = this.props,
                dataSource = _props.dataSource,
                scrollTop = _props.scrollTop,
                columns = _props.columns;

            if (JSON.stringify(dataSource).toString() !== JSON.stringify(nextProps.dataSource).toString()) {
                this.setState({
                    data: nextProps.dataSource,
                    expandRowIds: [],
                    checkboxArray: []
                });
            }

            if (JSON.stringify(columns) !== JSON.stringify(nextProps.columns)) {
                var sortState = {};
                nextProps.columns.forEach(function (item) {
                    var sort = item.sort,
                        key = item.key;

                    if (sort) {
                        sortState[key] = 'sort';
                    }
                });
                this.setState({
                    sortState: _extends({}, sortState)
                });
            }

            if (nextProps.scrollTop !== scrollTop) {
                this.scrollTbody.scrollTop = nextProps.scrollTop;
            }
        }
    }, {
        key: 'componentWillUnmount',
        value: function componentWillUnmount() {
            for (var item in this.pubsubEvent) {
                pubsub.unsubscribe(item);
            }
        }

        /**
         * 通用事件捕获，通过设置type来获取事件处理类型 todo 考虑支持无限加载
         * */

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

            var _props2 = this.props,
                position = _props2.position,
                onClickTh = _props2.onClickTh,
                styles = _props2.styles,
                textCenter = _props2.textCenter,
                prefixCls = _props2.prefixCls,
                hideTableTitle = _props2.hideTableTitle,
                stripe = _props2.stripe,
                columnsId = _props2.columnsId,
                shouldScroll = _props2.shouldScroll,
                scroll = _props2.scroll,
                theadRef = _props2.theadRef,
                tbodyRef = _props2.tbodyRef,
                tdWidthArray = _props2.tdWidthArray,
                warpWidth = _props2.warpWidth,
                rowHeightArray = _props2.rowHeightArray,
                scrollBarWidth = _props2.scrollBarWidth,
                allBorder = _props2.allBorder,
                warpBorder = _props2.warpBorder,
                handleMouseEnter = _props2.handleMouseEnter,
                handleMouseLeave = _props2.handleMouseLeave,
                checkbox = _props2.checkbox,
                baseHeaderHeight = _props2.baseHeaderHeight,
                expandOpt = _props2.expandOpt,
                mainTbody = _props2.mainTbody,
                pubsubEventString = _props2.pubsubEventString,
                isHover = _props2.isHover,
                noDataRender = _props2.noDataRender;

            var containerWidth = this.props.width;
            var _state = this.state,
                data = _state.data,
                expandRowIds = _state.expandRowIds,
                sortState = _state.sortState,
                tbodyScroll = _state.tbodyScroll;

            var renderColumns = this.initTableColumns();

            // 赋予固定栏整体宽度
            var innerTableWidth = 0;
            var renderStyle = _extends({}, styles);
            if (position === 'left' || position === 'right') {
                columnsId.forEach(function (id) {
                    if (position === 'left') {
                        if (checkbox) {
                            innerTableWidth += 50;
                        }
                        if (expandOpt && expandOpt.display) {
                            innerTableWidth += 50;
                        }
                    }
                    if (tdWidthArray[id]) {
                        innerTableWidth += tdWidthArray[id];
                    }
                });
                var width = innerTableWidth;
                if (position === 'right') {
                    width = scrollBarWidth && shouldScroll ? innerTableWidth + scrollBarWidth - 1 : innerTableWidth - 1;
                }
                renderStyle.width = width;
            } else {
                renderStyle.width = scrollBarWidth || shouldScroll ? containerWidth : containerWidth + scrollBarWidth;
            }
            var tableClassName = classNames(prefixCls + '-' + position + '-fixed', {
                'ne-table-exist-scroll-y': scroll.y && allBorder && !warpBorder
            });
            var theadClassName = classNames(prefixCls + '-thead', {
                'ne-table-border-none': position === 'right' || position === 'left'
            }, { 'display-none': hideTableTitle });
            var tbodyClassName = classNames(prefixCls + '-tbody', {
                'ne-table-border-none': position === 'right' || position === 'left'
            });
            var headerStyle = {
                overflowY: 'scroll',
                overflowX: position === 'main' && shouldScroll ? 'auto' : 'hidden'
            };
            if (scroll.y) {
                if (position === 'main') {
                    headerStyle.maxHeight = scroll.y;
                } else {
                    headerStyle.maxHeight = +scroll.y.split('px')[0] - 15;
                    if (!scrollBarWidth || !shouldScroll) {
                        headerStyle.maxHeight = +scroll.y.split('px')[0];
                    }
                }
            } else {
                headerStyle.overflowY = 'hidden';
            }

            var selfPrefixCls = prefixCls + '-item';
            var theadProps = {
                theadClassName: theadClassName,
                renderColumns: renderColumns,
                handleSetSort: this.handleSetSort,
                sortState: sortState,
                onClickTh: onClickTh,
                textCenter: textCenter,
                tdWidthArray: tdWidthArray,
                warpWidth: warpWidth,
                position: position,
                prefixCls: selfPrefixCls,
                scroll: tbodyScroll,
                tableHeaderRowRef: function tableHeaderRowRef(el) {
                    _this2.theadRow = el;
                },
                tableHeaderRef: function tableHeaderRef(el) {
                    theadRef && theadRef(el);
                    _this2.thead = el;
                },
                width: renderStyle.width,
                height: baseHeaderHeight,
                handleBodyScrollLeft: this.handleBodyScrollPosition
            };
            var tableHeaderRowProps = Object.assign({}, theadProps);
            var tbodyProps = {
                tbodyClassName: tbodyClassName,
                data: data,
                expandRowIds: expandRowIds,
                renderColumns: renderColumns,
                selfPrefixCls: selfPrefixCls,
                stripe: stripe,
                rowHeightArray: rowHeightArray,
                position: position,
                tableTbodyRef: function tableTbodyRef(el) {
                    tbodyRef && tbodyRef(el);
                    _this2.tbody = el;
                },
                handleBodyScrollLeft: this.handleBodyScrollPosition,
                rules: this.rules,
                handleMouseEnter: handleMouseEnter,
                handleMouseLeave: handleMouseLeave,
                mainTbody: mainTbody,
                pubsubEventString: pubsubEventString,
                expandOpt: expandOpt,
                checkbox: checkbox,
                isHover: isHover,
                noDataRender: noDataRender
            };
            return React.createElement(
                'div',
                { className: tableClassName, ref: this.getTableRef, __source: {
                        fileName: _jsxFileName,
                        lineNumber: 412
                    },
                    __self: this
                },
                scroll.y && React.createElement(TableHeader, Object.assign({}, theadProps, {
                    __source: {
                        fileName: _jsxFileName,
                        lineNumber: 413
                    },
                    __self: this
                })),
                React.createElement(
                    'div',
                    { className: selfPrefixCls + '-tbody', style: headerStyle, ref: this.handleInnerScrollEvent, __source: {
                            fileName: _jsxFileName,
                            lineNumber: 414
                        },
                        __self: this
                    },
                    React.createElement(
                        'table',
                        { style: renderStyle, __source: {
                                fileName: _jsxFileName,
                                lineNumber: 415
                            },
                            __self: this
                        },
                        React.createElement(ColGroup, { renderColumns: renderColumns, __source: {
                                fileName: _jsxFileName,
                                lineNumber: 416
                            },
                            __self: this
                        }),
                        !scroll.y && React.createElement(TableHeaderRow, Object.assign({}, tableHeaderRowProps, {
                            __source: {
                                fileName: _jsxFileName,
                                lineNumber: 417
                            },
                            __self: this
                        })),
                        React.createElement(TableTbody, Object.assign({}, tbodyProps, {
                            __source: {
                                fileName: _jsxFileName,
                                lineNumber: 418
                            },
                            __self: this
                        }))
                    )
                )
            );
        }
    }]);

    return ItemTable;
}(React.Component);

ItemTable.propTypes = {
    expandOpt: PropTypes.object,
    expandRender: PropTypes.func
};
ItemTable.defaultProps = {
    expandRender: function expandRender() {
        return React.createElement(
            'div',
            {
                __source: {
                    fileName: _jsxFileName,
                    lineNumber: 31
                },
                __self: _this3
            },
            '\u5C55\u5F00\u680F'
        );
    }
};

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

    this.handleMouseOn = function () {
        var _props3 = _this4.props,
            position = _props3.position,
            activeMouse = _props3.activeMouse;

        activeMouse(position);
    };

    this.handleBodyScrollPosition = function (e) {
        var _props4 = _this4.props,
            handleBodyScrollVertical = _props4.handleBodyScrollVertical,
            position = _props4.position;

        var target = e.target;
        var thead = _this4.thead,
            scrollTbody = _this4.scrollTbody;

        if (target.scrollLeft !== _this4.lastScrollLeft) {
            if (target === scrollTbody && thead) {
                thead.scrollLeft = target.scrollLeft;
            } else if (target === thead && scrollTbody) {
                scrollTbody.scrollLeft = target.scrollLeft;
            }
        }
        _this4.lastScrollLeft = target.scrollLeft;
        if (e.target.className !== 'ne-table-item-header') {
            handleBodyScrollVertical && handleBodyScrollVertical(e, position);
        }
    };

    this.handleBtnListener = function (event, id, type) {
        var _props5 = _this4.props,
            dataSource = _props5.dataSource,
            checkboxCallback = _props5.checkboxCallback;

        var idArray = Object.assign([], _this4.state[type]);
        var isContainId = idArray.filter(function (item) {
            return id === item;
        }).length;
        var idArrayLen = idArray.length;
        var dataSourceLen = dataSource.length;
        if (id === 'header') {
            if (idArrayLen === 0 || idArrayLen > 0 && idArrayLen < dataSourceLen) {
                idArray = dataSourceLen ? easyToMap(dataSourceLen) : ['all'];
            } else {
                idArray = [];
            }
        } else {
            if (isContainId) {
                idArray.forEach(function (item, index) {
                    if (item === id) {
                        idArray.splice(index, 1);
                    }
                });
            } else {
                idArray.push(id);
            }
        }
        _this4.setState(_defineProperty({}, type, idArray));
        if (type === 'checkboxArray') {
            checkboxCallback(_this4.state.data.filter(function (item, index) {
                var bool = false;
                idArray.forEach(function (id) {
                    if (id === index) {
                        bool = true;
                        return;
                    }
                });
                return bool;
            }));
        }
    };

    this.initTableColumns = function () {
        var _props6 = _this4.props,
            checkbox = _props6.checkbox,
            columns = _props6.columns,
            dataSource = _props6.dataSource,
            position = _props6.position,
            expandOpt = _props6.expandOpt;
        var _state2 = _this4.state,
            checkboxArray = _state2.checkboxArray,
            expandRowIds = _state2.expandRowIds;

        var renderColumns = Object.assign([], columns);
        _this4.rules = [];
        // 展开类型
        var showExpand = expandOpt && expandOpt.display && position !== 'right';
        if (showExpand) {
            var expandBtn = function expandBtn(id) {
                var filterArray = expandRowIds.filter(function (item) {
                    return item - 1 === id;
                });
                var type = !!filterArray.length ? 'down-arrow' : 'right-arrow';
                var icon = React.createElement(Icon, { type: type, style: { userSelect: 'none' }, __source: {
                        fileName: _jsxFileName,
                        lineNumber: 177
                    },
                    __self: _this4
                });
                if (expandOpt.display) {
                    icon = expandOpt.expandIcon;
                    if (!!filterArray.length) {
                        icon = expandOpt.shrinkIcon;
                    }
                }
                return icon;
            };
            renderColumns.unshift({
                key: 'expandBtn',
                width: 50,
                renderHeader: function renderHeader() {
                    return React.createElement('div', {
                        __source: {
                            fileName: _jsxFileName,
                            lineNumber: 189
                        },
                        __self: _this4
                    });
                },
                render: expandBtn
            });
        }

        // 多选框
        if (checkbox) {
            var checkElm = function checkElm(id) {
                var checked = '';
                if (checkboxArray.length === dataSource.length && checkboxArray.length) {
                    checked = 'checked';
                } else {
                    var filterArray = checkboxArray.filter(function (item) {
                        return item === id;
                    });
                    checked = !!filterArray.length ? 'checked' : '';
                }
                return React.createElement(Checkbox, {
                    checked: checked,
                    onChange: function onChange(event) {
                        return _this4.handleBtnListener(event, id, 'checkboxArray');
                    },
                    __source: {
                        fileName: _jsxFileName,
                        lineNumber: 205
                    },
                    __self: _this4
                });
            };
            renderColumns.unshift({
                key: 'checkbox',
                width: 50,
                renderHeader: checkElm,
                render: checkElm
            });
        }

        renderColumns.forEach(function (item) {
            _this4.rules.push(item.key);
        });
        return renderColumns;
    };

    this.handleSetSort = function (key, id) {
        var _props7 = _this4.props,
            columns = _props7.columns,
            onSort = _props7.onSort,
            checkbox = _props7.checkbox,
            expandOpt = _props7.expandOpt;

        var sortState = Object.assign({}, _this4.state.sortState);
        var nextType = '';
        switch (_this4.state.sortState[key]) {
            case 'sort':
                nextType = 'sort-down';
                break;
            case 'sort-down':
                nextType = 'sort-up';
                break;
            case 'sort-up':
                nextType = 'sort';
                break;
            default:
                return;
        }
        sortState[key] = nextType;
        var actualId = id;
        if (checkbox) {
            actualId -= 1;
        }
        if (expandOpt.display) {
            actualId -= 1;
        }
        _this4.setState({
            sortState: sortState
        }, function () {
            onSort && onSort(columns[actualId], nextType);
        });
    };

    this.handleInnerScrollEvent = function (elm) {
        var _props8 = _this4.props,
            handleInnerScrollEvent = _props8.handleInnerScrollEvent,
            tbodyRef = _props8.tbodyRef;

        tbodyRef && tbodyRef(elm);
        _this4.scrollTbody = elm;
        handleInnerScrollEvent && handleInnerScrollEvent(elm);
    };

    this.getTableRef = function (el) {
        var tableRef = _this4.props.tableRef;

        _this4.tableItemRef = el;
        tableRef && tableRef(el);
    };
};

export default ItemTable;