import React from 'react';
import { Tabs, Table, Icon, Tooltip, Modal, message, AutoComplete, Spin, DatePicker,Upload, Input, InputNumber, Select,TimePicker, Button, Radio, Form, Cascader, Tag, Switch } from 'antd';
import './myClient.less';
import ajax from 'jquery/src/ajax/xhr.js';
import moment from 'moment';
import $ from 'jquery/src/ajax';
import { areaSelect } from '../../NewDicProvinceList';
import { maturityList, innovationList, transferModeList,cityArr ,newFollow,customerStatus,intentionalService,tag} from '../../dataDic';
import { IndustryObject, getIndustryCategory } from '../../DicIndustryList.js';
import { beforeUploadFile, splitUrl, companySearch, getTransferMode, getAchievementCategory, getTechAuditStatus, getDemandType, getMaturity, getInnovation,beforeUpload, getBase64,getsex,getCompanyIntention,getcityArr,getfllowSituation,getcustomerStatue} from '../../tools.js';
import throttle from '../../throttle.js';


const AchievementDetailForm = Form.create()(React.createClass({
    getInitialState() {
        return {
            loading: false,
            data: {},
            tags: [],
        };
    },

    handleSubmit(e) {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {                                 

            //意向服务多选
//          let companyMore = [];
//          if (values.companyIntention.length) {
//              let companyList = [];
//              values.companyIntention.map(function (item) {
//                  companyList.push(item);
//              });
//              companyMore = companyList.join(",");
//          };
            let yearMonth = new Date().toLocaleDateString();           
            let yearString = yearMonth.split('/').join('-');                                          	           
        	let days = new Date(); 
            let hours = parseInt(days.getHours())<10 ? "0"+days.getHours():days.getHours();            
            let minutes =parseInt(days.getMinutes())<10 ? "0"+days.getMinutes():days.getMinutes();            
            let seconds =parseInt(days.getSeconds())<10 ? "0"+days.getSeconds():days.getSeconds();           
            let	pjstringY=hours+':'+minutes+':'+seconds ; 
            let tags=''
            switch(values.tag){
            	case '科技专家':tags=0; break;
            	case '科研单位':tags=1; break;
            	case '民间达人':tags=2; break;
            }
            if (!err) {
                this.setState({
                    loading: true
                });
                
                $.ajax({
                    method: "POST",
                    dataType: "json",
                    crossDomain: false,
                    url: this.props.data.id ?  globalConfig.context + '/api/admin/customer/updCustomer' : globalConfig.context + '/api/admin/customer/addCustomer',
                    data: {
                        id: this.props.data.id, //编号
                        customerType:values.customerTyp ,//客户信息  1                                                                              
                        companyName: values.companyName,//公司名称  1
                        companyIndustry: values.companyIndustry,//公司行业  
                        companyIntention: values.companyIntention,//公司意向1
                        tag: tags,
                        locationProvince: values.locationProvince,//省份1
                        address: values.address,//详细地址1
                        remarks: values.remarks,//备注1
                        followSituation: values.followSituation,//最新跟进1
                        customerStatus: values.customerStatus,//客户状态1
                        name: values.name,//客户姓名1                        
                        mobile: values.mobile,//座机1
                        telNum: values.telNum,//手机号码1
                        sex: values.sex,//性别1
                        customerPosition: values.customerPosition,//职位1
                        wechat: values.wechat,//微信号1
                        qq: values.qq,//qq     1                 
                        depatrment: values.depatrment,//部门             1
                        email: values.email,//邮箱     1                   
                       	shareType:0,
                        followDates:yearString+' '+pjstringY,//时间,
                        primaryFlg:0,
                    }
                }).done(function (data) {
                    this.state.auditStatus = 0;
                    this.setState({
                        loading: false
                    });
                    if (!data.error.length) {
                        message.success('保存成功!');
                        this.props.handleOk();
                    } else {
                        message.warning(data.error[0].message);
                    }
                }.bind(this));
            }
        });
    },
    componentWillMount() {
        this.state.therottleSearch = throttle(this.handleSearch, 1000, { leading: false }).bind(this);
        if (this.props.data && this.props.data.id) {
            this.loadData(this.props.data.id, this.props.detailApiUrl);
        };  
    },
    componentWillReceiveProps(nextProps) {
        if (!this.props.visible && nextProps.visible) {
            if (nextProps.data && nextProps.data.id) {
                this.loadData(nextProps.data.id, nextProps.detailApiUrl);
            };
            this.state.data = {};
            this.state.tags = [];
            this.state.switchValue = false;
            this.state.radios = false;
            this.state.technicalPictureUrl = [];
            this.state.coverImg = [];
            this.state.maturityPictureUrl = [];
            this.state.textFileList = [];
            this.state.techPlanFileList = [];
            this.state.businessPlanFileList = [];
            this.props.form.resetFields();
        };
    },
   
    render() {
        const theData = this.state.data || {};
        const { getFieldDecorator } = this.props.form;
        const FormItem = Form.Item
        const formItemLayout = {
            labelCol: { span: 8 },
            wrapperCol: { span: 14 },
        };  
        let yearMonth = new Date().toLocaleDateString();           
        let yearString = yearMonth.split('/').join('-');                                          	           
    	let days = new Date(); 
        let hours = parseInt(days.getHours())<10 ? "0"+days.getHours():days.getHours();            
        let minutes =parseInt(days.getMinutes())<10 ? "0"+days.getMinutes():days.getMinutes();            
        let seconds =parseInt(days.getSeconds())<10 ? "0"+days.getSeconds():days.getSeconds();           
        let	pjstringY=hours+':'+minutes+':'+seconds ;
        const { RangePicker } = DatePicker;
        return (
            <Form horizontal onSubmit={this.handleSubmit} id="demand-form">
                <Spin spinning={this.state.loading}>
                    <div className="clearfix">
                    	<FormItem className="half-item"
		                            {...formItemLayout}
		                            label="客户类型" >
		                            {getFieldDecorator('customerTyp', {
		                                rules: [{ required: true, message: '此项为必填项!' }],
		                                initialValue: theData.customerTyp
		                            })(
		                                <Select placeholder="选择客户类型" style={{ width: 160 }} >
		                                    <Select.Option value="0" >个人客户</Select.Option>
		                                    <Select.Option value="1" >公司客户</Select.Option>
		                                    <Select.Option value="2" >团体客户</Select.Option> 
		                                </Select>
		                                )}
		                </FormItem>
                    	<div className="clearfix" style={{marginLeft:'40px',marginBottom:'20px',color:'#000000'}}>基本资料:</div>	                    	                       
                        <div>	                    	
				              <FormItem className="half-item"
		                            {...formItemLayout}
		                            label="录入时间" >	
		                            {yearString+' '+pjstringY}
			                   </FormItem> 	                    
                        </div>
                        <div className="clearfix" style={{marginLeft:'40px',marginBottom:'20px',color:'#000000'}}>公司资料:</div>	                    		                           	                                                       	                                               
                        <div>
                            <FormItem className="half-item"
	                            {...formItemLayout}
	                            label="公司名称" >
	                            {getFieldDecorator('companyName', {
	                                rules: [{ required: true, message: '此项为必填项!' }],
	                                initialValue: theData.companyName
	                            })(
	                                <Input />
	                                )}
	                        </FormItem>
	                        <FormItem className="half-item"
	                            {...formItemLayout}
	                            label="公司行业" >
	                            {getFieldDecorator('companyIndustry', {	                                
	                                initialValue: theData.companyIndustry
	                            })(
	                                <Input />
	                                )}
	                        </FormItem>	                     	                        
			                <FormItem className="half-item"
	                            {...formItemLayout}
	                            label="地区" >
	                            {getFieldDecorator('locationProvince', {
	                                initialValue: getcityArr(theData.locationProvince)
	                            })(
	                                <Select placeholder="选择地区" style={{ width: 160 }} >
	                                    {
	                                        cityArr.map(function (item) {
	                                            return <Select.Option key={item.value} >{item.key}</Select.Option>
	                                        })
	                                    }
	                                </Select>
	                                )}
	                        </FormItem>
	                        <FormItem className="half-item"
	                            {...formItemLayout}
	                            label="最新跟进" >
	                            {getFieldDecorator('followSituation', {
	                            	rules: [{ required: true, message: '此项为必填项!' }],
	                                initialValue: getfllowSituation(theData.followSituation)
	                            })(
	                                <Select placeholder="选择跟进进度" style={{ width: 160 }} >
	                                    {
	                                        newFollow.map(function (item) {
	                                            return <Select.Option key={item.value} >{item.key}</Select.Option>
	                                        })
	                                    }
	                                </Select>
	                                )}
	                        </FormItem>
	                        <FormItem className="half-item"
	                            {...formItemLayout}
	                            label="客户状态" >
	                            {getFieldDecorator('customerStatus', {
	                            	rules: [{ required: true, message: '此项为必填项!' }],
	                                initialValue: getcustomerStatue(theData.customerStatus)
	                            })(
	                                <Select placeholder="选择客户状态" style={{ width: 160 }} >
	                                    {
	                                        customerStatus.map(function (item) {
	                                            return <Select.Option key={item.value} >{item.key}</Select.Option>
	                                        })
	                                    }
	                                </Select>
	                                )}
	                        </FormItem>	                       
	                        <FormItem className="half-item"
		                            {...formItemLayout}
		                            label="详细地址" >
		                            {getFieldDecorator('address', {		                            	
		                                initialValue: theData.address
		                            })(
		                                <Input />
		                                )}
		                    </FormItem>
		                     <FormItem className="half-item"
	                            {...formItemLayout}
	                            label="标签" >
	                            {getFieldDecorator('tag', {	                            	
	                                initialValue: theData.tag
	                            })(
                               <Select placeholder="选择客户标签" >
                                    {
                                        tag.map(function (item) {
                                            return <Select.Option key={item.key} >{item.key}</Select.Option>
                                        })
                                    }
                                </Select>
	                                )}
	                        </FormItem>
	                        <div  className="clearfix" >	
		                        <FormItem className="half-item" style={{marginLeft:'80px'}}
			                         labelCol={{ span: 4 }}
			                        wrapperCol={{ span: 18 }}
			                        label="意向服务" > 
			                        {getFieldDecorator('companyIntention', {
			                            	rules: [{ required: true, message: '此项为必填项!' }],	
			                            	initialValue: theData.companyIntention
	                                })(
									    <Select placeholder="选择意向服务" style={{ width: 160 }} >
	                                    {
	                                        intentionalService.map(function (item) {
	                                            return <Select.Option key={item.value} >{item.key}</Select.Option>
	                                        })
	                                    }
	                                </Select>
	                                )}
			                    </FormItem>
		                    </div>
	                        <div  className="clearfix">		                        
				                <FormItem
			                        labelCol={{ span: 4 }}
			                        wrapperCol={{ span: 18 }}
			                        label="备注" >
			                        {getFieldDecorator('remarks', {
			                            initialValue: theData.remarks
			                        })(
			                            <Input type="textarea" rows={4} />
			                            )}
			                    </FormItem>
			                </div>
                        </div>  
                        <div className="clearfix" style={{marginLeft:'40px',marginBottom:'20px',color:'#000000'}}>联系资料:</div>
                        <div>
                        	<FormItem className="half-item"
	                            {...formItemLayout}
	                            label="姓名" >
	                            {getFieldDecorator('name', {
	                                rules: [{ required: true, message: '此项为必填项!' }],
	                                initialValue: theData.name
	                            })(
	                                <Input />
	                                )}
	                        </FormItem>
                       		<FormItem className="half-item"
	                            {...formItemLayout}
	                            label="手机号码" >
	                            {getFieldDecorator('telNum', {	
	                            	rules: [{ required: true, message: '此项为必填项!' }],
	                                initialValue: theData.telNum 
	                            })(
	                                <Input />
	                                )}
	                        </FormItem>	                        
	                        <FormItem className="half-item"
                                {...formItemLayout}
                                label="性别" >
                                {getFieldDecorator('sex', {                                	
                                    initialValue: getsex(theData.sex)
                                })(
                                    <Radio.Group>
                                        <Radio value="0">男</Radio>
                                        <Radio value="1">女</Radio>
                                    </Radio.Group>
                                    )}
                       		</FormItem>
	                        <FormItem className="half-item"
	                            {...formItemLayout}
	                            label="座机号" >
	                            {getFieldDecorator('mobile', {	                              
	                                initialValue: theData.mobile
	                            })(
	                                <Input />
	                                )}
	                        </FormItem>
	                        <FormItem className="half-item"
	                            {...formItemLayout}
	                            label="QQ号码" >
	                            {getFieldDecorator('qq', {	                              
	                                initialValue: theData.qq
	                            })(
	                                <Input />
	                                )}
	                        </FormItem>
	                        <FormItem className="half-item"
	                            {...formItemLayout}
	                            label="邮箱号" >
	                            {getFieldDecorator('email', {	                              
	                                initialValue: theData.email
	                            })(
	                                <Input />
	                                )}
	                        </FormItem>
	                        <FormItem className="half-item"
	                            {...formItemLayout}
	                            label="微信" >
	                            {getFieldDecorator('wechat', {	                              
	                                initialValue: theData.wechat
	                            })(
	                                <Input />
	                                )}
	                        </FormItem>
	                        <FormItem className="half-item"
	                            {...formItemLayout}
	                            label="部门" >
	                            {getFieldDecorator('depatrment', {	                              
	                                initialValue: theData.depatrment
	                            })(
	                                <Input />
	                                )}
	                        </FormItem>
	                        <FormItem className="half-item"
	                            {...formItemLayout}
	                            label="职位" >
	                            {getFieldDecorator('customerPosition', {	                              
	                                initialValue: theData.customerPosition
	                            })(
	                                <Input />
	                                )}
	                        </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.props.closeDesc}>取消</Button>
                    </FormItem>                   
                </Spin>
            </Form >
        )
    }
}));

const CustomerDetail = React.createClass({
    getInitialState() {
        return {
            visible: false,
            tabsKey: 1,
            loading: false,           
            dataSource: [],
        };
    },    
    handleCancel(e) {
        this.setState({
            visible: false,
        });
        this.props.closeDesc(false);
    },
    handleOk(e) {
        this.setState({
            visible: false,
        });
        this.props.closeDesc(false, true);
    },
    
    componentWillReceiveProps(nextProps) {
        if (!this.state.visible && nextProps.showDesc) {
            this.state.tabsKey = "1";
        };
        this.state.visible = nextProps.showDesc;
    },
    render() {
        
            return (
                <div className="patent-desc">
                    <Modal maskClosable={false} visible={this.state.visible}
                        onOk={this.checkPatentProcess} onCancel={this.handleCancel}
                        width='1000px'
                        title='新建客户'                       
                        footer=''
                        className="admin-desc-content">
                        <Spin spinning={this.state.loading}>               
                            <AchievementDetailForm
                                data={this.props.data}                               
                                closeDesc={this.handleCancel}
                                visible={this.state.visible}
                                handleOk={this.handleOk} />
                        </Spin>
                    </Modal>
                </div>
            );        
    },
});


export default CustomerDetail;