import React, {Fragment, PureComponent} from 'react';
import {Alert, Table} from 'antd';
import styles from './index.less';

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

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

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

    static getDerivedStateFromProps(nextProps) {
        // clean state
        if (nextProps.selectedRows.length === 0) {
            const needTotalList = initTotalList(nextProps.columns);
            return {
                selectedRowKeys: [],
                selectedRows: [],
                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);
        }
        this.setState({selectedRowKeys, selectedRows, needTotalList});
    };

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

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

    // 单击行事件
    rowClick = (record) => {
        const {selectionType, rowKey} = this.props;
        const {selectedRowKeys, selectedRows} = this.state;
        const key = record[rowKey] || record.key;

        let newSelectedRowKeys = [];
        let newSelectedRows = [];


        if (selectedRowKeys.includes(key)) {
            newSelectedRowKeys = selectedRowKeys.filter(item => item !== key)
            newSelectedRows = selectedRows.filter(item => item.id !== key)
        } else {
            if("radio" != selectionType) {
                newSelectedRowKeys = [...selectedRowKeys, key];
                newSelectedRows = [...selectedRows, record];
            }else {
                newSelectedRowKeys = [key];
                newSelectedRows = [record];
            }

        }

        this.handleRowSelectChange(newSelectedRowKeys, newSelectedRows);
    }

    // 行操作事件
    rowCallback = (record) => {
        const {rowClick, rowDoubleClick, rowContextMenu, rowMouseEnter, rowMouseLeave} = this.props;
        return {
            onClick: event => {
                const node = event.target;
                const toolNode = event.currentTarget.lastChild;
                const hasNode = toolNode.contains(node);
                if (!hasNode) {
                    this.rowClick(record)
                }
                if(rowClick) {
                    rowClick(event, record);
                }
            }, // 点击行
            onDoubleClick: event => {
                if(rowDoubleClick) {
                    rowDoubleClick(event, record);
                }
            },
            onContextMenu: event => {
                if(rowContextMenu) {
                    rowContextMenu(event, record);
                }
            },
            onMouseEnter: event => {
                if(rowMouseEnter) {
                    rowMouseEnter(event, record);
                }
            }, // 鼠标移入行
            onMouseLeave: event => {
                if(rowMouseLeave) {
                    rowMouseLeave(event, record);
                }
            },
        };

    };

    render() {
        const {selectedRowKeys, needTotalList} = this.state;

        const {data = {}, selectionType, rowKey, size, bodyStyle, isshowAlert,...rest} = this.props;
        const {list = [], pagination} = data;
        const toggleAlert = this.props.showAlert !== '' && this.props.showAlert !== undefined ? this.props.showAlert : true;
        const paginationProps = {
            showSizeChanger: true,
            showQuickJumper: true,
            current: pagination?.currentPage == 0 ? 1 : pagination?.currentPage,
            ...pagination,
        };

        const rowSelection = {
            type: selectionType || "checkbox",
            selectedRowKeys,
            onChange: this.handleRowSelectChange,
            getCheckboxProps: record => ({
                disabled: record.disabled,
            }),
        };


        return (
            <div className={bodyStyle || styles.standardTable}>
                { isshowAlert&&(toggleAlert && toggleAlert !== undefined) ? (
                    <div className={styles.tableAlert}>
                        <Alert
                            message={
                                <Fragment>
                                    已选择 <a style={{fontWeight: 600}}>{selectedRowKeys.length}</a> 项&nbsp;&nbsp;
                                    {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>
                                </Fragment>
                            }
                            type="info"
                            showIcon
                        />
                    </div>
                ) : null}
                <Table
                    rowKey={rowKey || 'key'}
                    rowSelection={selectionType?rowSelection:null}
                    dataSource={list}
                    pagination={paginationProps}
                    onChange={this.handleTableChange}
                    onRow={this.rowCallback}
                    size={size || 'small'}
                    {...rest}
                />
            </div>
        );
    }
}

export default StandardTable;
