/**
 * 用户分组
 */
import React from 'react';
import { Layout, Input, Table, Button, Icon, Menu } from 'antd'
import { connect } from 'dva'
import './userGroupManagement.less'
import DetailBox from './userGroupDetailBox'
import AddMemberBox from '../common/selectUserBox/selectUserBox'
import DeleteBox from '../common/deleteBox/deleteBox'
const { Sider, Content } = Layout
const { Search } = Input

class UserGroupManagement extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            pageSize: 10,
            tableBodyHeight: 0,
            visibleAddMemberBox: false
        }
    }

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

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

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

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

    showDetailBox = (operate) => {
        const { userGroup, dispatch } = this.props;
        const { selectedGroup } = userGroup;

        if(operate === 'create') {
            dispatch({ type: 'userGroup/setNewModel', model: {
                visibleDetailBox: true,
                operate
            }});
        }else {
            dispatch({ type: 'userGroup/setNewModel', model: { ...selectedGroup, visibleDetailBox: true, operate } });
        }
    }

    showAddMemberBox = () => {
        const { dispatch } = this.props;
        dispatch({ type: 'userGroup/setNewModelField', name: 'visibleAddMemberBox', value: true });
    }

    render() {
        const { userGroup, dispatch } = this.props;
        const { selectedGroup } = userGroup;
        const { tableBodyHeight, pageSize, visibleDeleteBox } = this.state;

        const reg = new RegExp('([+ \\- & | ! ( ) { } \\[ \\] ^ \" ~ * ? : ( ) \/])', 'g'); // 需要转义的字符
        let filterLabel = (userGroup.filterLabel || '').replace(new RegExp('(\\\\)', 'g'), '\\$1').replace(reg, '\\$1'); // 添加转义符号
        let userFilterLabel = (userGroup.userFilterLabel || '').replace(new RegExp('(\\\\)', 'g'), '\\$1').replace(reg, '\\$1'); // 添加转义符号

        const columns = [{
            title: '用户',
            dataIndex: 'name',
            width: 200,
            render: text => {
                return (
                    <span>
                        { userFilterLabel ?
                            ((text || '').split(new RegExp(`(${userFilterLabel})`, 'i')).map((fragment, i) => {
                                return (
                                    fragment.toLowerCase().replace(new RegExp('(\\\\)', 'g'), '\\$1').replace(reg, '\\$1') === userFilterLabel.toLowerCase() ?
                                    <span key={i} style={{fontWeight: 'bold', color: 'red'}} className="highlight">{fragment}</span> :
                                    fragment
                                )
                            }
                            )) : text
                        }
                    </span>
                )
            }
        }, {
            title: '操作',
            width: 50,
            render: (text, record, index) => (
                <span style={{ cursor: 'pointer', color: 'red' }} onClick={() => {
                    dispatch({ type: 'userGroup/remoteMemberDelete', userCode: record.code, groupCode: selectedGroup.code });
                }}>删除</span>
            ),
        }]
        const selectedKeys = selectedGroup ? [selectedGroup.code] : [];
        return (
            <Layout className='layout-group'>
                <Sider>
                    <div className='search-area'>
                        <Search
                            value={userGroup.filterLabel}
                            placeholder="请输入关键字"
                            onChange={e => {
                                dispatch({ type: 'userGroup/setFilterLabel', label: e.target.value });
                            }}
                        />
                    </div>
                    <Menu
                        selectedKeys={selectedKeys}
                    >
                        {userGroup.list.map(l => {
                           let reg = new RegExp('(' + filterLabel + '){1}', 'ig');
                           if((l.name || '').search(reg) !== -1) {
                               return { ...l, visible: true };
                           }else {
                               return { ...l, visible: false };
                           }
                        }).map(l => (
                            <Menu.Item key={l.code+''} style={{ display: l.visible ? 'block' : 'none' }} onClick={() => {
                                dispatch({ type: 'userGroup/changeSelectedGroup', group: l });
                            }} >
                                <div className='item-title'>
                                    <span className='label' title={l.name}>
                                        { filterLabel ?
                                            ((l.name || '').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
                                                )
                                            }
                                            )) : <span>{l.name}</span>
                                        }
                                    </span>
                                    <div className='tools'>
                                        <Icon className='tool' title='编辑' type='edit' onClick={() => {this.showDetailBox('modify')}}/>
                                        <Icon className='tool' title='删除' type='delete' onClick={() => {
                                            this.setState({
                                                visibleDeleteBox: true
                                            })
                                        }}/>
                                    </div>
                                </div>
                            </Menu.Item>
                        ))}
                    </Menu>
                    <div className='addbtn-area'>
                        <Button className='add-btn' onClick={() => {this.showDetailBox('create')}}>
                            <Icon type="plus-circle-o" />添加用户组
                        </Button>
                        <DetailBox />
                    </div>
                </Sider>
                <Content>
                    <div className='groupname'>
                        <span>{selectedGroup ? selectedGroup.name : ''}</span>
                        <div className='buttons'>
                            <Search
                                value={userGroup.userFilterLabel}
                                placeholder="请输入关键字"
                                onChange={e => {
                                    dispatch({ type: 'userGroup/setUserFilterLabel', label: e.target.value });
                                }}
                            />
                            {selectedGroup && <Button className='add-btn' onClick={() => {
                                this.setState({
                                    visibleAddMemberBox: true
                                });
                            }}>
                                <Icon type="plus-circle-o" />添加用户
                            </Button>}
                            {this.state.visibleAddMemberBox && <AddMemberBox
                                visibleBox={this.state.visibleAddMemberBox}
                                title='添加用户组成员'
                                hideBox={() => {
                                    this.setState({
                                        visibleAddMemberBox: false
                                    });
                                }}
                                multiple={true}
                                okHandler={(selectedUser) => {
                                    selectedUser.length > 0 && dispatch({ type: 'userGroup/remoteMemberAdd', userList: selectedUser, group: selectedGroup });
                                }}
                                selectedUsers={selectedGroup.member}
                            />}
                        </div>
                    </div>
                    <Table
                        className='member-table'
                        size='small'
                        scroll={{
                            x: columns ? columns.length * 200 : 0,
                            y: tableBodyHeight,
                        }}
                        pagination={{
                            pageSize: pageSize,
                            hideOnSinglePage: true
                        }}
                        columns={columns}
                        dataSource={selectedGroup ? (selectedGroup.member.filter(m => m.name.search(new RegExp('(' + userFilterLabel + '){1}', 'ig')) > -1).map((d, i) => ({...d, key: i})) || []) : []}
                    />
                </Content>
                {visibleDeleteBox && <DeleteBox
                    visibleBox={visibleDeleteBox}
                    text={`确定要删除用户组【${selectedGroup.name}】吗？`}
                    hideBox={() => {
                        this.setState({
                            visibleDeleteBox: false
                        })
                    }}
                    okHandler={() =>{
                        dispatch({ type: 'userGroup/remoteDelete', group: selectedGroup });
                }} />}
            </Layout>
        )
    }
}

export default connect(( { present: { userGroup } } ) => ({ userGroup }))(UserGroupManagement);