import React from 'react';
import $ from 'jquery/src/ajax';
import {
	Icon,
	Tabs,
	Table,
	Tooltip,
	Modal,
	Popover,
	message,
	Upload,
	Input,
	InputNumber,
	Select,
	DatePicker,
	Button,
	Radio,
	Form,
	Cascader,
    Tag,
    Checkbox,
    Row,
    Col
} from 'antd';

import {  splitUrl } from '@/tools.js';
import {industry} from '@/industryList';
import SpinContainer from "../../SpinContainer";

const KeyWordTagGroup = React.createClass({
    getInitialState() {
        return {
            tags: [],
            inputVisible: false,
            inputValue: ''
        };
    },
    handleClose(removedTag) {
        const tags = this.state.tags.filter(tag => tag !== removedTag);
        this.props.tagsArr(tags);
        this.setState({ tags });
    },
    showInput() {
        this.setState({ inputVisible: true }, () => this.input.focus());
    },
    handleInputChange(e) {
        this.setState({ inputValue: e.target.value });
    },
    handleInputConfirm() {
        const state = this.state;
        const inputValue = state.inputValue;
        let tags = state.tags;
        if (inputValue && tags.indexOf(inputValue) === -1 && inputValue.replace(/(^\s*)|(\s*$)/g, "").length != 0) {
            tags = [...tags, inputValue.replace(/(^\s*)|(\s*$)/g, "")];
        }
        this.props.tagsArr(tags);
        this.setState({
            tags,
            inputVisible: false,
            inputValue: '',
        });
    },
    componentWillMount() {
        this.state.tags = this.props.keyWordArr;
    },
    componentWillReceiveProps(nextProps) {
        if (this.props.keyWordArr != nextProps.keyWordArr) {
            this.state.tags = nextProps.keyWordArr;
        };
    },
    render() {
        const { tags, inputVisible, inputValue } = this.state;
        return (
            <div className="keyWord-tips">
                {tags.map((tag, index) => {
                    const isLongTag = tag.length > 10;
                    const tagElem = (
                        <Tag key={tag} closable={index !== -1} afterClose={() => this.handleClose(tag)}>
                            {isLongTag ? `${tag.slice(0, 10)}...` : tag}
                        </Tag>
                    );
                    return isLongTag ? <Tooltip title={tag}>{tagElem}</Tooltip> : tagElem;
                })}
                {inputVisible && (
                    <Input
                        ref={input => this.input = input}
                        type="text"
                        style={{ width: 78 }}
                        value={inputValue}
                        onChange={this.handleInputChange}
                        onBlur={this.handleInputConfirm}
                        onPressEnter={this.handleInputConfirm}
                    />
                )}
                {!inputVisible && <Button className="addtips" type="dashed" disabled={tags.length > 9 ? true : false} onClick={this.showInput}>+ 新关键词</Button>}
            </div>
        );
    }
});


