import React from 'react';
import { Radio, Icon, Button, AutoComplete, Cascader, layout, Input, Select, Tabs, Spin, Popconfirm, Popover, Table, Switch, message, DatePicker, Modal, Upload, Form, Row, Col, TimePicker } from 'antd';
import ajax from 'jquery/src/ajax/xhr.js';
import $ from 'jquery/src/ajax';
import moment from 'moment';
import { citySelect, provinceList, areaSelect } from '@/NewDicProvinceList';
import { socialAttribute, industry, newFollow, auditStatusL, lvl, currentMember, cityArr, statuslist, customerStatus, intentionalService, sex } from '@/dataDic.js';
import { getCompanyIntention, splitUrl, getIndustry, getStatuslist, getAuditStatus, getContactType, getSocialAttribute, getfllowSituation, beforeUploadFile, getWhether, getcityArr, getcustomerStatue, getfllowSituationOn, getCertification, getcustomerTyp, getLvl, getCurrentMember, getprovince } from '@/tools.js';
const FormItem = Form.Item;
const monthFormat = 'YYYY/MM';
//图片组件
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/uploadCustomerImg"}
                    data={{ 'sign': '' }}
                    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 Basic = React.createClass({
	getInitialState() {
		return {
			loading: false,
			orgCodeUrl: [],
			companyLogoUrl: [],
			headPortraitUrl: [],
			positiveIdUrl: [],
			oppositeIdUrl: []
		}
	},
	loadInformation(record) {
		this.setState({
			loading: true
		});
		$.ajax({
			method: "get",
			dataType: "json",
			crossDomain: false,
			url: globalConfig.context + '/api/admin/customer/findPersonalCustomerDetail',
			data: {
				uid: record
			},
			success: function(data) {
				let thisData = data.data;
				if(!thisData) {
					if(data.error && data.error.length) {
						message.warning(data.error[0].message);
					};
					thisData = {};
				};
				let ProvinceCityArr = [];
				let ProvinceS = thisData.province; //getprovince
				let citys = thisData.city;
				let Areas = thisData.area;
				ProvinceCityArr.push(ProvinceS, citys, Areas);
				let month = thisData.dateOfBirthYear ? thisData.dateOfBirthYear + '/' + thisData.dateOfBirthMonth : undefined;
				this.setState({
					InformationId: thisData.id,
					InformationUid: thisData.uid,
					identifyName: thisData.identifyName,
					listed: thisData.listed,
					highTechZone: thisData.highTechZone,
					headPortraitUrl: thisData.headPortraitUrl ? splitUrl(thisData.headPortraitUrl, ',', globalConfig.avatarHost + '/upload') : [],
					positiveIdUrl: thisData.positiveIdUrl ? splitUrl(thisData.positiveIdUrl, ',', globalConfig.avatarHost + '/upload') : [],
					oppositeIdUrl: thisData.oppositeIdUrl ? splitUrl(thisData.oppositeIdUrl, ',', globalConfig.avatarHost + '/upload') : [],
					dataInformation: thisData,
					idNumber: thisData.idNumber,
					contacts: thisData.contacts,
					contactMobile: thisData.contactMobile,
					ProvinceCity: ProvinceCityArr[0]!=null?ProvinceCityArr:undefined,
					industry: thisData.industry ? String(thisData.industry) : undefined,
					societyTag: thisData.societyTag||undefined,
					sex: thisData.sex,
					yearMonth: month,
					postalAddress: thisData.postalAddress,
					fixedTel: thisData.fixedTel,
					consultationPrice: thisData.consultationPrice,
					email: thisData.email,
					qq: thisData.qq,
					introduction: thisData.introduction,
					expert: thisData.expert,
					celebrity: thisData.celebrity,
					consultant: thisData.consultant,
					international: thisData.international,
					investment: thisData.investment,
					professionalTitle: thisData.professionalTitle,
					workUnit: thisData.workUnit,
					education: thisData.education,
					graduateSchool: thisData.graduateSchool,
					majorCategory: thisData.majorCategory,
					qualification: thisData.qualification,
					businessAudit: thisData.businessAudit,
					auditStatus: thisData.auditStatus ? String(thisData.auditStatus) : undefined,
				});
			}.bind(this),
		}).always(function() {
			this.setState({
				loading: false
			});
		}.bind(this));
	},
	//图片
	getOrgCodeUrl(e) {
		this.setState({
			orgCodeUrl: e
		});
	},
	getCompanyLogoUrl(e) {
		this.setState({
			companyLogoUrl: e
		});
	},
	//基本信息提交
	newSubmit(e) {
		e.preventDefault();
		if(!this.state.industry) {
			message.warning('请选择行业');
			return false;
		};
		if(!this.state.societyTag) {
			message.warning('请选择社会性质');
			return false;
		};
		if(!this.state.ProvinceCity[1]) {
			message.warning('请选择地区');
			return false;
		};
		var reg = /^[1-9]\d*$|^0$/;
		if(this.state.consultationPrice) {
			if(this.state.consultationPrice.length > 6) {
				message.warning('咨询费用不超过6位数');
				this.refs.consul.focus();
				return false;
			};
			if(!reg.test(this.state.consultationPrice)) {
				message.warning('咨询费用只能输入数字');
				this.refs.consul.focus();
				return false;
			}
		}

		this.state.data = [];
		this.setState({
			selectedRowKeys: [],
		});

		let theorgCodeUrl = [];
		if(this.state.headPortraitUrl.length) {
			let picArr = [];
			this.state.headPortraitUrl.map(function(item) {
				if(item.response && item.response.data && item.response.data.length) {
					picArr.push(item.response.data);
				}
			});
			theorgCodeUrl = picArr.join(",");
		};
		let thecompanyLogoUrl = [];
		if(this.state.positiveIdUrl.length) {
			let picArr = [];
			this.state.positiveIdUrl.map(function(item) {
				if(item.response && item.response.data && item.response.data.length) {
					picArr.push(item.response.data);
				}
			});
			thecompanyLogoUrl = picArr.join(",");
		};
		let thecompanyLogoUrls = [];
		if(this.state.oppositeIdUrl.length) {
			let picArr = [];
			this.state.oppositeIdUrl.map(function(item) {
				if(item.response && item.response.data && item.response.data.length) {
					picArr.push(item.response.data);
				}
			});
			thecompanyLogoUrls = picArr.join(",");
		};

		let years = [];
		let yearMonth = this.state.yearMonth != undefined ? new Date(this.state.yearMonth).toLocaleDateString() : '';
		years = yearMonth.split('/');
		this.setState({
			loading: true
		});
		$.ajax({
			method: "post",
			dataType: "json",
			url: globalConfig.context + '/api/admin/customer/updatePersonalCustomer',
			data: {
				id: this.state.InformationId,
				uid: this.state.InformationUid,
				societyTag: this.state.societyTag,
				identifyName: this.state.identifyName,
				industry: this.state.industry,
				dateOfBirthYear: years[0], //出生年
				dateOfBirthMonth: years[1], //出生月
				province: (this.state.ProvinceCity)[0], //省-
				city: (this.state.ProvinceCity)[1], //市
				area: (this.state.ProvinceCity)[2], //区
				sex: this.state.sex,
				expert: this.state.expert,
				celebrity: this.state.celebrity,
				consultant: this.state.consultant,
				international: this.state.international,
				fixedTel: this.state.fixedTel,
				consultationPrice: this.state.consultationPrice ? this.state.consultationPrice : '',
				qq: this.state.qq,
				contacts: this.state.contacts,
				contactMobile: this.state.contactMobile,
				idNumber: this.state.idNumber,
				email: this.state.email,
				isMember: this.state.isMember,
				postalAddress: this.state.postalAddress,
				introduction: this.state.introduction,
				positiveIdUrl: thecompanyLogoUrl.length != 0 ? thecompanyLogoUrl : '',
				oppositeIdUrl: thecompanyLogoUrls.length != 0 ? thecompanyLogoUrls : '',
				headPortraitUrl: theorgCodeUrl.length != 0 ? theorgCodeUrl : '',
				investment: this.state.investment,
				professionalTitle: this.state.professionalTitle,
				workUnit: this.state.workUnit,
				education: this.state.education,
				graduateSchool: this.state.graduateSchool,
				majorCategory: this.state.majorCategory,
				qualification: this.state.qualification,
				businessAudit: this.state.businessAudit,
				auditStatus: this.state.auditStatus,
			}
		}).done(function(data) {
			this.setState({
				loading: false
			});
			if(!data.error.length) {
				message.success('保存成功！');
				this.props.closeDetail(false, true)
			} else {
				message.warning(data.error[0].message);
			}
		}.bind(this));

	},
	//取消
	detailsModal() {
		this.props.closeDetail(false, false)
	},
	getHeadPortraitUrl(e) {
		this.setState({ headPortraitUrl: e });
	},
	getPositiveIdUrl(e) {
		this.setState({ positiveIdUrl: e });
	},
	getOppositeIdUrl(e) {
		this.setState({ oppositeIdUrl: e });
	},
	componentWillMount() {
		this.loadInformation(this.props.data.id)
	},
	componentWillReceiveProps(nextProps) {
		if(nextProps.data && nextProps.basicState) {
			this.loadInformation(nextProps.data.id)
		}
	},
	render() {
		const {
			RangePicker,
			MonthPicker
		} = DatePicker;
		const formItemLayout = {
			labelCol: {
				span: 8
			},
			wrapperCol: {
				span: 14
			},
		};
		return(
			<div>
				 <Form layout="horizontal" onSubmit={this.newSubmit} id="demand-form">
	                <Spin spinning={this.state.loading}>
		               	<div className="clearfix" >
	                    	<FormItem className="half-item"
			                     {...formItemLayout}
			                    label="客户姓名"
		                        >
	                    	 <span>{this.state.identifyName}</span>
		                    </FormItem>
	                    </div>
	                    <div className="clearfix" >
	                    	<FormItem className="half-item" 
	                          {...formItemLayout}
	                         label="行业">
							    <Select placeholder="选择行业" value={this.state.industry}  style={{width:'300px'}}
							    				onChange={(e)=>{this.setState({industry:e})}}>
                                      {
                                        industry.map(function (item) {
                                            return <Select.Option key={item.value} >{item.key}</Select.Option>
                                        })
                                      }
                                </Select>
                                <span style={{color:'red',marginLeft:'15px'}}>*</span>
	                   		 </FormItem>
	                   		 <FormItem className="half-item" 
	                            {...formItemLayout}
	                           label="社会属性"
	                           > 
								    <Select placeholder="客户社会属性" value={this.state.societyTag}  style={{width:'300px'}}
							    				onChange={(e)=>{this.setState({societyTag:e})}}> 
                                     {
                                        socialAttribute.map(function (item) {
                                            return <Select.Option key={item.value} >{item.key}</Select.Option>
                                        })
                                    }
                                </Select>  
                                <span style={{color:'red',marginLeft:'15px'}}>*</span>
	                   		 </FormItem>
	                   		 <FormItem className="half-item" 
	                            {...formItemLayout}
	                           label="省-市-区"
	                          > 
	                            <Cascader options={areaSelect()}  value={this.state.ProvinceCity} placeholder="选择城市" style={{width:'300px'}}
									onChange={(e,pre) => { this.setState({ ProvinceCity: e }) }} />
									<span style={{color:'red',marginLeft:'15px'}}>*</span>
		                    </FormItem>
	                   		 <FormItem className="half-item" 
		                           {...formItemLayout}
		                           label="出生日期"
	                          > 
	                              {!this.state.yearMonth?<MonthPicker placeholder="选择出生年月" value={this.state.yearMonth} onChange={(time) => {this.setState({yearMonth: time});}}/>	   	 
		                          :<MonthPicker value={moment(this.state.yearMonth, monthFormat)} format={monthFormat} onChange={(time) => {this.setState({yearMonth: time});}}/>
		                    	}
		                    </FormItem>
		                     <FormItem className="half-item" 
			                    	 {...formItemLayout}
			                        label="身份证号码"
	                           	 >
		                            <Input placeholder="身份证号码" value={this.state.idNumber} onChange={(e) => {
				                        this.setState({ idNumber:  e.target.value })}}/>
		                     </FormItem>
							<FormItem className="half-item" 
			                    	 {...formItemLayout}
			                        label="主要联系人"
	                           	 >
		                            <Input placeholder="主要联系人" value={this.state.contacts} onChange={(e) => {
				                        this.setState({ contacts:  e.target.value })}}/>
		                    </FormItem>
		                    <FormItem className="half-item" 
			                    	 {...formItemLayout}
			                        label="主要联系人号码"
	                           	 >
		                            <Input placeholder="主要联系人号码" value={this.state.contactMobile} onChange={(e) => {
				                        this.setState({ contactMobile:  e.target.value })}}/>
		                    </FormItem>
		                    <div className="clearfix">
			                    <FormItem className="half-item" 
				                    	 {...formItemLayout}
				                        label="职称名字"
		                           	 >
			                            <Input placeholder="职称名字" value={this.state.professionalTitle} onChange={(e) => {
					                        this.setState({ professionalTitle:  e.target.value })}}/>
			                    </FormItem>
			                    <FormItem className="half-item" 
				                    	 {...formItemLayout}
				                        label="就业单位"
		                           	 >
			                            <Input placeholder="就业单位" value={this.state.workUnit} onChange={(e) => {
					                        this.setState({ workUnit:  e.target.value })}}/>
			                    </FormItem>
			                    <FormItem className="half-item" 
				                    	 {...formItemLayout}
				                        label="学历"
		                           	 >
			                            <Input placeholder="学历" value={this.state.education} onChange={(e) => {
					                        this.setState({ education:  e.target.value })}}/>
			                    </FormItem>
			                    <FormItem className="half-item" 
				                    	 {...formItemLayout}
				                        label="毕业院校"
		                           	 >
			                            <Input placeholder="学历" value={this.state.graduateSchool} onChange={(e) => {
					                        this.setState({ graduateSchool:  e.target.value })}}/>
			                    </FormItem>
			                    <FormItem className="half-item" 
				                    	 {...formItemLayout}
				                        label="专业类别"
		                           	 >
			                            <Input placeholder="专业类别" value={this.state.majorCategory} onChange={(e) => {
					                        this.setState({ majorCategory:  e.target.value })}}/>
			                    </FormItem>
			                    <FormItem className="half-item" 
				                    	 {...formItemLayout}
				                        label="职业资格"
		                           	 >
			                            <Input placeholder="职业资格" value={this.state.qualification} onChange={(e) => {
					                        this.setState({ qualification:  e.target.value })}}/>
			                    </FormItem>
			                    <FormItem className="half-item"
				                    	 {...formItemLayout}
				                         label="通信地址"
			                            >
			                                <Input placeholder="客户通信地址" value={this.state.postalAddress} 
										onChange={(e,pre) => { this.setState({ postalAddress: e.target.value }) }}/>
			                    </FormItem>
			                    <FormItem className="half-item"
				                    	 {...formItemLayout}
				                         label="固定电话"
			                            >
			                                <Input placeholder="客户固定电话" value={this.state.fixedTel} 
										onChange={(e) => { this.setState({ fixedTel: e.target.value }) }}/>
			                    </FormItem>
			                    <FormItem className="half-item"
				                    	 {...formItemLayout}
				                         label="客户QQ"
			                            >
			                                <Input placeholder="客户QQ" value={this.state.qq} 
										onChange={(e) => { this.setState({ qq: e.target.value })}}/>
			                    </FormItem>
			                    <FormItem className="half-item"
				                    	 {...formItemLayout}
				                         label="电子邮箱"
			                            >
			                                <Input placeholder="客户电子邮箱" value={this.state.email} 
										onChange={(e) => {this.setState({email: e.target.value })}}/>
			                    </FormItem>
			                    <FormItem className="half-item"
				                    	 {...formItemLayout}
				                         label="咨询费用"
			                            >
			                                <Input ref='consul' placeholder="请输入咨询费用" value={this.state.consultationPrice} 
										onChange={(e) => {this.setState({consultationPrice: e.target.value })}}/>
			                    </FormItem>
			                </div>
		                    <div className="clearfix">
		                   		 <FormItem className="half-item" 
			                            {...formItemLayout}
			                           label="性别"
			                         > 
			                   		 <Radio.Group value={this.state.sex} onChange={(e) => {
					                        this.setState({sex:e.target.value})
					                    }}>
					                        <Radio value={'男'}>男</Radio>
					                        <Radio value={'女'}>女</Radio>
					                  </Radio.Group>
		                   		 </FormItem>
	                   		 </div>
		                    <div className='clearfix'>
			                    <FormItem
			                        labelCol={{ span:4 }}
			                        wrapperCol={{ span: 18 }}
			                        label="客户简介" >
			                            <Input type="textarea" rows={4} value={this.state.introduction} 
									onChange={(e,pre) => { this.setState({ introduction: e.target.value })}}/>
			                    </FormItem>
		                    </div>
		                    <div className="clearfix pictures">
		                        <FormItem style={{display:'inline-block',width:'350px',marginTop:'20px',marginLeft:'95px'}}
			                        labelCol={{ span: 8 }}
			                        wrapperCol={{ span: 10 }}
			                        label="身份证正面" >
			                        <PicturesWall
			                            fileList={this.getPositiveIdUrl}
			                            pictureUrl={this.state.positiveIdUrl} />
			                            <p>建议：图片要清晰。</p>
		                        </FormItem>
		                        <FormItem style={{display:'inline-block',width:'350px',marginTop:'20px'}}
			                        labelCol={{ span: 8 }}
			                        wrapperCol={{ span: 10 }}
			                        label="身份证反面" > 
			                        <PicturesWall
			                            fileList={this.getOppositeIdUrl}
			                            pictureUrl={this.state.oppositeIdUrl} />
			                            <p>建议：图片要清晰。</p>
			                    </FormItem>
			                    <FormItem style={{display:'inline-block' ,width:'350px',marginTop:'20px'}}
			                        labelCol={{ span: 8 }}
			                        wrapperCol={{ span: 10 }}
			                        label="客户照片" > 
			                        <PicturesWall
			                            fileList={this.getHeadPortraitUrl}
			                            pictureUrl={this.state.headPortraitUrl} />
			                            <p>建议：图片要清晰。</p>
			                    </FormItem>
			                </div> 
		                    <Button className="setSubmit" type="primary" htmlType="submit">保存</Button>  
	                        <Button  type="ghost" onClick={this.detailsModal}>取消</Button>
	                    </div>		                	
				    </Spin>
				</Form>		
			</div>
		)
	}
})
export default Basic;