import React from 'react';
import $ from 'jquery/src/ajax';
import {
	Icon,
	Tabs,
	Table,
	Tooltip,
	Modal,
	Popover,
	message,
	Spin,
	Upload,
	Input,
	InputNumber,
	Select,
	DatePicker,
	Button,
	Radio,
	Form,
	Cascader,
    Tag,
    Checkbox,
    Row,
    Col
} from 'antd';
import { getTechField } from '@/DicTechFieldList.js';
import {areaSelect } from '@/NewDicProvinceList';
import { IndustryObject, getIndustryCategory } from '@/DicIndustryList.js';
import { beforeUploadFile, splitUrl, companySearch, getDemandType, getAchievementCategory } from '@/tools.js';


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 className="clearfix">
				<Upload
					action={globalConfig.context + '/api/user/demand/uploadPicture'}
					data={{ sign: 'demand_picture', uid: this.props.uid }}
					listType="picture-card"
					fileList={fileList}
					onPreview={this.handlePreview}
					onChange={this.handleChange}
				>
					{fileList.length >= 5 ? null : uploadButton}
				</Upload>
				<Modal maskClosable={false} visible={previewVisible} footer={null} onCancel={this.handleCancel}>
					<img alt="example" style={{ width: '100%' }} src={previewImage} />
				</Modal>
			</div>
		);
	}
});
const DemandForm = Form.create()(
	React.createClass({
		getInitialState() {
			return {
				visible: false,
				loading: false,
				auditStatus: 0,
				textFileList: [],
				videoFileList: [],
				pictureUrl: [],
                tags: [],
                ProvinceCity:[]
			};
		},
		loadData(id) {
			this.setState({
				loading: true
			});
			$.ajax({
				method: 'get',
				dataType: 'json',
				crossDomain: false,
				url:
					globalConfig.context +
					(window.userData.type == '1'
						? '/api/user/demand/orgDemandDetail'
						: '/api/user/demand/userDemandDetail'),
				data: {
					id: id
				},
				success: function(data) {
					let thisData = data.data;
					if (!thisData) {
						if (data.error && data.error.length) {
							message.warning(data.error[0].message);
						}
						thisData = {};
					}
					this.setState({
						data: thisData,
						tags: thisData.keyword ? thisData.keyword.split(',') : [],
						pictureUrl: thisData.pictureUrl
							? splitUrl(thisData.pictureUrl, ',', globalConfig.avatarHost + '/upload')
							: []
					});
				}.bind(this)
			}).always(
				function() {
					this.setState({
						loading: false
					});
				}.bind(this)
			);
		},
		getTagsArr(e) {
			this.setState({ tags: e });
		},
		getPictureUrl(e) {
			this.setState({ pictureUrl: e });
		},
		handleSubmit(e) {
			e.preventDefault();
			this.props.form.validateFields((err, values) => {
				//keyword长度判断
				if (this.state.tags.length < 3) {
					message.warning('关键词数量不能小于3个！');
					return;
				}
				//url转化
				let thePictureUrl = [];
				if (this.state.pictureUrl.length) {
					let picArr = [];
					this.state.pictureUrl.map(function(item) {
						if (item.response && item.response.data && item.response.data.length) {
							picArr.push(item.response.data);
						}
					});
					thePictureUrl = picArr.join(',');
				}
				if (!err) {
					this.setState({
						loading: true
					});
					$.ajax({
						method: 'POST',
						dataType: 'json',
						crossDomain: false,
						url: this.props.data.id
							? globalConfig.context + '/api/user/demand/update'
							: globalConfig.context + '/api/user/demand/apply',
						data: {
							id: this.props.data.id,
							dataCategory: Number(window.userData.type),
							serialNumber: this.props.data.serialNumber,
							name: values.name,
							keyword: this.state.tags ? this.state.tags.join(',') : [],
							keywords: this.state.tags,
							infoSources: 1,
							industryCategoryA: values.industryCategory ? values.industryCategory[0] : undefined,
							industryCategoryB: values.industryCategory ? values.industryCategory[1] : undefined,
							demandType: values.demandType,
							problemDes: values.problemDes,
							technicalRequirements: values.technicalRequirements,
							pictureUrl: thePictureUrl,
							textFileUrl: this.state.textFileUrl,
							videoUrl: values.videoUrl,
							fixedBudget: values.fixedBudget,
							fixedCycle: values.fixedCycle,
							peopleNumber: values.peopleNumber,
							fixedScheme: values.fixedScheme,
							costEscrow: values.costEscrow,
							budgetCost: values.budgetCost,
							employerId: values.employerId || this.state.data.employerId,
							releaseStatus: values.releaseStatus,
							principalId: values.principalId,
							validityPeriodFormattedDate: values.validityPeriod
								? values.validityPeriod.format('YYYY-MM-DD')
								: undefined,
							//
							contacts: values.contacts,
							status: this.state.status,
							auditStatus: this.state.auditStatus
						}
					}).done(
						function(data) {
							this.state.auditStatus = 0;
							this.setState({
								loading: false
							});
							if (!data.error.length) {
								message.success('保存成功！');
								this.setState({
									visible: false
								});
								this.props.handleOk();
							} else {
								message.warning(data.error[0].message);
							}
						}.bind(this)
					);
				}
			});
		},
		componentWillMount() {
			if (this.props.data.id) {
				this.loadData(this.props.data.id);
			} else {
				this.state.data = {};
			}
		},
		componentWillReceiveProps(nextProps) {
                this.state.textFileList = [];
                this.state.videoFileList = [];
				if (nextProps.data.id) {
					this.loadData(nextProps.data.id);
				} else {
					this.state.data = {};
					this.state.pictureUrl = [];
                }
				this.props.form.resetFields();
		},
		render() {
			const theData = this.state.data || {};
            const { getFieldDecorator, getFieldsError, getFieldError, isFieldTouched } = this.props.form;
			const FormItem = Form.Item;
			const formItemLayout = {
				labelCol: { span: 6 },
				wrapperCol: { span: 12 }
			};
			return (
				<Form layout="horizontal" onSubmit={this.handleSubmit} id="demand-form">
					<Spin spinning={this.state.loading}>
						<div className="clearfix">
							<FormItem labelCol={{ span: 3 }} wrapperCol={{ span: 18 }} label="发个需求吧">
								{getFieldDecorator('problemDes', {
									rules: [ { required: true, message: '此项为必填项!' } ],
									initialValue: theData.problemDes
								})(<Input type="textarea" rows={4} placeholder="亲,发个需求吧！让技术专家主动找到您." />)}
							</FormItem>
							<FormItem className="half-item" {...formItemLayout} label="标题">
								{getFieldDecorator('name', {
									rules: [ { required: true, message: '此项为必填项!' } ],
									initialValue: theData.name
								})(<Input placeholder="给您的需求配个标题吧." />)}
							</FormItem>
						</div>
						
						<FormItem labelCol={{ span: 3 }} wrapperCol={{ span: 18 }} label="行业领域">
							{getFieldDecorator('industryCategory', {
								rules: [ { type: 'array', required: true, message: '此项为必填项!' } ],
								initialValue: [ theData.industryCategoryA, theData.industryCategoryB ]
							})(<Cascader style={{ width: 300 }} options={IndustryObject} placeholder="请选择一个行业" />)}
						</FormItem>
						<div className="clearfix">
							<FormItem className="half-item" {...formItemLayout} label="需求类型">
									<Select style={{ width: 160 }} placeholder="请选择需求类型"
                                        value={this.state.demandType} onChange={(e)=>{this.setState({demandType:e})}}
                                        >
										<Select.Option value="0" >人才需求</Select.Option>
                                        <Select.Option value="1" >资金需求</Select.Option>
									</Select>
							</FormItem>
                            {this.state.demandType=='0'&&
                                <FormItem className="half-item" {...formItemLayout} label="人才需求酬劳">
								{getFieldDecorator('name', {
									rules: [ { required: false } ],
									initialValue: theData.namea
								})(<Input placeholder="请输入酬劳." />)}
							</FormItem>}
                            {this.state.demandType=='1'&&<div className="clearfix"><FormItem className="half-item" {...formItemLayout} label="资金需求额度">
								{getFieldDecorator('name', {
									rules: [ { required: false } ],
									initialValue: theData.namea
								})(<Input placeholder="请输入资金需求额度." />)}
							</FormItem>
                            <FormItem className="half-item" {...formItemLayout} label="资金用途">
								{getFieldDecorator('namea', {
									rules: [ { required: false } ],
									initialValue: theData.namea
								})(
                                    <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>
                            }
						</div>
                        <p style={{marginLeft:40,fontSize:18,marginBottom:15}}>您还可以说明</p>
                        <div className="clearfix">
                            <FormItem className="half-item" {...formItemLayout} label="加急">
                                <Radio.Group value={this.state.urgent} onChange={(e)=>{this.setState({urgent:e.target.value})}}>
                                    <Radio value={1}>加急需求</Radio>
                                    <Radio value={0}>非加急需求</Radio>
                                </Radio.Group>
                            </FormItem>
                            {this.state.urgent&&<FormItem className="half-item" {...formItemLayout} label="日期">
								{getFieldDecorator('validitytime', {
									initialValue: theData.validitytime ? moment(theData.validitytime) : null
								})(<DatePicker />)}
							</FormItem>}
						</div>
						<div className="clearfix">
							<FormItem className="half-item" {...formItemLayout} label="悬赏需求">
                                <Radio.Group value={this.state.offer} onChange={(e)=>{this.setState({offer:e.target.value})}}>
                                    <Radio value={0}>否</Radio>
                                    <Radio value={1}>是</Radio>
                                </Radio.Group>
							</FormItem>
                            {this.state.offer>=1&&<FormItem className="half-item" {...formItemLayout} label="悬赏金额">
								{getFieldDecorator('budgetCost', {
									initialValue: theData.budgetCost
								})(<InputNumber min={0} max={999999} step={0.01} placeholder="输入金额."/>)}
								<span style={{ marginLeft: '20px' }}>万元</span>
							</FormItem>}
						</div>
                        <div className="clearfix">
                            <FormItem className="half-item" {...formItemLayout} label="热点需求">
                                <Radio.Group value={this.state.hotDemand} onChange={(e)=>{this.setState({hotDemand:e.target.value})}}>
                                    <Radio value={0}>否</Radio>
                                    <Radio value={1}>是</Radio>
                                </Radio.Group>
							</FormItem>
                            <FormItem className="half-item" {...formItemLayout} label="解决">
                                <Radio.Group value={this.state.solve} onChange={(e)=>{this.setState({solve:e.target.value})}}>
                                    <Radio value={0}>否</Radio>
                                    <Radio value={1}>是</Radio>
                                </Radio.Group>
							</FormItem>
                        </div>
                        <div className="clearfix">
                            <FormItem
                                className="half-item"
                                {...formItemLayout}
                                label="地区"
                            >
                                <Cascader
                                    options={areaSelect()}
                                    value={this.state.ProvinceCity}
                                    placeholder="选择地区"
                                    onChange={(e, pre) => {
                                        this.setState({ ProvinceCity: e });
                                    }}
                                />
                            </FormItem>  
                        </div>
                        <FormItem labelCol={{ span: 3 }} wrapperCol={{ span: 18 }} label="需求文件(图片)">
							<PicturesWall
								uid={theData.employerId}
								fileList={this.getPictureUrl}
								pictureUrl={this.state.pictureUrl}
								visible={this.props.visible}
							/>
						</FormItem>
                        <div>
                            <FormItem className="half-item" {...formItemLayout} label="发布状态">
								{getFieldDecorator('releaseState', {
									rules: [ { required: false } ],
									initialValue: theData.releaseState
								})(
                                    <Select placeholder="选择发布状态" style={{ width: 160 }} >
                                        <Select.Option value="0" >草稿</Select.Option>
                                        <Select.Option value="1" >发布审核</Select.Option>
                                        <Select.Option value="2" >已发布</Select.Option>
                                        <Select.Option value="3" >发布失败</Select.Option>
                                        <Select.Option value="4" >已撤销</Select.Option>
                                    </Select>
                                )}
                            </FormItem>
                            <FormItem className="half-item" {...formItemLayout} label="发布时间">
                                    {getFieldDecorator('releaseTime', {
                                        initialValue: theData.releaseTime ? moment(theData.releaseTime) : null
                                    })(<DatePicker />)}
                            </FormItem>
                        </div>
                        <div className="clearfix">
                            <FormItem className="full-item" 
                                labelCol={{ span: 3 }}
								wrapperCol={{ span: 18 }} label="发布状态">
								{getFieldDecorator('releasePosition', {
									rules: [ { required: false } ],
									initialValue: theData.releasePosition
								})(
                                    <Checkbox.Group>
                                        <Row>
                                            <Col span={6}><Checkbox value="A">网站首页</Checkbox></Col>
                                            <Col span={6}><Checkbox value="B">网站需求主页</Checkbox></Col>
                                            <Col span={6}><Checkbox value="C">网站需求搜索页</Checkbox></Col>
                                            <Col span={6}><Checkbox value="D">APP首页</Checkbox></Col>
                                            <Col span={6}><Checkbox value="E">APP需求首页</Checkbox></Col>
                                            <Col span={6}><Checkbox value="E">APP需求搜索页</Checkbox></Col>
                                        </Row>
                                    </Checkbox.Group>
                                )}
                            </FormItem>
                        </div>
                        <div className="clearfix">
                            <FormItem wrapperCol={{ span: 12, offset: 3 }}>
                                <Button className="set-submit" type="primary" htmlType="submit">
                                    保存
                                </Button>
                                {this.props.data&&this.props.data.id&&<Button
                                    className="set-submit"
                                    type="ghost"
                                    onClick={(e) => {
                                        this.state.auditStatus = 1;
                                    }}
                                    htmlType="submit"
                                >
                                    提交审核
                                </Button>}
                                <Button className="set-submit" type="ghost" onClick={this.props.closeDesc}>
                                    取消
                                </Button>
                            </FormItem>
                        </div>
					</Spin>
				</Form>
			);
		}
	})
);
export default DemandForm;
