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';
import {splitUrl} from '../../../tools.js';
const Option = AutoComplete.Option;
//图片组件
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 = (
            
        );
        return (
            
                
                    {fileList.length >= 1 ? null : uploadButton}
                
                
                     
                
             
        );
    }
});
const Newuser = Form.create()(React.createClass({
    getInitialState() {
        return {
        	orgCodeUrl:[],
            loading: false,
            loaduser: {}, 
            visible:false,
            datauser:[],
            role:[]
        };
    },
    getDefaultProps(){
    	return{
    		userDetaile:false
    	}
    },
    handleSubmit(e) {
        e.preventDefault();
        if(!this.state.role){
        	message.warning('请选择角色');
        	return false;
        };
        if(!this.state.status&&this.props.userDetaile){
        	message.warning('请选择角色状态');
        	return false;
        };
        if(!this.state.departmentId){
        	message.warning('请选择组织部门');
        	return false;
        };
        if(!this.state.theTypes&&!this.state.superiorId){
        	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
        });  
        let roleArrT=[];
		roleArrT.push((this.state.role).toString())
        $.ajax({
            method: "POST",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + api,
            data: {
            	roles:roleArrT,
            	data:JSON.stringify({
            		id:this.state.id?this.state.id:this.props.addId,
	                mobile:this.state.mobile,
					status:this.state.status,
					name:this.state.name,
					departmentId:this.state.departmentId,
					duty:this.state.duty,
					position:this.state.position,//岗位
					email:this.state.email,
					superiorId:this.state.theTypes?this.state.theTypes:this.state.superiorId,
					district:this.state.district,
					headPortraitUrl:theorgCodeUrl.length?theorgCodeUrl:'',
            	})
            	
            }
        }).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,options){
		this.setState({
			superior:value
		})
	},
	blurChange(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>=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 = {};
                }; 
                let roleArr=[]
                roleArr.push(this.props.role[0])
                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
                    duty:thisdata.duty?thisdata.duty:undefined,//职务
                    status:thisdata.status?thisdata.status:undefined,
                    departmentId:thisdata.departmentId?thisdata.departmentId:undefined,//部门id
                    userNo:thisdata.userNo,
                	orgCodeUrl: thisdata.headPortraitUrl? splitUrl(thisdata.headPortraitUrl, ',', globalConfig.avatarHost + '/upload') : [],
                	role:roleArr,
                });
            }.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.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(
                {item.key}
            )                    
        });
        this.state.cityOption=cityArrs;
    },
   
    componentWillReceiveProps(nextProps) {    	
		if(nextProps.userDetaile&&nextProps.datauser.id){
			this.loaduser(nextProps.datauser)
			this.setState({
				rolek:nextProps.role
			})
   		}else{
    		this.state.name='';
			this.state.role=[];
			this.state.departmentId=undefined;
			this.state.mobile='';
			this.state.duty=undefined;
			this.state.position=undefined;
			this.state.station=undefined;
			this.state.email='';
			this.state.superiorId='';
			this.state.superior='';
			this.state.district=[];
			this.state.orgCodeUrl=[];
			this.state.id='';
			this.state.rolek=[];
    	   } 
		   this.state.visible = nextProps.showDesc;
		   
      },
    render() {
        const FormItem = Form.Item
        const formItemLayout = {
            labelCol: { span: 8 },
            wrapperCol: { span: 14 },
        };  
        const dataSources=this.state.customerArr || [];
        const options = dataSources.map((group,index) =>
				      {group.name}
				     )
        const departmentArr=this.props.departmentArr || [];
        const roleArrS=this.props.roleArr || [];
        const rolst=this.state.rolek || [];
        return (
        
        )
    }
}));
export default Newuser;