import React, { Component } from 'react';
import { Table } from 'antd';
import 'antd/dist/antd.css';
//import memoize from 'memoize-one';

export default class RowspanTable extends Component {
    //buildNewColumns = memoize();
    buildNewColumns=(columns, pageSize) => {
        return columns.map(column => {
            const { mergeAbove, render: originRender, dataIndex } = column;
            if (!mergeAbove) {
                return column;
            }
            const render = (value, row) => {
                const { dataSource: data } = this.props;

                // 当有分页时，antd 传递进来的第三个参数行索引 index 是错的，因此
                // 用 findIndex 找到正确的行索引，要求 data 里面不得出现两个相同
                // 的行（一般不会出现这种情况）。
                const i = data.findIndex(r => r === row); 

                const _i = i % pageSize;
                if (_i > 0 && value === data[i - 1][dataIndex]) {
                    var children = null;
                    var rowSpan = 0;
                } else {
                    children = originRender
                        ? originRender(value, row, i)
                        : value;
                    const nextI = Math.min(i - _i + pageSize, data.length);
                    for (
                        var ii = i + 1;
                        ii < nextI && value === data[ii][dataIndex];
                        ii++
                    ) ;
                    rowSpan = ii - i;
                }
                return { children, props: { rowSpan } };
            };
            return { ...column, render };
        });
    }

    render() {
        const { props, buildNewColumns } = this;
        const { columns, pagination } = props;
        const pageSize = getPageSize(pagination);
        const newColumns = buildNewColumns(columns, pageSize);
        return <Table {...props} columns={newColumns}/>;
    }
}

function getPageSize(pagination) {
    if (!pagination) {
        return 100000;
    }
    if (typeof(pagination) === 'object') {
        return pagination.pageSize || 10;
    }
    return 10;
}