import React from 'react';
import { Icon,  Modal, message,  AutoComplete,Spin, Input, Select, Button, Form,Upload,Popconfirm } from 'antd';
import ajax from 'jquery/src/ajax/xhr.js';
import $ from 'jquery/src/ajax';
import './userMangagement.less';
import {socialAttribute,cityArr,station,post} from '../../../dataDic.js';
const Option = AutoComplete.Option;

//图片组件
const PicturesWall = React.createClass({
    getInitialState() {
        return {
            previewVisible: false,
            previewImage: '',
            fileList: [],
        }
    },
    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"}}>
                <Upload
                    action={globalConfig.context + "/api/admin/customer/attachmentUpload"}
                    data={{ 'sign': this.props.pictureSign }}
                    listType="picture-card"
                    fileList={fileList}
                    onPreview={this.handlePreview}
                    onChange={this.handleChange} >
                    {fileList.length >= 1 ? null : uploadButton}
                </Upload>
                <Modal maskClosable={false} visible={previewVisible} footer={null} onCancel={this.handleCancel}>
                    <img alt="example" style={{ width: '100%' }} src={previewImage} />
                </Modal>
            </div>
        );
    }
});

const Newuser = Form.create()(React.createClass({
    getInitialState() {
        return {
        	orgCodeUrl:[],
            loading: false,
            loaduser: {}, 
            visible:false
        };
    },
    handleSubmit(e) {
        e.preventDefault();
        if(!this.state.role){
        	message.warning('亲！请选择角色');
        	return false;
        };
        if(!this.state.roleState){
        	message.warning('亲！请选择角色状态');
        	return false;
        }
        let theorgCodeUrl = [];
        if (this.state.orgCodeUrl.length) {
            let picArr = [];
            this.state.orgCodeUrl.map(function (item) {
                picArr.push(item.response.data);
            });
            theorgCodeUrl = picArr.join(",");
        };
        this.setState({
            loading: true
        });
        $.ajax({
            method: "POST",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + '/api/admin/customer/addCustomer',
            data: {
            	id:this.props.datauser.id,
                uesrName:this.state.uesrName,
				role:this.state.role,
				roleState:this.state.roleState,
				customerName:this.state.customerName,
				department:this.state.department,
				post:this.state.post,
				station:this.state.station,
				phone:this.state.phone,
				email:this.state.email,
				director:this.state.theTypes,
				companyIntention:JSON.stringify(this.state.companyIntention),
            }
        }).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: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/customer/findCustomerByName",
            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,options){
		this.setState({
			auto:value
		})
	},
	blurChange(e){
		console.log(e)
		let theType='';
		let contactLists=this.state.customerArr||[];
			if (e) {
            contactLists.map(function (item) {
                if (item.name == e.toString()) {
                    theType = item.id;
                }
           });     
   	    }
		this.setState({
			theTypes:theType
		})
	},
	//值改变时请求客户名称
	httpChange(e){
		if(e.length>=2){
			this.supervisor(e); 
		}	
		this.setState({
			auto:e
		})
	},
	//查看基本详情基本信息
    loaduser(record){
    	if(record){
    	$.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + '/api/admin/customer/toUpdateBusiness',
            data: {
              businessId: record.name
            },
            success: function (data) {
                let thisData = data.data;                
                if (!thisData) {
                    if (data.error && data.error.length) {
                        message.warning(data.error[0].message);
                    };
                    thisData = {};
                }; 
                this.setState({
                	orgCodeUrl: thisData.orgCodeUrl ? splitUrl(thisData.orgCodeUrl, ',', globalConfig.avatarHost + '/upload') : [],
                	uids:thisData.uid,
                	followSituation:thisData.followSituation,
                	businessGlossoryId:thisData.businessGlossoryId,
                	customerStatus:thisData.customerStatus,
                	remarks:thisData.remarks,	
                });                  
            }.bind(this),
       }).always(function () {
            this.setState({            	
                loading: false
            });
        }.bind(this));  
       }
    },
    //重置密码
    resetPwd(e) {
        this.setState({
            loading: true
        })
        $.ajax({
            type: 'post',
            url: globalConfig.context + "/api/admin/supervise/resetPwd",
            dataType: "json",
            data: {
                id: this.state.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.setState({
            visible: false,
        });
        this.props.closeDesc(false, true);
    },
    handleCancel(e) {
        this.setState({
            visible: false,
        });
        this.props.closeDesc(false);
    },
    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;
    },
    componentWillReceiveProps(nextProps) {
    	this.state.visible = nextProps.showDesc;
    	this.state.Detaile=nextProps.userDetaile;
		if(!nextProps.userDetaile){
			this.state.uesrName='';
			this.state.role=undefined;
			this.state.roleState=undefined;
			this.state.customerName='';
			this.state.department=undefined;
			this.state.post=undefined;
			this.state.station=undefined;
			this.state.phone='';
			this.state.email='';
			this.state.auto='';
			this.state.companyIntention=[];
			this.state.orgCodeUrl=[];
   		}else{
    		this.loaduser(nextProps.datauser)
    	   }     
      },
    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>
				     )
        return (
        <div>
           <Modal maskClosable={false} visible={this.state.visible}
                        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.uesrName}
					                                    onChange={(e)=>{this.setState({uesrName:e.target.value})}} required="required" style={{width:'200px'}}/>
					                                <span className="mandatory">*</span>
						                    </FormItem>
						                    {this.props.userDetaile?
						                    	<Popconfirm
			                                        title={"用户 [ " + this.state.name + " ] 的密码将会重置为123456，确认操作？"}
			                                        onConfirm={this.resetPwd}
			                                        okText="确认"
			                                        cancelText="取消"
			                                        placement="topLeft">
			                                        <Button>重置密码</Button>
			                                    </Popconfirm>:''}
					                    </div>
					                    <FormItem className="half-item" 
					                          {...formItemLayout}
					                           label="用户角色"
					                         > 
												  <Select placeholder="选择用户角色" value={this.state.role}
												    onChange={(e)=>{this.setState({role:e})}} style={{width:'200px'}}>
					                                {
					                                    socialAttribute.map(function (item) {
					                                        return <Select.Option key={item.value} >{item.key}</Select.Option>
					                                    })
					                                }
					                              </Select>
					                              <span className="mandatory">*</span>
			                   		    </FormItem>
			                   		    {this.props.userDetaile?<FormItem className="half-item"
						                            {...formItemLayout}
						                            label="用户状态" >   
					                                    <Select placeholder="用户状态" value={this.state.roleState} style={{width:'200px'}}
												          onChange={(e)=>{this.setState({roleState:e})}} > 
					                                      {
					                                      socialAttribute.map(function (item) {
					                                        return <Select.Option key={item.value} >{item.key}</Select.Option>
					                                       })
					                                      }
					                                   </Select>
					                                   <span className="mandatory">*</span>
						                </FormItem>:''}
					                    <FormItem className="half-item"
					                            {...formItemLayout}
					                            label="用户姓名" >   
				                                    <Input placeholder="请输入用户姓名" style={{width:'200px'}} value={this.state.customerName}
					                                    onChange={(e)=>{this.setState({customerName:e.target.value})}} required="required"/> 
				                                    <span className="mandatory">*</span>
					                    </FormItem>
					                    <FormItem className="half-item"
					                            {...formItemLayout}
					                            label="组织部门" >   
				                                    <Input placeholder="请输入组织部门" style={{width:'200px'}} value={this.state.department}
					                                    onChange={(e)=>{this.setState({department:e.target.value})}} required="required"/> 
				                                    <span className="mandatory">*</span>
					                    </FormItem>
					                    <FormItem className="half-item" 
					                          {...formItemLayout}
					                           label="职务"
					                         > 
												  <Select placeholder="选择职务" style={{width:'200px'}} value={this.state.post} onChange={(e)=>{this.setState({post: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.station} onChange={(e)=>{this.setState({station: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.phone}
					                                    onChange={(e)=>{this.setState({phone:e.target.value})}} required="required"/> 
				                                    <span className="mandatory">*</span>
					                    </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}
											        dropdownStyle={{ width: 200 }}
											        size="large"
											        style={{ width: '200px' }}
											        dataSource={options}
											        placeholder="输入名称"
											        value={this.state.auto}
											        onChange={this.httpChange}
											        filterOption={true}
											        onBlur={this.blurChange}
											        onSelect={this.selectAuto}
											      >
											        <Input/>
											      </AutoComplete> 
											      <span className="mandatory">*</span>
							            </FormItem>
							           {this.props.userDetaile?
							           	
						                    <FormItem className="half-item"
						                            {...formItemLayout}
						                            label="用户编号" >   
						                            <span>{this.state.id}</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.companyIntention}
						                                onChange={(pids) => {
						                                    this.state.companyIntention = pids;
						                                    this.setState({
						                                        companyIntention: this.state.companyIntention
						                                    })
						                                }}
						                            >
						                                {this.state.cityOption}
						                            </Select>
						                    </FormItem>	
							            </div>
							             <div className="clearfix pictures">
						                        <FormItem
							                        labelCol={{ span: 4 }}
							                        wrapperCol={{ span: 18 }}
							                        label="用户头像" >
							                        <PicturesWall
							                            pictureSign="customer_sys_file"
							                            fileList={this.getOrgCodeUrl}
							                            pictureUrl={this.state.orgCodeUrl} />
							                            <p>图片建议：要萌。</p>
						                        </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;