import React from 'react';
import { Icon, Modal, Button, Form, message, AutoComplete,Input, Spin, Select, Checkbox, InputNumber, DatePicker } from 'antd';
import './contract.less';
import { companySearch } from '../../../tools.js';
import ajax from 'jquery/src/ajax/xhr.js'
import $ from 'jquery/src/ajax';
const Option = AutoComplete.Option;
const ContractAddFrom = Form.create()(React.createClass({
    getContactsList(theUid) {
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/customer/findAllContacts",
            data: {
                uid: theUid
            },
            success: function (data) {
                let theOption = [];
                if (!data.data) {
                    if (data.error && data.error.length) {
                        message.warning(data.error[0].message);
                        return;
                    };
                };
                for (let item in data.data) {
                    let theData = data.data[item];
                    theOption.push(
                        {theData.name}
                    );
                };
                this.setState({
                	//orderStatusOption:data.data,
                    //contactsOption: theOption
                });
            }.bind(this),
        });
    },
    getInitialState() {
        return {
            loading: false,
            companyOption: [],
            accelerated: 0,
            acceleratedDate: 0,
            visible: "visible"
        };
    },
    loadData(id) {
        this.setState({
            loading: true
        });
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            cache: false,
            url: globalConfig.context + "/api/admin/contract/detail",
            data: {
                id: id || this.props.data.id
            }
        }).done((data) => {
            if (!data.data) {
                if (data.error && data.error.length) {
                    message.warning(data.error[0].message);
                };
            } else {
                this.setState({
                    data: data.data,
                    patentCheck: data.data.patentNum ? true : false,
                    copyrightCheck: data.data.copyrightNum ? true : false,
                    highTechCheck: data.data.cognizanceYear ? true : false,
                    techProjectCheck: data.data.techProjectNum ? true : false,
                });
            };
        }).always(function () {
            this.setState({
                loading: false
            });
        }.bind(this));
    },
    componentWillMount() {
        let d = new Date(), _me = this, theArr = [];
        d = d.getFullYear() - 1;
        for (let i = d; i < d + 20; i++) {
            theArr.push(
                {i}
            )
        };
        this.state.yearOption = theArr;
        if (this.props.data && this.props.data.uid && this.props.data.id) {
            this.getNewWoman(this.props.data.uid);
            this.loadData(this.props.data.id);
        } else {
            this.state.data = {};
            this.state.patentCheck = false;
            this.state.copyrightCheck = false;
            this.state.highTechCheck = false;
            this.state.techProjectCheck = false;
        };
    },
    componentWillReceiveProps(nextProps) {
        if (!this.props.visible && nextProps.visible) {
            if (nextProps.data && nextProps.data.uid && nextProps.data.id) {
                this.getNewWoman(nextProps.data.uid);
                this.loadData(nextProps.data.id);
            } else {
                this.state.data = {};
                this.state.patentCheck = false;
                this.state.copyrightCheck = false;
                this.state.highTechCheck = false;
                this.state.techProjectCheck = false;
            };
            this.props.form.resetFields();
        };
    },
    //获取联系人下拉框
	getNewWoman(ids) {  
    	this.state.data = []
         $.ajax({
                method: "get",
                dataType: "json",
                crossDomain: false,
                url: globalConfig.context + "/api/admin/customer/findAllContacts",
                data:{
                   uid:ids,
                },
                success: function (data) {                	  
                		let theArr = [];
					    let thedata=data.data;
					    if (!thedata) {
		                    if (data.error && data.error.length) {
		                        message.warning(data.error[0].message);
		                    };	
		                    thedata = {}; 
		              };   
					    var contactIds=[];
				        for (let item in data.data) {
		                    let theData = data.data[item];
		                    theArr.push(
		                        {theData.name}
		                    );
		                };
						this.setState({												   						  	        	    	
		                    contactsOption: theArr, 
		                    orderStatusOptions:data.data,
	                    });
					}.bind(this),
				}).always(function () {
	            this.setState({
	                loading: false
	            });
	        }.bind(this));
	},
    handleSave(e) {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            if (!err) {
                if (!(this.state.data.uid || this.state.khId) || !this.state.contacts) {
                    message.warning('请选择一个公司和联系人!');
                    return;
                }
                if (!values.patentNum && !values.copyrightNum && !values.cognizanceYear && !values.techProjectNum) {
                    message.warning('请至少选择一个申报项目!');
                    return;
                };
 				
                this.props.spinState(true);
                $.ajax({
                    method: "POST",
                    dataType: "json",
                    crossDomain: false,
                    url: globalConfig.context + "/api/admin/contract/apply",
                    data: {
                        "uid": this.state.data.uid || this.state.khId,
                        "id": this.state.data.id,
                        "contacts": this.state.contacts, //联系人
                        "type": values.type, //合同类型
                        "depict": values.depict, // "合同描述",
                        "patentNum": this.state.patentCheck ? values.patentNum : 0,
                        "copyrightNum": this.state.copyrightCheck ? values.copyrightNum : 0,
                        "cognizanceYear": this.state.highTechCheck ? values.cognizanceYear : undefined,
                        "techProjectNum": this.state.techProjectCheck ? values.techProjectNum : 0,
                        "previousFee": values.previousFee,
                        "comment": values.comment //"备注"
                    }
                }).done(function (data) {
                    if (!data.error.length) {
                        message.success('保存成功!');
                        this.props.okClick();
                        this.props.closeModal();
                        this.props.form.resetFields();
                    } else {
                        message.warning(data.error[0].message);
                    }
                }.bind(this)).always(function () {
                    this.props.spinState(false);
                }.bind(this));
            }
        });
    },
    handleSubmit() {
        this.props.form.validateFields((err, values) => {
            if (!err) {
                if (!values.principals || !values.recordTime) {
                    message.warning('请填写审核信息!');
                    return;
                };
                if(this.state.contacts==undefined){
		  		 message.warning('请选择联系人')
		  		return false;
		  	    }
                this.props.spinState(true);
                $.ajax({
                    method: "POST",
                    dataType: "json",
                    crossDomain: false,
                    url: globalConfig.context + "/api/admin/contract/submit",
                    data: {
                        "uid": this.state.data.uid || this.state.khId,
                        "id": this.state.data.id,
                        "contacts": this.state.contacts, //联系人
                        "type": values.type, //合同类型
                        "depict": values.depict, // "合同描述",
                        "patentNum": this.state.patentCheck ? values.patentNum : 0,
                        "copyrightNum": this.state.copyrightCheck ? values.copyrightNum : 0,
                        "cognizanceYear": this.state.highTechCheck ? values.cognizanceYear : undefined,
                        "techProjectNum": this.state.techProjectCheck ? values.techProjectNum : 0,
                        "principals": values.principals,
                        "previousFee": values.previousFee,
                        "signDateFormattedDate": values.recordTime ? values.recordTime.format("YYYY-MM-DD HH:mm:ss") : undefined,
                        "comment": values.comment //"备注"
                    }
                }).done(function (data) {
                    if (!data.error.length) {
                        message.success('提交成功!');
                        this.props.okClick();
                        this.props.closeModal();
                        this.props.form.resetFields();
                    } else {
                        message.warning(data.error[0].message);
                    }
                }.bind(this)).always(function () {
                    this.props.spinState(false);
                }.bind(this));
            }
        });
    },
    //客户名称初始加载
	customerList(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));  
	},
    //值改变时请求客户名称
	httpChange(e){
			if(e.length>=2){
				this.customerList(e);
				return;
			}	 
	},
	
    //客户输入框失去焦点是判断客户是否存在
	blurChange(e){
		let theType='';
		let contactLists=this.state.customerArr||[];
			if (e) {
            contactLists.map(function (item) {
                if (item.name == e.toString()) {
                    theType = item.id;
                }
           });     
    	}
		if(!theType){
		    return message.warning('当前客户名不存在')
		};
		this.setState({
			khId:theType
		})
	},
	//选择值时值匹配及联系人函数加载
	autoChange(e){
		let theType='';
		let contactLists=this.state.customerArr||[];
			if (e) {
            contactLists.map(function (item) {
                if (item.name == e.toString()) {
                    theType = item.id;
                }
           });     
       }	
       this.getNewWoman(theType)
	},
    render() {
        const FormItem = Form.Item;
        const { getFieldDecorator } = this.props.form;
        const theData = this.state.data || {};
        const formItemLayout = {
            labelCol: { span: 6 },
            wrapperCol: { span: 14 },
        };
        const dataSources=this.state.customerArr || [];
        const options = dataSources.map((group) =>
				      
				     );
        const _me = this;
        return (
            
        );
    },
}));
const ContractAdd = React.createClass({
    getInitialState() {
        return {
            visible: false,
            loading: false
        };
    },
    showModal() {
        this.setState({
            visible: true,
            data: {}
        });
    },
    handleCancel(e) {
        this.setState({
            visible: false,
        });
        this.props.closeAdd(false);
    },
    componentWillReceiveProps(nextProps) {
        if (nextProps.showAdd && nextProps.data) {
            this.state.data = nextProps.data;
        };
        this.state.visible = nextProps.showAdd;
    },
    spinChange(e) {
        this.setState({
            loading: e
        });
    },
    render() {
        return (
            
                
                
                    
                         { this.props.closeAdd(false, true) }}
                            companyOption={this.props.companyOption}
                            authorOption={this.props.authorOption}
                            typeOption={this.props.typeOption} />
                    
                
            
        );
    },
});
export default ContractAdd;