import React from 'react'
import { Layout, Row, Col, Table, Card, Button, Icon } from 'antd'
import { connect } from 'dva'
import moment from 'moment'
import ListFilter from '../common/listFilter/index'
import EllipsisTooltip from '../common/ellipsisTooltip/index'
import Loading from '../common/loading/index'
import './logs.less'
const { Content } = Layout

class Logs extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            total: 0,
            pageSize: 0,
            tableBodyHeight: 0,
        }
    };

    componentDidMount() {
        this.tableSize();
        window.addEventListener('resize', this.tableSize);
    }

    componentWillUnmount() {
        window.removeEventListener('resize', this.tableSize);
    }

    tableSize = () => {
        const { dispatch, logs } = this.props;
        const cardBody = document.getElementsByClassName('ant-card-body')[0];
        const table = cardBody.getElementsByClassName('logs-table')[0];
        const tableHeader = table.getElementsByClassName('ant-table-thead')[0];
        const padding = table.getBoundingClientRect().top - cardBody.getBoundingClientRect().top;
        const tableHeaderHeight = tableHeader.offsetHeight;
        let tableBodyHeight = cardBody.offsetHeight - padding * 2 - tableHeaderHeight - 40;
        let pageSize = Math.ceil((tableBodyHeight) / 38);
        this.setState({
            pageSize,
            tableBodyHeight
        });
        dispatch({ type: 'logs/fetchList', page: logs.currentPage, pageSize });
    }

    onSort = (list) => {
        return list.sort((a, b) => new Date(b.date) - new Date(a.date));
    }

    onSearch = () => {
        const { logs } = this.props;
        const { list, filterLabel, filterItem } = logs;
        const reg = new RegExp('([+ \\- & | ! ( ) { } \\[ \\] ^ \" ~ * ? : ( ) \/])', 'g'); // 需要转义的字符
        let _filterLabel = filterLabel ? (filterLabel + '').replace(new RegExp('(\\\\)', 'g'), '\\$1').replace(reg, '\\$1') : ''; // 添加转义符号
        let filterReg = new RegExp('(' + _filterLabel + '){1}', 'ig');

        let dataList = list.map(l => {
            if(filterItem.type === 'date') {
                if(filterLabel===""){
                    return { ...l };
                }else if(filterLabel.indexOf('#')>-1){
                    let start = filterLabel.split('#')[0]
                    let end = filterLabel.split('#')[1]
                    let nowTime = new Date(l[filterItem.name]).getTime();
                    if(nowTime>=start && nowTime<=end){
                        return { ...l };
                    }
                    return null;
                }else{
                    return null;
                }
            }else {
                return ((l[filterItem.name] + '').search(filterReg) > -1) ? { ...l } : null
            }
        }).filter(l => l !== null);

        return dataList;
    }

    onPageChange = page => {
        const { dispatch } = this.props;
        const { pageSize } = this.state;
        dispatch({ type: 'logs/setField', name: 'currentPage', value: page });
        dispatch({ type: 'logs/fetchList', page: page, pageSize });
    };

    render() {
        const { logs, dispatch } = this.props;
        const { pageSize, tableBodyHeight } = this.state;
        const { listLoading, filterItem, filterLabel, currentPage, total } = logs;

        let dataList = this.onSort(this.onSearch());

        const reg = new RegExp('([+ \\- & | ! ( ) { } \\[ \\] ^ \" ~ * ? : ( ) \/])', 'g'); // 需要转义的字符

        const logsColumns = [{
            title: '模块',
            dataIndex: 'module',
            key: 'module',
            width: 100,
            render: text => {
                return (filterItem.name === 'module' && filterLabel) ?
                ((text || '').split(new RegExp(`(${filterLabel})`, 'i')).map((fragment, i) => {
                    return (
                        fragment.toLowerCase().replace(new RegExp('(\\\\)', 'g'), '\\$1').replace(reg, '\\$1') === filterLabel.toLowerCase() ?
                        <span key={i} style={{fontWeight: 'bold', color: 'red'}} className="highlight">{fragment}</span> :
                        fragment
                    )
                }
                )) : text
            }
        }, {
            title: '名称',
            dataIndex: 'name',
            key: 'name',
            width: 200,
            onCell: () => {
                return {
                    style: {
                        whiteSpace: 'nowrap',
                        maxWidth: 200,
                    }
                }
            },
            render: text => {
                return <EllipsisTooltip title={text}>{
                    (filterItem.name === 'name' && filterLabel) ?
                    ((text || '').split(new RegExp(`(${filterLabel})`, 'i')).map((fragment, i) => {
                        return (
                            fragment.toLowerCase().replace(new RegExp('(\\\\)', 'g'), '\\$1').replace(reg, '\\$1') === filterLabel.toLowerCase() ?
                            <span key={i} style={{fontWeight: 'bold', color: 'red'}} className="highlight">{fragment}</span> :
                            fragment
                        )
                    }
                    )) : text
                }</EllipsisTooltip>
            }
        }, {
            title: '操作',
            dataIndex: 'operation',
            key: 'operation',
            width: 200,
            onCell: () => {
                return {
                    style: {
                        whiteSpace: 'nowrap',
                        maxWidth: 200,
                    }
                }
            },
            render: text => <EllipsisTooltip title={text}>{text}</EllipsisTooltip>
        }, {
            title: '操作人',
            dataIndex: 'operator',
            key: 'operator',
            width: 100,
            render: text => {
                return (filterItem.name === 'operator' && filterLabel) ?
                ((text || '').split(new RegExp(`(${filterLabel})`, 'i')).map((fragment, i) => {
                    return (
                        fragment.toLowerCase().replace(new RegExp('(\\\\)', 'g'), '\\$1').replace(reg, '\\$1') === filterLabel.toLowerCase() ?
                        <span key={i} style={{fontWeight: 'bold', color: 'red'}} className="highlight">{fragment}</span> :
                        fragment
                    )
                }
                )) : text
            }
        }, {
            title: '操作时间',
            dataIndex: 'date',
            key: 'date',
            width: 100,
            render: text => moment(text).format('YYYY-MM-DD HH:mm:ss')
        }];

        return (
            <Layout className='layout-logs'>
                <Loading visible={listLoading}/>
                <Content>
                    <Card bordered={false} className='logs-body' title={
                        <Row className='logs-tools' type='flex' justify='end'>
                            <Col className='search'>
                                <Button className='btn-refresh' onClick={() => {
                                    dispatch({ type: 'logs/setFilterLabel', label: '' });
                                    dispatch({ type: 'logs/fetchList', page: currentPage, pageSize });
                                }}>
                                    <Icon type='sync'/>
                                </Button>
                                <ListFilter modelName='logs' model={logs}
                                    onChangeFilterValue={()=> {
                                        window.clearTimeout(this.timeoutkey);
                                        this.timeoutkey = window.setTimeout(() => {
                                            dispatch({ type: 'logs/fetchList', page: currentPage, pageSize });
                                        }, 200);
                                    }}
                                />
                            </Col>
                        </Row>
                    }>
                        <Table
                            className='logs-table'
                            columns={logsColumns}
                            dataSource={dataList.map((d, i) => ({ ...d, key: i }))}
                            size='small'
                            // loading={loading}
                            pagination={{
                                pageSize,
                                total,
                                current: currentPage,
                                // simple: true,
                                showTotal: (total, range) => {
                                    return `第${range[0]}到第${range[1]}条数据，共${total}条数据`;
                                },
                                onChange: this.onPageChange
                            }}
                            scroll={{ x: false, y: tableBodyHeight }}
                        />
                    </Card>
                </Content>
            </Layout>
        )
    }
}

export default connect(({ logs }) => ({ logs }))(Logs)