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 {  splitUrl, companySearch, getDemandType, getAchievementCategory } from '@/tools.js';
const FormItem =Form.Item

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 DemandDetailForm = Form.create()(React.createClass({
    getInitialState() {
        return {
            visible: false,
            loading: false,
            auditStatus: 0,
            textFileList: [],
            videoFileList: [],
            pictureUrl: [],
        };
    },
    loadData(id) {
        this.setState({
            loading: true
        });
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context +  '/api/user/demand/demandDetail' ,
            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 = {};
				};
				// let ProvinceCityArr = [];
				// let ProvinceS = thisData.locationProvince; //getprovince
				// let citys = thisData.locationCity;
				// let Areas = thisData.locationArea;
				// ProvinceCityArr.push(ProvinceS, citys, Areas);
                this.setState({
					//ProvinceCity:ProvinceCityArr,
					id:thisData.id,
					data: thisData,
					isHot:thisData.isHot,
					isUrgent:thisData.isUrgent,
					status:thisData.status,
					isHot:thisData.isHot,
                    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) => {
			console.log(values)
            //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,
                        name: values.name,
                        industryCategoryA: values.industryCategory ? values.industryCategory[0] : undefined,
                        industryCategoryB: values.industryCategory ? values.industryCategory[1] : undefined,
                        demandType: values.demandType,
                        problemDes: values.problemDes,
                      //  pictureUrl: thePictureUrl,
						crowdCost:values.crowdCost,
						budgetCost:values.budgetCost,
						urgentDays:values.urgentDays?values.urgentDays.format('YYYY-MM-DD'):undefined,
						urgentMoney:values.urgentMoney,
						auditStatus:values.auditStatus,
                        status: this.state.status,
						isUrgent: this.state.isUrgent,
						isHot:this.state.isHot,
						publishPages:JSON.stringify(values.publishPages),
						researchType:values.researchType
                    }
                }).done(function (data) {
                    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));
            }
        });
	},
	submission(record){
		this.handleSubmit();
        $.ajax({
            method: "POST",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/user/demand/deletet",
            data: {
                ids: deletedIds
            }
        }).done(function (data) {
            if (!data.error.length) {
                message.success('成功提交审核.');
                this.setState({
                    loading: false,
                });
            } else {
                message.warning(data.error[0].message);
            };
            this.loadData();
        }.bind(this));
    },
	cancelFun(){
		this.props.closeDesc();
	},
    componentWillMount() {
        if (this.props.data.id) {
            this.loadData(this.props.data.id);
        } else {
            this.state.data = {};
        };
    },
    componentWillReceiveProps(nextProps) {
        if (!this.props.visible && nextProps.visible) {
            this.state.textFileList = [];
            this.state.videoFileList = [];
            if (nextProps.data.id) {
                this.loadData(nextProps.data.id);
            } else {
				this.state.data = {};
				this.state.isUrgent=undefined;//加急需求
				this.state.isHot=undefined;//是否悬赏
				this.state.status=undefined;
                this.state.pictureUrl = [];
            };
            this.props.form.resetFields();
        };
    },
    render() {
        const theData = this.state.data || {};
        const { getFieldDecorator,getFieldsValue } = this.props.form;
        const FormItem = Form.Item
        const formItemLayout = {
            labelCol: { span: 6 },
            wrapperCol: { span: 12 },
		};
		let demandType =(getFieldsValue(['demandType']).demandType);
        return (
			<div className='login'>
			<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="需求类型">
							{getFieldDecorator('demandType', {
									rules: [ { required: true, message: '此项为必填项!' } ],
									initialValue:theData.demandType
							})(
								<Select style={{ width: 160 }} placeholder="请选择需求类型"
									>
									{this.props.demandTypeOption}
								</Select>
							)}
						</FormItem>
						{demandType=='5'||theData.demandType=='5'?
							<FormItem className="half-item" {...formItemLayout} label="人才需求酬劳">
							{getFieldDecorator('crowdCost', {
								rules: [ { required: false } ],
								initialValue: theData.crowdCost
							})(<InputNumber min={0} max={999999} step={0.01} placeholder="输入酬劳."/>)}
							<span style={{ marginLeft: '20px' }}>元/月</span>
						</FormItem>:''}
						{demandType=='3'||theData.demandType=='3'?<div className="clearfix"><FormItem className="half-item" {...formItemLayout} label="资金需求额度">
							{getFieldDecorator('budgetCost', {
								rules: [ { required: false } ],
								initialValue: theData.budgetCost
							})(<InputNumber min={0} max={999999} step={0.01} placeholder="输入资金需求额度."/>)}
							<span style={{ marginLeft: '10px' }}>万元</span>
						</FormItem>
						<FormItem className="half-item" {...formItemLayout} label="资金用途">
							{getFieldDecorator('researchType', {
								rules: [ { required: false } ],
								initialValue: theData.researchType
							})(
								<Select placeholder="选择资金用途" style={{ width: 160 }} >
									<Select.Option value="0" >研发</Select.Option>
									<Select.Option value="1" >扩大再生产</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.isUrgent} onChange={(e)=>{this.setState({isUrgent:e.target.value})}}>
								<Radio value={1}>加急</Radio>
								<Radio value={0}>非加急</Radio>
							</Radio.Group>
						</FormItem>
						{this.state.isUrgent?<div className="clearfix">
						<FormItem className="half-item" {...formItemLayout} label="日期">
							{getFieldDecorator('urgentDays', {
								initialValue: theData.urgentDays ? moment(theData.urgentDays) : null
							})(<DatePicker />)}
						</FormItem>
						<FormItem className="half-item" {...formItemLayout} label="加急金额">
							{getFieldDecorator('urgentMoney', {
								initialValue: theData.urgentMoney
							})(<InputNumber min={0} max={999999} step={0.01} placeholder="输入金额."/>)}
							<span style={{ marginLeft: '20px' }}>万元</span>
						</FormItem></div>:''}
					</div>
					<div className="clearfix">
						<FormItem className="half-item" {...formItemLayout} label="热点需求">
							<Radio.Group value={this.state.isHot} onChange={(e)=>{this.setState({isHot: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.status} onChange={(e)=>{this.setState({status:e.target.value})}}>
								<Radio value={0}>进行中</Radio>
								<Radio value={1}>未解决</Radio>
								<Radio value={2}>已解决</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('auditStatus', {
								rules: [ { required: false } ],
								initialValue: theData.auditStatus
							})(
								<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('publishPages', {
								rules: [ { required: false } ],
								initialValue: theData.publishPages
							})(
								<Checkbox.Group>
									<Row>
										<Col span={6}><Checkbox value="0">网站首页</Checkbox></Col>
										<Col span={6}><Checkbox value="1">网站需求主页</Checkbox></Col>
										<Col span={6}><Checkbox value="2">网站需求搜索页</Checkbox></Col>
										<Col span={6}><Checkbox value="3">APP首页</Checkbox></Col>
										<Col span={6}><Checkbox value="4">APP需求首页</Checkbox></Col>
										<Col span={6}><Checkbox value="5">APP需求搜索页</Checkbox></Col>
									</Row>
								</Checkbox.Group>
							)}
						</FormItem>
					</div>
					{theData.auditInfo&&<div className="clearfix">
						<FormItem labelCol={{ span: 3 }} wrapperCol={{ span: 18 }} label="审核信息">
							<span>{theData.auditInfo}</span>
						</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.submission()
								}}
								htmlType="submit"
							>
								提交审核
							</Button>}
							<Button className="set-submit" type="ghost" onClick={this.cancelFun}>
								取消
							</Button>
						</FormItem>
					</div>
				</Spin>
			</Form>    
		</div>
        )
    }
}));
export default DemandDetailForm;




