import React from 'react';
import { Icon, Modal, message, AutoComplete, Spin, Input, Select, Button, Form, Popconfirm, TreeSelect } from 'antd';
import $ from 'jquery/src/ajax';
import './userMangagement.less';
import { cityArr, station, post } from '../../../dataDic.js';
import { splitUrl } from '../../../tools.js';
import moment from 'moment';
import ImgList from "../../../common/imgList";

import StaffSearch from '../../../../component/common/staffSearch';

//图片组件
const PicturesWall = React.createClass({
    getInitialState() {
        return {
            previewVisible: false,
            previewImage: '',
            fileList: [],
            role: [],
            district: [],
            cityOption: [],
        }
    },
    handleCancel() {
        this.setState({ previewVisible: false })
    },
    handlePreview(file) {
        this.setState({
            previewImage: file.url || file.thumbUrl,
            previewVisible: true,
        });
    },
    handleChange(info) {
        let fileList = info.fileList;
        this.setState({ fileList });
        this.props.fileList(fileList);
    },
    componentWillReceiveProps(nextProps) {
        this.state.fileList = nextProps.pictureUrl;
    },
    render() {
        const { previewVisible, previewImage, fileList } = this.state;
        const uploadButton = (
            <div>
                <Icon type="plus" />
                <div className="ant-upload-text">点击上传</div>
            </div>
        );
        return (
            <div style={{ display: "inline-block" }}>
                <ImgList
                    domId={this.props.domId}
                    uploadConfig={{
                        action: globalConfig.context + "/api/admin/superviser/uploadAdminImg",
                        data: { 'sign': this.props.pictureSign },
                        multiple: true,
                        listType: "picture-card",
                    }}
                    onChange={(infor) => {
                        this.handleChange(infor)
                    }}
                    fileList={fileList}
                />
            </div>
        );
    }
});

