import React from 'react'
import { Layout, Card, Row, Col, Table, Dropdown, Icon, Menu, Input } from 'antd'
import { connect } from 'dva'
import './userManagement.less'
const { Content } = Layout
const { Search } = Input

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

    componentDidMount() {
        const { dispatch } = this.props;
        dispatch({ type: 'user/fetchList' });
        this.tableSize();
        window.addEventListener('resize', this.tableSize);
    }

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

    tableSize = () => {

        const layoutGroup = document.getElementsByClassName('layout-usermanagement')[0];
        const content = layoutGroup.getElementsByClassName('ant-layout-content')[0];
        const header = content.getElementsByClassName('ant-card-head')[0];
        // 容器高度 - 搜索栏 - 表头高度 - 分页器高度 - padding
        let tableBodyHeight = content.offsetHeight - header.offsetHeight - 42 - 26 - 24;
        this.setState({
            tableBodyHeight,
            pageSize: Math.ceil((tableBodyHeight) / 38)
        });
    }

    render() {
        const { user, main, dispatch } = this.props;
        const { tableBodyHeight, pageSize } = this.state;
        const { newOne } = user;
        const { currentUser } = main;

        const moreOperatingMenu = (
            <Menu className='operationmenu' visible={true}>
                <Menu.Item
                    disabled={currentUser.code === newOne.code || newOne.role === 'superAdmin'}
                    onClick={() => {
                        dispatch({ type: 'user/remoteModify', fields: {
                            role: newOne.role === 'admin' ? 'normal' : 'admin'
                        } });
                    }}
                >
                    <Icon type="key" />{ newOne.role === 'admin' ? '取消管理员' : ( newOne.role === 'superAdmin' ? '超级管理员' : '设为管理员')}
                </Menu.Item>
            </Menu>
        );

        const reg = new RegExp('([+ \\- & | ! ( ) { } \\[ \\] ^ \" ~ * ? : ( ) \/])', 'g'); // 需要转义的字符
        let filterLabel = (user.filterLabel || '').replace(new RegExp('(\\\\)', 'g'), '\\$1').replace(reg, '\\$1'); // 添加转义符号
        
        const columns = [{
            title: '姓名',
            dataIndex: 'fullName',
            width: 100,
            render: (text, record, index) => (
                <span>
                    { 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
                    }
                </span>
            )
        }, {
            title: '角色',
            dataIndex: 'role',
            width: 100,
            render: text => text === 'admin' ? '管理员' : ( text === 'superAdmin' ? '超级管理员' : '普通用户')
        }, {
            title: '操作',
            render: (text, record, index) => {
                return record.role === 'superAdmin' ? null : <Dropdown code={record.code} overlay={moreOperatingMenu} trigger={['click']} >
                    <Icon type="setting" />
                </Dropdown>
            },
            width: 50
        }];

        return (
            <Layout className='layout-usermanagement'>
                <Content>
                    <Card className='usermanagement-body' title={
                        <Row className='usermanagement-tools' type='flex' justify='space-between'>
                            <Col style={{ display: 'flex' }}>
                            </Col>
                            <Col className='search'>
                                <Col>
                                    <Search
                                        placeholder="请输入关键字"
                                        value={user.filterLabel}
                                        onChange={e => {
                                            dispatch({ type: 'user/setFilterLabel', label: e.target.value });
                                        }}
                                    />
                                </Col>
                            </Col>
                        </Row>
                    }>
                        <Table
                            className='usermanagement-table'
                            columns={columns}
                            dataSource={user.list.filter(l => {
                                let reg = new RegExp('(' + filterLabel + '){1}', 'ig');
                                return (l.fullName || '').search(reg) !== -1;
                            }).map((d, i) => ({
                                ...d, key: i
                            }))}
                            size='small'
                            scroll={{
                                x: columns ? columns.length * 200 : 0,
                                y: tableBodyHeight,
                            }}
                            pagination={{
                                pageSize: pageSize,
                                hideOnSinglePage: true
                            }}
                            onRow={(record) => {
                                return {
                                    onClick: () => {
                                        let arr = [];
                                        for(let k in record) {
                                            let obj = {};
                                            obj.name = k;
                                            obj.value = record[k];
                                            arr.push(obj);
                                        }
                                        dispatch({ type: 'user/setNewModelFields', fields: arr });
                                    }
                                }
                            }}
                        />
                    </Card>
                </Content>
            </Layout>
        );
    }
}

export default connect(({ present: { user, main } }) => ({ user, main }))(UserManagement);