const PicturesWall = React.createClass({
	getInitialState() {
		return {
			previewVisible: false,
			previewImage: '',
			fileList: [],
			tags: []
		};
	},
	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'}}
					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: [],
			pictureUrlMin:[],
			pictureUrl: [],
			tags:[]
        };
    },
    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 publishPagesArr = [];
				thisData.publishPages.map(item=>{
					publishPagesArr.push(item.publishPage)
				})
                this.setState({
					id:thisData.id,
					tags: thisData.keyword ? thisData.keyword.split(",") : [],
					data: thisData,
					auditStatus:thisData.auditStatus,
					publishPagesArr:publishPagesArr,
					isHot:thisData.isHot,
					isUrgent:thisData.isUrgent,
					status:thisData.status,
					isHot:thisData.isHot,
					pictureUrl: thisData.pictureUrl ? splitUrl(thisData.pictureUrl, ',', globalConfig.avatarHost + '/upload') : [],
					pictureUrlMin: thisData.pictureUrlMin ? splitUrl(thisData.pictureUrlMin, ',', 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,index) {
		e.preventDefault();
        this.props.form.validateFields((err, 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(",");
			};
			let thepictureUrlMin = [];
            if (this.state.pictureUrlMin.length) {
                let picArr = [];
                this.state.pictureUrlMin.map(function (item) {
                    if ( item.response && item.response.data && item.response.data.length ){
                        picArr.push(item.response.data);
                    }
                });
                thepictureUrlMin = picArr.join(",");
			};
			if(!this.state.tags.length){
				message.warning('请填写关键词.')
				return false;
			}
            if (!err) {
                this.setState({
                    loading: true
                });
                $.ajax({
                    method: "post",
					dataType: "json",
					async:true,
                    url: this.props.data.id ? globalConfig.context + '/api/user/demand/updateDemand' : 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.length?thePictureUrl:'',
						pictureUrlMin: thepictureUrlMin.length?thepictureUrlMin:'',
						crowdCost:values.crowdCost,
						keyword: this.state.tags ? this.state.tags.join(",") : [],
						keywords: this.state.tags,
						budgetCost:values.budgetCost?values.budgetCost:0,
						urgentDays:this.state.isUrgent?values.urgentDays:0,
						urgentMoney:this.state.isUrgent?values.urgentMoney?values.urgentMoney:0:0,
						auditStatus:index,
                        status: this.state.status,
						isUrgent: this.state.isUrgent,
						isHot:this.state.isHot,
						publishPages:values.publishPages,
						researchType:values.researchType
                    }
                }).done(function (data) {
                    this.setState({
                        loading: false
                    });
                    if (!data.error.length) {
                        message.success('操作成功!');
                        this.setState({
                            visible: false
                        });
                        this.props.handOk();
                    } else {
                        message.warning(data.error[0].message);
                    }
                }.bind(this));
            }
        });
	},
	submission(e,index){
		this.handleSubmit(e,index);
		$.ajax({
            method: "POST",
            dataType: "json",
			crossDomain: false,
			async:true,
            url: globalConfig.context + "/api/user/demand/publishDemand",
            data: {
				id: this.state.id,
				auditStatus:index
            }
        }).done(function (data) {
            if (!data.error.length) {
                this.setState({
                    loading: false,
                });
            } else {
                message.warning(data.error[0].message);
            };
        }.bind(this));
    },
	cancelFun(){
		this.props.closeDesc();
	},
    componentWillMount() {
        if (this.props.data.id) {
            this.loadData(this.props.data.id);
        } else {
			this.state.data = {};
			this.state.tags = [];
			this.state.pictureUrl=[];
			this.state.pictureUrlMin=[];
			this.setState({
				publishPagesArr:['app_demand_list','web_demand_list']
			})
        };
    },
    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.state.pictureUrlMin=[];
				this.state.tags = [];
				this.setState({
					publishPagesArr:['app_demand_list','web_demand_list']
				})
            };
			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={(e)=>{this.handleSubmit(e,0)}} id="demand-form">
				<SpinContainer 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="亲,发个需求吧!让技术专家主动找到您." 	maxLength={512}/>)}
						</FormItem>
						<FormItem className="half-item" {...formItemLayout} label="标题">
							{getFieldDecorator('name', {
								rules: [ { required: true, message: '此项为必填项!' } ],
								initialValue: theData.name
							})(<Input placeholder="给您的需求配个标题吧." maxLength={128} />)}
						</FormItem>
					</div>
					<div className="clearfix">
						<FormItem
							labelCol={{ span: 3 }}
							wrapperCol={{ span: 18 }}
							label={<span><strong style={{color:'red'}}>*</strong>关键词</span>} >
							<KeyWordTagGroup
								keyWordArr={this.state.tags}
								tagsArr={(e)=>{this.setState({tags:e})}}
								/>
						</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={industry} placeholder="请选择一个行业" />)}
					</FormItem>
					<div className="clearfix">
						<FormItem className="half-item" {...formItemLayout} label="需求类型">
							{getFieldDecorator('demandType', {
									rules: [ { required: true, message: '此项为必填项!' } ],
									initialValue:(theData.demandType||theData.demandType=='0'?theData.demandType.toString():undefined)
							})(
								<Select style={{ width: 160 }} placeholder="请选择需求类型"
									>
									{this.props.demandTypeOption}
								</Select>
							)}
						</FormItem>
						{demandType=='5'||theData.demandType=='5'?
							<FormItem className="half-item" {...formItemLayout} label="人才酬劳">
							{getFieldDecorator('budgetCost', {
								rules: [ { required: false } ],
								initialValue: theData.budgetCost?theData.budgetCost:undefined
							})(<InputNumber min={0} max={999999} step={0.01} placeholder="输入酬劳."/>)}
							<span style={{ marginLeft: '5px' }}>万元</span>
						</FormItem>:''}
						{demandType=='3'||theData.demandType=='3'?<div className="clearfix"><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: '5px' }}>万元</span>
						</FormItem>
						<FormItem className="half-item" {...formItemLayout} label="资金用途">
							{getFieldDecorator('researchType', {
								rules: [ { required: false } ],
								initialValue: theData.researchType||theData.researchType=='0'?theData.researchType.toString():undefined
							})(
								<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={0}>非加急</Radio>
								<Radio value={1}>加急</Radio>
							</Radio.Group>
						</FormItem>
						{this.state.isUrgent?<div className="clearfix">
						<FormItem className="half-item" {...formItemLayout} label="日期">
							{getFieldDecorator('urgentDays', {
								initialValue: theData.urgentDays
							})(<InputNumber min={0} max={999999} step={0} placeholder="输入天数."/>)}
							<span style={{ marginLeft: '5px' }}>天</span>
						</FormItem>
						<FormItem className="half-item" {...formItemLayout} label="加急金额">
							{getFieldDecorator('urgentMoney', {
								initialValue: theData.urgentMoney?theData.urgentMoney:undefined
							})(<InputNumber min={0} max={999999} step={0.01} placeholder="输入金额."/>)}
							<span style={{ marginLeft: '5px' }}>万元</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>
					<FormItem labelCol={{ span: 3 }} wrapperCol={{ span: 18 }} label="需求(大图)">
						<PicturesWall
							fileList={this.getPictureUrl}
							pictureUrl={this.state.pictureUrl}
							visible={this.props.visible}
						/>
					</FormItem>
					<FormItem labelCol={{ span: 3 }} wrapperCol={{ span: 18 }} label="需求(小图)">
						<PicturesWall
							fileList={(e)=>{this.setState({pictureUrlMin:e})}}
							pictureUrl={this.state.pictureUrlMin}
							visible={this.props.visible}
						/>
					</FormItem>
					<div className="clearfix">
						<FormItem className="full-item"
							labelCol={{ span: 3 }}
							wrapperCol={{ span: 18 }} label="发布位置">
							{getFieldDecorator('publishPages', {
								rules: [ { required: false } ],
								initialValue: this.state.publishPagesArr
							})(
								<Checkbox.Group>
									<Row>
										<Col span={6}><Checkbox value="web_index">网站首页</Checkbox></Col>
										<Col span={6}><Checkbox value="web_demand_main">网站需求主页</Checkbox></Col>
										<Col span={6}><Checkbox value="web_demand_list" disabled>网站需求搜索页</Checkbox></Col>
										<Col span={6}><Checkbox value="app_index">APP首页</Checkbox></Col>
										<Col span={6}><Checkbox value="app_demand_main">APP需求首页</Checkbox></Col>
										<Col span={6}><Checkbox value="app_demand_list" disabled>APP需求搜索页</Checkbox></Col>
										<Col span={6}><Checkbox value="web_demand_trading_index">知识产权交易首页</Checkbox></Col>
										<Col span={6}><Checkbox value="app_demand_trading_index">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>
							<Button
								className="set-submit"
								type="ghost"
								onClick={(e) => {
									if(this.props.data.id){
										this.submission(e,1)
									}else{
										this.handleSubmit(e,1)
									}
								}}
							>
								提交审核
							</Button>
							<Button className="set-submit" type="ghost" onClick={this.cancelFun}>
								取消
							</Button>
						</FormItem>
					</div>
				</SpinContainer>
			</Form>
		</div>
        )
    }
}));
export default DemandDetailForm;