const Newuser = Form.create()(React.createClass({
    getInitialState() {
        return {
            orgCodeUrl: [],
            loading: false,
            loaduser: {},
            datauser: [],
            role: []
        };
    },
    getDefaultProps() {
        return {
            userDetaile: false
        }
    },
    handleSubmit(e) {
        e.preventDefault();
        if (!this.state.role || this.state.role.length === 0) {
            message.warning('请选择角色');
            return false;
        };
        // if (!this.state.status && this.props.userDetaile) {
        //     message.warning('请选择角色状态');
        //     return false;
        // };
        if (window.adminData.isSuperAdmin) {
            if (!this.state.departmentId) {
                message.warning('请选择组织部门');
                return false;
            };
        }
        if (!this.state.theTypes && !this.state.superiorId) {
            message.warning('请输入正确的上级主管');
            return false;
        };
        if (!this.state.reviewer) {
            message.warning('请输入正确的公出审核人');
            return false;
        }
        if (this.state.contactMobile) {
            if (!(/^1[1-9][0-9]\d{4,8}$/.test(this.state.contactMobile))) {
                message.warning("不是完整的11位手机号或者正确的手机号前七位");
                this.setState({
                    loading: false
                });
                return false;
            }
        }
        // if (this.state.ambId == null || this.state.ambId == undefined) {
        //     message.warning('请选择所属巴');
        //     return false;
        // }
        let theorgCodeUrl = [];
        if (this.state.orgCodeUrl.length) {
            let picArr = [];
            this.state.orgCodeUrl.map(function (item) {
                if (item.response && item.response.data && item.response.data.length) {
                    picArr.push(item.response.data);
                }
            });
            theorgCodeUrl = picArr.join(",");
        };
        let api = this.props.userDetaile ? "/api/admin/superviser/updateAdmin" : '/api/admin/superviser/insertAdmin'
        this.setState({
            loading: true
        });
        $.ajax({
            method: "POST",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + api,
            data: {
                roles: this.state.role,
                data: JSON.stringify({
                    id: this.state.id ? this.state.id : this.props.addId,
                    mobile: this.state.mobile,
                    status: this.state.status,
                    contactMobile: this.state.contactMobile,
                    name: this.state.name,
                    departmentId: window.adminData.isSuperAdmin ? this.state.departmentId : window.adminData.departmentId,
                    duty: this.state.duty,
                    position: this.state.position,//岗位
                    email: this.state.email,
                    superiorId: this.state.theTypes ? this.state.theTypes : this.state.superiorId,
                    reviewer: this.state.reviewer,
                    district: this.state.district,
                    headPortraitUrl: theorgCodeUrl.length ? theorgCodeUrl : '',
                    entryTime: this.state.selTime,
                    ambId: !!this.state.ambId ? this.state.ambId : null,
                })
            }
        }).done(function (data) {
            this.setState({
                loading: false
            });
            if (!data.error.length) {
                message.success('保存成功!');
                this.handleOk();
            } else {
                message.warning(data.error[0].message);
            }
        }.bind(this));
    },
    //主管初始加载(自动补全)
    supervisor(e) {
        $.ajax({
            method: "post",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/organization/selectName",
            data: {
                name: e
            },
            success: function (data) {
                let thedata = data.data;
                if (!thedata) {
                    if (data.error && data.error.length) {
                        message.warning(data.error[0].message);
                    };
                    thedata = {};
                };
                this.setState({
                    customerArr: thedata,
                });
            }.bind(this),
        }).always(function () {
            this.setState({
                loading: false
            });
        }.bind(this));
    },
    //上级主管输入框失去焦点是判断客户是否存在
    selectAuto(value) {
        let theType = '';
        let contactLists = this.state.customerArr || [];
        if (value) {
            contactLists.map(function (item) {
                if (item.name === value.toString()) {
                    theType = item.id;
                }
            });
        }
        this.setState({
            theTypes: theType,
            superior: value
        })
        if (!this.state.reviewerName || !this.state.reviewer) {
            this.setState({
                reviewerName: value,
                reviewer: theType
            })
        }
    },
    //值改变时请求客户名称
    httpChange(e) {
        if (e.length >= 1) {
            this.supervisor(e);
        }
        this.setState({
            superior: e
        })
    },
    //查看基本详情基本信息
    loaduser(record) {
        if (record) {
            $.ajax({
                method: "post",
                dataType: "json",
                crossDomain: false,
                url: globalConfig.context + '/api/admin/superviser/selectAllByid',
                data: {
                    id: record.id
                },
                success: function (data) {
                    let thisdata = data.data;
                    if (!thisdata) {
                        if (data.error && data.error.length) {
                            message.warning(data.error[0].message);
                        };
                        thisdata = {};
                    };
                    this.setState({
                        id: thisdata.id,
                        mobile: thisdata.mobile,
                        name: thisdata.name,
                        email: thisdata.email,
                        createTime: thisdata.createTime,
                        district: thisdata.district != ' ' ? JSON.parse(thisdata.district) : undefined,
                        position: thisdata.position ? thisdata.position : undefined,
                        superior: thisdata.superior,
                        superiorId: thisdata.superiorId,//上级Id
                        reviewerName: thisdata.reviewerName,
                        reviewer: thisdata.reviewer,
                        theTypes: '',
                        duty: thisdata.duty ? thisdata.duty : undefined,//职务
                        status: Number(thisdata.status),
                        contactMobile: thisdata.contactMobile ? thisdata.contactMobile : undefined,//手机号
                        departmentId: thisdata.departmentId ? thisdata.departmentId : undefined,//部门id
                        userNo: thisdata.userNo,
                        orgCodeUrl: thisdata.headPortraitUrl ? splitUrl(thisdata.headPortraitUrl, ',', globalConfig.avatarHost + '/upload') : [],
                        role: this.props.role,
                        entryTime: thisdata.entryTime ? moment(thisdata.entryTime, 'YYYY-MM-DD') : undefined,
                        selTime: thisdata.entryTime,
                        ambId: !!thisdata.ambId && Number(thisdata.ambId), // 分巴id
                    });
                }.bind(this),
            }).always(function () {
                this.setState({
                    loading: false
                });
            }.bind(this));
        }
    },
    //重置密码
    resetPwd() {
        this.setState({
            loading: true
        })
        $.ajax({
            type: 'post',
            url: globalConfig.context + "/api/admin/superviser/resetPwd",
            dataType: "json",
            data: {
                id: this.props.datauser.id
            },
        }).done((res) => {
            if (res.error && res.error.length) {
                message.error(res.error[0].message);
            } else {
                message.success("密码重置成功");
            }
        }).always(() => {
            this.setState({
                loading: false
            })
        });
    },
    handleOk(e) {
        this.props.closeDesc(false, true);
    },
    handleCancel(e) {
        this.props.closeDesc(false);
    },
    //入职时间选择
    selTime(e, index) {
        this.setState({
            entryTime: e,
            selTime: index
        })
    },
    getOrgCodeUrl(e) {
        this.setState({ orgCodeUrl: e });
    },
    componentWillMount(e) {
        const cityArrs = [];
        cityArr.map(function (item) {
            cityArrs.push(
                <Select.Option key={item.value}>{item.key}</Select.Option>
            )
        });
        this.state.cityOption = cityArrs;
    },
    componentDidMount() {
        if (this.props.datauser.id) {
            this.loaduser(this.props.datauser)
            this.setState({
                rolek: this.props.role
            })
        }
    },

    render() {
        const FormItem = Form.Item
        const formItemLayout = {
            labelCol: { span: 8 },
            wrapperCol: { span: 14 },
        };
        const dataSources = this.state.customerArr || [];
        const options = dataSources.map((group, index) =>
            <Select.Option key={index} value={group.name}>{group.name}</Select.Option>
        )
        const departmentArr = this.props.departmentArr || [];
        const roleArrS = this.props.roleArr || [];
        const rolst = this.state.rolek || [];
        return (
            <div>
                <Modal maskClosable={false} visible={this.props.showDesc}
                    onOk={this.handleOk} onCancel={this.handleCancel}
                    width='800px'
                    title={this.props.userDetaile ? '用户详情' : '新建用户'}
                    footer=''
                    className="admin-desc-content">
                    <Form layout="horizontal" onSubmit={this.handleSubmit} id="demand-form">
                        <Spin spinning={this.state.loading}>
                            <div className="clearfix">
                                <div className="clearfix">
                                    <FormItem className="half-item"
                                        {...formItemLayout}
                                        label="用户名" >
                                        <Input placeholder="输入登录用户名" value={this.state.mobile}
                                            onChange={(e) => { this.setState({ mobile: e.target.value }) }} required="required" style={{ width: '200px' }} />
                                        <span className="mandatory">*</span>
                                    </FormItem>
                                    {this.props.userDetaile ?
                                        <Popconfirm
                                            title={"用户 [ " + this.props.datauser.name + " ] 的密码将会重置为123456,确认操作?"}
                                            onConfirm={this.resetPwd}
                                            okText="确认"
                                            cancelText="取消"
                                            placement="topLeft">
                                            <Button>重置密码</Button>
                                        </Popconfirm> : ''}
                                </div>
                                <FormItem className="half-item"
                                    {...formItemLayout}
                                    label="用户角色"
                                >
                                    {roleArrS.length > 0 ?
                                        <Select
                                            mode="multiple"
                                            optionFilterProp={'title'}
                                            tokenSeparators={[',']}
                                            placeholder="选择用户角色"
                                            value={this.state.role}
                                            style={{ width: '200px' }}
                                            onChange={(e) => {
                                                this.setState({
                                                    role: e
                                                })
                                            }}>
                                            {
                                                roleArrS.map(function (item, _) {
                                                    return <Select.Option title={item.roleName} value={item.id}>{item.roleName}</Select.Option>
                                                })
                                            }
                                        </Select> : null
                                    }
                                    <span className="mandatory">*</span>
                                </FormItem>

                                <FormItem className="half-item"
                                    {...formItemLayout}
                                    label=""
                                >
                                    <span style={{ display: rolst.length > 1 ? 'block' : 'none', color: 'red' }}>存在多个角色</span>
                                </FormItem>
                                {this.props.userDetaile ? <FormItem className="half-item"
                                    {...formItemLayout}
                                    label="用户状态" >
                                    <Select
                                        placeholder="用户状态"
                                        value={this.state.status}
                                        style={{ width: '200px' }}
                                        onChange={(e) => { this.setState({ status: e }) }}
                                    >
                                        <Select.Option value={0} >正常</Select.Option>
                                        <Select.Option value={1} >锁定</Select.Option>
                                    </Select>
                                    <span className="mandatory">*</span>
                                </FormItem> : ''}
                                <FormItem className="half-item"
                                    {...formItemLayout}
                                    label="用户姓名" >
                                    <Input placeholder="请输入用户姓名" style={{ width: '200px' }} value={this.state.name}
                                        onChange={(e) => { this.setState({ name: e.target.value }) }} required="required" />
                                    <span className="mandatory">*</span>
                                </FormItem>
                                <FormItem className="half-item"
                                    {...formItemLayout}
                                    label="联系方式" >
                                    <Input placeholder="请输入手机号" style={{ width: '200px' }} value={this.state.contactMobile}
                                        onChange={(e) => { this.setState({ contactMobile: e.target.value }) }} />
                                </FormItem>
                                {/*<FormItem className="half-item"
				                            {...formItemLayout}
				                            label="入职时间" >
				                            <DatePicker
				                              style={{marginTop:'0',width:'200px',height:'27px'}}
										      showTime
										      format="YYYY-MM-DD"
										      placeholder="选择入职时间"
										      value={this.state.entryTime}
										      onChange={(e,time)=>{this.selTime(e,time)}}
										    />
			                    		</FormItem>*/}
                                {window.adminData.isSuperAdmin ? <FormItem className="half-item"
                                    {...formItemLayout}
                                    label="组织部门" >
                                    <Select placeholder="选择组织部门"
                                        style={{ width: 200 }}
                                        value={this.state.departmentId}
                                        onChange={(e) => { this.setState({ departmentId: e }) }}>
                                        {
                                            departmentArr.map(function (item) {
                                                return <Select.Option key={item.id} >{item.name}</Select.Option>
                                            })
                                        }
                                    </Select>
                                    <span className="mandatory">*</span>
                                </FormItem> : ''}
                                <FormItem className="half-item"
                                    {...formItemLayout}
                                    label="职务"
                                >
                                    <Select placeholder="选择职务" style={{ width: '200px' }} value={this.state.duty} onChange={(e) => { this.setState({ duty: e }) }}>
                                        {
                                            post.map(function (item) {
                                                return <Select.Option key={item.value} >{item.key}</Select.Option>
                                            })
                                        }
                                    </Select>
                                </FormItem>
                                <FormItem className="half-item"
                                    {...formItemLayout}
                                    label="岗位"
                                >
                                    <Select placeholder="选择岗位" style={{ width: '200px' }} value={this.state.position} onChange={(e) => { this.setState({ position: e }) }}>
                                        {
                                            station.map(function (item) {
                                                return <Select.Option key={item.value} >{item.key}</Select.Option>
                                            })
                                        }
                                    </Select>
                                </FormItem>
                                <FormItem className="half-item"
                                    {...formItemLayout}
                                    label="电子邮箱" >
                                    <Input placeholder="请输入邮箱" style={{ width: '200px' }} value={this.state.email}
                                        onChange={(e) => { this.setState({ email: e.target.value }) }} />
                                </FormItem>
                                <FormItem className="half-item"
                                    {...formItemLayout}
                                    label="上级主管"
                                >
                                    <AutoComplete
                                        className="certain-category-search"
                                        dropdownClassName="certain-category-search-dropdown"
                                        dropdownMatchSelectWidth={false}
                                        size="large"
                                        style={{ width: '200px' }}
                                        dataSource={options}
                                        placeholder="输入名称"
                                        value={this.state.superior}
                                        onChange={this.httpChange}
                                        filterOption={true}
                                        onSelect={this.selectAuto}
                                    >
                                        <Input />
                                    </AutoComplete>
                                    <span className="mandatory">*</span>
                                </FormItem>
                                <FormItem className="half-item"
                                    {...formItemLayout}
                                    label="公出审核"
                                >
                                    <StaffSearch
                                        valueName={this.state.reviewerName}
                                        placeholder="输入名称"
                                        onBlurChange={(obj) => {
                                            this.setState({
                                                reviewer: obj.value
                                            })
                                        }}
                                    />
                                    <span className="mandatory">*</span>
                                </FormItem>
                                {this.props.userDetaile ?
                                    <FormItem className="half-item"
                                        {...formItemLayout}
                                        label="用户编号" >
                                        <span>{this.state.userNo}</span>
                                    </FormItem>
                                    : ''}
                                <div className='clearfix'>
                                    <FormItem className="half-item"
                                        {...formItemLayout}
                                        label="地区" >
                                        <Select
                                            multiple
                                            style={{ width: '500px' }}
                                            placeholder="选择地区"
                                            filterOption={(input, option) => { return option.props.children.indexOf(input) >= 0 }}
                                            value={this.state.district}
                                            onChange={(pids) => {
                                                this.state.district = pids;
                                                this.setState({
                                                    district: this.state.district
                                                })
                                            }}
                                        >
                                            {this.state.cityOption}
                                        </Select>
                                    </FormItem>
                                </div>
                                <div className="clearfix">
                                    <FormItem
                                        className="half-item"
                                        {...formItemLayout}
                                        label="用户头像"
                                    >
                                        <PicturesWall
                                            domId={'newUser1'}
                                            pictureSign="customer_sys_file"
                                            fileList={this.getOrgCodeUrl}
                                            pictureUrl={this.state.orgCodeUrl} />
                                        <p>图片建议:要清晰。</p>
                                    </FormItem>
                                    <FormItem
                                        className="half-item"
                                        {...formItemLayout}
                                        label="分巴"
                                    >
                                        <TreeSelect
                                            style={{ width: 200 }}
                                            value={this.state.ambId}
                                            dropdownStyle={{ maxHeight: 300, overflow: 'auto' }}
                                            treeData={this.props.level1Data}
                                            placeholder="请选择"
                                            showSearch
                                            treeNodeFilterProp="title"
                                            onChange={(e) => {
                                                this.setState({
                                                    ambId: e,
                                                });
                                            }}
                                        />
                                    </FormItem>
                                </div>
                            </div>
                            <FormItem wrapperCol={{ span: 12, offset: 4 }}>
                                <Button className="set-submit" type="primary" htmlType="submit">保存</Button>
                                <Button className="set-submit" type="ghost" onClick={this.handleCancel}>取消</Button>
                            </FormItem>
                        </Spin>
                    </Form >
                </Modal>
            </div>
        )
    }
}));

export default Newuser;