import React, { Component, Fragment } from 'react';
import NormalTable from '../NormalTable';
import Index from '../Shell';

function initTotalList(columns) {
	const totalList = [];
	columns.forEach((column) => {
		if (column.needTotal) {
			totalList.push({ ...column, total: 0 });
		}
	});
	return totalList;
}

class StandardTable extends Component {
	constructor(props) {
		super(props);
		const { columns } = props;
		const needTotalList = initTotalList(columns);

		this.state = {
			selectedRowKeys: [],
			needTotalList,
		};
	}

	static getDerivedStateFromProps(nextProps) {
		// clean state
		if (nextProps.selectedRows.length === 0) {
			const needTotalList = initTotalList(nextProps.columns);
			return {
				selectedRowKeys: [],
				needTotalList,
			};
		}
		return null;
	}

	handleRowSelectChange = (selectedRowKeys, selectedRows) => {
		let { needTotalList } = this.state;
		needTotalList = needTotalList.map((item) => ({
			...item,
			total: selectedRows.reduce((sum, val) => sum + parseFloat(val[item.dataIndex], 10), 0),
		}));
		const { onSelectRow } = this.props;
		if (onSelectRow) {
			onSelectRow(selectedRows, selectedRowKeys);
		}

		this.setState({ selectedRowKeys, needTotalList });
	};

	handleTableChange = (pagination, filters, sorter) => {
		const { onChange } = this.props;
		if (onChange) {
			onChange(pagination, filters, sorter);
		}
	};

	cleanSelectedKeys = () => {
		this.handleRowSelectChange([], []);
	};

	checkRowKey = () => {
	  const { rowKey,
      data: { list, pagination },
    } = this.props;
	  if(rowKey && list && list.length){
	    if(list[0][rowKey]){
	      return rowKey;
      }
    }
	  return 'id';
  }


	render() {
		const { selectedRowKeys, needTotalList } = this.state;
		const {
			data: { list, pagination },
			loading,
			columns,
			rowKey,
			components,
			scroll,
			noSelectRow,
			bordered,
			showHeader,
      getCheckboxProps,
		} = this.props;

		const paginationProps = {
			showSizeChanger: true,
			showQuickJumper: true,
			pageSizeOptions: ['10', '20', '50', '100', '200'],
			...pagination,
		};
		if (typeof paginationProps.total === 'string') {
			paginationProps.total = Number(paginationProps.total) || 0;
		}
		const rowSelection = {
			selectedRowKeys,
			onChange: this.handleRowSelectChange,
			type: this.props.selectType || 'checkbox ',
			getCheckboxProps: getCheckboxProps && typeof getCheckboxProps === 'function' ? getCheckboxProps : (record) => ({
				disabled: record.disabled,
			}),
		};
		return (
			<div>
				<Index>
					{!noSelectRow ? (
						<span style={{ paddingLeft: '12px', paddingTop: '8px' }}>
							已选择
							{selectedRowKeys.length}
							{needTotalList.map((item) => (
								<span style={{ marginLeft: 8 }} key={item.dataIndex}>
									{item.title}
									总计&nbsp;
									<span style={{ fontWeight: 600 }}>
										{item.render ? item.render(item.total) : item.total}
									</span>
								</span>
							))}
							<a onClick={this.cleanSelectedKeys} style={{ marginLeft: 24 }}>
								清空
							</a>
						</span>
					) : (
						<div style={{ height: '1px' }} />
					)}
				</Index>

				<NormalTable
					components={components}
					loading={loading}
          rowKey={this.checkRowKey()}
					rowSelection={typeof noSelectRow !== 'undefined' && noSelectRow ? null : rowSelection}
					dataSource={
						!!list &&
						list.map((x) => {
							return !!x.id
								? x
								: {
										id: Math.random() * 10000 + '',
										...x,
								  };
						})
					}
					bordered={bordered}
					columns={columns}
					size="small"
					scroll={scroll}
					showHeader={showHeader}
					pagination={this.props.isHiddenPage ? null : pagination === null ? null : paginationProps}
					onChange={this.handleTableChange}
				/>
			</div>
		);
	}
}

export default StandardTable;
