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

const Addjurisdiction = Form.create()(React.createClass({
    getInitialState() {
        return {
            loading: false,
            visible:false
        };
    },
    //保存
    handleSubmit(e) {
    	e.preventDefault();
    	let theType;
    	if(this.props.userDetaile){
			if (!this.state.auto) {
				message.warning('请输入上级模块')
				return false;
			}
		}
    	let api=this.props.userDetaile?'/api/admin/updateById':'/api/admin/addSupPermission';
        this.props.form.validateFields((err, values) => { 
            if (!err) {
                this.setState({
                    loading: true
                });
                $.ajax({
                    method: "POST",
                    dataType: "json",
                    crossDomain: false,
                    url: globalConfig.context + api,
                    data: {
                    	id:this.state.ids,
                        name:this.state.name, //接口名称
						url:this.state.url,//接口路径
						superId:this.state.auto,//接口上级模板功能
                    }
                }).done(function (data) { 
                    this.setState({
                        loading: false
                    });
                    if (!data.error.length) {
                        message.success('保存成功！');
                        this.props.closeDesc(false,true);
                    } else {
                        message.warning(data.error[0].message);
                    }
                }.bind(this));
            }
        });
    },
    //主管初始加载(自动补全)
	supervisor(e){ 
		$.ajax({
            method: "post",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/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({
			auto:value
		})
	},
	blurChange(e){
		let theType;
		let contactLists=this.state.customerArr||[];
			if (e) {
            contactLists.map(function (item) {
                if (item.name == e.toString()) {
                    theType=true
                }else{
                	theType=false
                }
           });     
   	    }
		this.setState({
			theTypes:theType
		})
	},
	//值改变时请求客户名称
	httpChange(e){
		if(e.length>=1){
			this.supervisor(e); 
		}	
		this.setState({
			auto:e
		})
	},
	//查看基本详情基本信息
    loaduser(record){
    	if(record){
    	$.ajax({
            method: "post",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + '/api/admin/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 Times = new Date(thisData.createTime);
                let upTimes = new Date(thisData.updateTime);
                let createY=Times.getFullYear();
                let createH=Times.getHours();
                let createF=Times.getMinutes();
                let createS=Times.getSeconds();
                let createM,createD;
                if(createM<10){
                	createM='0'+Times.getMonth()
                }else{
                	createM=Times.getMonth();
                };
                if(createD<10){
                	createD='0'+Times.getDate()
                }else{
                	createD=Times.getDate();
                };
                let createTimes=createY+'-'+createM+'-'+createD+' '+createH+':'+createF+':'+createS;
                //更新时间
                let updateY=upTimes.getFullYear();
                let updateH=upTimes.getHours();
                let updateF=upTimes.getMinutes();
                let updateS=upTimes.getSeconds();
                let updateM,updateD;
                if(updateM<10){
                	updateM='0'+upTimes.getMonth()
                }else{
                	updateM=upTimes.getMonth();
                };
                if(updateD<10){
                	updateD='0'+upTimes.getDate()
                }else{
                	updateD=upTimes.getDate();
                };
                let updateTimes=updateY+'-'+updateM+'-'+updateD+' '+updateH+':'+updateF+':'+updateS;
                this.setState({
                	ids:thisData.id,
                	name:thisData.name, //接口名称
					url:thisData.url,//接口路径
					preModule:thisData.preModule,//接口上级模板功能
                	createId:thisData.createId,
                	createTime:createTimes,
                	updateTime:updateTimes,
                	autNo:thisData.autNo,
                	auto:thisData.superId,
                });                  
            }.bind(this),
       }).always(function () {
            this.setState({ 
                loading: false
            });
        }.bind(this));  
       }
    },
    handleOk(e) {
        this.setState({
            visible: false,
        });
        this.props.closeDesc(false, true);
    },
    handleCancel(e) {
        this.setState({
            visible: false,
        });
        this.props.closeDesc(false);
    },
    componentWillReceiveProps(nextProps) {
    	this.state.visible = nextProps.showDesc;
    	this.state.Detaile=nextProps.userDetaile;
		if(!nextProps.userDetaile){
			this.state.name='';
			this.state.url='';
   		}else{
    		this.loaduser(nextProps.datauser)
    	   }     
      },
    render() {
        const theData = this.state.datauser||{};
        const { getFieldDecorator } = this.props.form;
        const FormItem = Form.Item
        const formItemLayout = {
            labelCol: { span: 8 },
            wrapperCol: { span: 14 },
        }; 
        const dataSources=this.state.customerArr || [];
        const options = dataSources.map((group,index) =>
				      <Option key={index} value={group.name}>{group.name}</Option>
				     )
        return (
        <div>
           <Modal maskClosable={false} visible={this.state.visible}
                        onOk={this.handleOk} onCancel={this.handleCancel}
                        width='600px'
                        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">
				                    	<FormItem className="half-middle"
					                            {...formItemLayout}
					                            label="接口名称" >   			                           
				                                    <Input placeholder="接口名称" value={this.state.name} style={{width:'230px'}}
				                                    onChange={(e)=>{this.setState({name:e.target.value})}} required="required"/>
					                   			<span className="mandatory">*</span>
					                   </FormItem>
					                    <FormItem className="half-middle"
					                            {...formItemLayout}
					                            label="接口路径" >   
				                                    <Input placeholder="接口路径" value={this.state.url} style={{width:'230px'}}
				                                    onChange={(e)=>{this.setState({url:e.target.value})}} required="required"/>
					                    		<span className="mandatory">*</span>	
					                    </FormItem>
				                    </div>
				                    <div className="clearfix" style={{display:this.props.userDetaile?'block':'none'}}>
				                    	<FormItem className="half-middle"
					                            {...formItemLayout}
					                            label="上级功能模块" >   
				                                    <AutoComplete
											        className="certain-category-search"
											        dropdownClassName="certain-category-search-dropdown"
											        dropdownMatchSelectWidth={false}
											        dropdownStyle={{ width: 230 }}
											        size="large"
											        style={{ width: '230px' }}
											        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>
				                    	<FormItem className="half-middle"
					                            {...formItemLayout}
					                            label="权限编号" >   
					                            <span>{this.state.autNo}</span>
					                    </FormItem>
					                    <FormItem className="half-middle"
					                            {...formItemLayout}
					                            label="创建人" >   
					                            <span>{this.state.createId}</span>
					                    </FormItem>
			                   		    <FormItem className="half-middle"
					                            {...formItemLayout}
					                            label="创建时间" >   
					                            <span>{this.state.createTime}</span>
					                    </FormItem>
					                    <FormItem className="half-middle"
					                            {...formItemLayout}
					                            label="更新时间" >   
					                           <span>{this.state.updateTime}</span>
					                    </FormItem>
				                    </div>	
			                    <FormItem wrapperCol={{ span: 12, offset: 4 }} className="half-middle">
			                        <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 Addjurisdiction;