/**
 * 人员选择器
 */
import React from 'react'
import { Modal, Row, Col, Select, Spin } from 'antd'
import * as service from '../../../services/index'
import URLS from '../../../constants/url'
const SelectOption = Select.Option

class AddGroupMemberBox extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            selectedUser: props.multiple ? [] : null,
            userData: [],
            fetching: false
        }
    }

    fetchUserData = (keyword) => {
        this.setState({ userData: [], fetching: true }, () => {
            const body = keyword || '';
            service.fetch({
                url: URLS.USER_QUERY,
                body: body,
            }).then(r => {
                if(!r.err && r.data.code > 0) {
                    return r;
                }else {
                    let obj = {};
                    throw obj;
                }
            }).then(r => {
                console.log('获得用户数据', body, r);
                const resData = r.data.data || [];
                this.setState({
                    userData: resData.map(d => ({
                        code: d.id + '',
                        name: d.name,
                        account: d.userName + '',
                        password: d.passWord,
                        role: d.role === 'admin' ? 'admin' : 'default',
                        department: d.department,
                        post: d.post,
                    })),
                    fetching: false
                });
            }).catch(ex => {
                this.setState({
                    userData: [],
                    fetching: false
                });
                console.error('fetch error', ex);
            });
        });
    }

    render() {
        /**
         * multiple: 允许多选
         * onlyAdmin: 只允许选管理员
         * selectedUsers: 已选中用户（无法再被选）
         */
        const { visibleBox, title, hideBox, okHandler, multiple, onlyAdmin, selectedUsers } = this.props;
        const { userData, fetching } = this.state;

        return (
            <Modal
                className='addmember-box'
                title={title}
                visible={visibleBox}
                onOk={() => {
                    if(!!this.state.selectedUser) {
                        okHandler(this.state.selectedUser);
                        hideBox();
                    }
                }}
                onCancel={hideBox}
                maskClosable={false}
                destroyOnClose={true}
            >
                <Row type='flex'>
                    <Col span={24}>
                        <Select
                            style={{ width: '100%' }}
                            mode={ multiple ? 'multiple' : 'sigle'}
                            showSearch
                            filterOption={false}
                            labelInValue={true}
                            notFoundContent={fetching ? <Spin size="small" /> : '无'}
                            onSearch={(value) => {
                                const timeout = this.state.timeout;
                                timeout && window.clearTimeout(timeout);
                                this.setState({
                                    timeout: window.setTimeout(() => {
                                        this.fetchUserData(value)
                                    }, 500)
                                });
                            }}
                            onFocus={() => {
                                this.fetchUserData('');
                            }}
                            onChange={(value) => {
                                this.setState({
                                    selectedUser: multiple ? value.map(v => ({
                                        code: v.key,
                                        name: v.label
                                    })) : {
                                        code: value.key,
                                        name: value.label
                                    }
                                });
                            }}
                            onKeyPress={() => {
                                console.log(112131231);
                            }}
                        >
                            { userData.filter(u => !!onlyAdmin ? (u.role === 'admin') : ( true )).map((s, i) => {
                                return <SelectOption key={i} value={s.code} disabled={!!selectedUsers && selectedUsers.length > 0 && selectedUsers.findIndex(u => u.code === s.code) !== -1}>{s.name}</SelectOption>
                            }) }
                        </Select>
                    </Col>
                </Row>
            </Modal>
        );
    }
}

export default AddGroupMemberBox;