import React from 'react';
import $ from 'jquery/src/ajax';
import {
	Icon,
	Tooltip,
	Modal,
	message,
	Spin,
	Upload,
	Input,
	Select,
	Button,
	Radio,
	Form,
	Cascader,
    Tag,
    Checkbox,
    Row,
    Col
} from 'antd';
import {industry} from '@/industryList';
import {achievementType,achievementCategoryList,maturityList,innovationList,transaction} from '@/dataDic';
import {  splitUrl} from '@/tools.js';
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: [],
			pictureUrl: [],
			pictureUrlMin:[],
			tags:[]
        };
    },
    loadData(id) {
        this.setState({
            loading: true
        });
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context +  '/api/user/achievement/achievementDetail' ,
            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({
					id:thisData.id,
					tags: thisData.keywords,
					data: thisData,
					publishPages:thisData.publishPages.length?thisData.publishPages:['app_achievement_list','web_achievement_list'],
					auditStatus:thisData.auditStatus,
					pictureUrl: thisData.technicalPictureUrl ? splitUrl(thisData.technicalPictureUrl, ',', 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/achievement/update' : globalConfig.context + '/api/user/achievement/apply',
                    data: {
                        id: this.props.data.id,
						name: values.name,
                        fieldA: values.industryCategory ? values.industryCategory[0] : undefined,
                        fieldB: values.industryCategory ? values.industryCategory[1] : undefined,
                        dataCategory: values.dataCategory,
                        category: values.category,
						technicalPictureUrl: thePictureUrl.length?thePictureUrl:'',
						pictureUrlMin: thepictureUrlMin.length?thepictureUrlMin:'',
						introduction:values.introduction,
						keyword: this.state.tags ? this.state.tags.join(",") : [],
						keywords: this.state.tags,
						maturity:values.maturity,
						innovation:values.innovation,
						transferMode:values.transferMode,
						auditStatus:index,
                        patentCase: values.patentCase,
						teamDes: values.teamDes,
						parameter: values.parameter,
						boutique: values.boutique,
						isHot:values.isHot,
						publishPages:values.publishPages,
                    }
                }).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/achievement/commit",
            data: {
				id: this.state.id,
            }
        }).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.setState({
				publishPages:['app_achievement_list','web_achievement_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.pictureUrl = [];
				this.state.pictureUrlMin=[];
				this.state.tags = [];
				this.setState({
					publishPages:['app_achievement_list','web_achievement_list']
				})
            };
			this.props.form.resetFields();
        };
    },
    render() {
        const theData = this.state.data || {};
        const { getFieldDecorator } = this.props.form;
        const FormItem = Form.Item
        const formItemLayout = {
            labelCol: { span: 6 },
            wrapperCol: { span: 12 },
		};
        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 className="half-item" {...formItemLayout} label="标题">
							{getFieldDecorator('name', {
								rules: [ { required: true, message: '此项为必填项!' } ],
								initialValue: theData.name
							})(<Input placeholder="给您的成果配个标题吧." maxLength={200}/>)}
						</FormItem>
					</div>
					<div className="clearfix">
						<FormItem labelCol={{ span: 3 }} wrapperCol={{ span: 18 }} label="发个成果吧">
							{getFieldDecorator('introduction', {
								rules: [ { required: true, message: '此项为必填项!' } ],
								initialValue: theData.introduction
							})(<Input type="textarea" rows={4}  placeholder="请详细介绍您的技术成果情况，包括但不限于：能解决什么问题、重大技术性突破、取得的奖励情况." />)}
						</FormItem>
						<FormItem labelCol={{ span: 3 }} wrapperCol={{ span: 18 }} label="知识产权情况">
							{getFieldDecorator('patentCase', {
								initialValue: theData.patentCase
							})(<Input type="textarea" rows={4} placeholder="请输入您的知识产权情况." maxLength={300}/>)}
						</FormItem>
						<FormItem labelCol={{ span: 3 }} wrapperCol={{ span: 18 }} label="技术参数">
							{getFieldDecorator('parameter', {
								initialValue: theData.parameter
							})(<Input type="textarea" rows={4} placeholder="请输入您的技术成果参数." maxLength={1024}/>)}
						</FormItem>
						<FormItem labelCol={{ span: 3 }} wrapperCol={{ span: 18 }} label="团队情况">
							{getFieldDecorator('teamDes', {
								initialValue: theData.teamDes
							})(<Input type="textarea" rows={4} placeholder="请输入您的团队情况." maxLength={300}/>)}
						</FormItem>
					</div>
					<div className="clearfix">
						<FormItem
							labelCol={{ span: 3 }}
							wrapperCol={{ span: 18 }}
							label={<span><span style={{color:'red'}}> * </span>关键词</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.fieldA, theData.fieldB ]
						})(<Cascader style={{ width: 300 }} options={industry} placeholder="请选择一个行业" />)}
					</FormItem>
					<div className="clearfix">
						<FormItem className="half-item" {...formItemLayout} label="成果类型">
							{getFieldDecorator('dataCategory', {
									rules: [ { required: true, message: '此项为必填项!' } ],
									initialValue:(theData.dataCategory||theData.dataCategory=='0'?theData.dataCategory.toString():undefined)
							})(
								<Select style={{ width: 160 }} placeholder="请选择成果类型"
									>
									{
										achievementType.map(function (item) {
											return	<Select.Option value={item.value} key={item.key}>{item.key}</Select.Option>
										})
									}
								</Select>
							)}
						</FormItem>
						<FormItem className="half-item" {...formItemLayout} label="知识产权类型">
							{getFieldDecorator('category', {
									rules: [ { required: true, message: '此项为必填项!' } ],
									initialValue:(theData.category||theData.category=='0'?theData.category.toString():undefined)
							})(
								<Select style={{ width: 160 }} placeholder="请选择知识产权类型"
									>
									{
										achievementCategoryList.map(function (item) {
											return	<Select.Option value={item.value} key={item.key}>{item.key}</Select.Option>
										})
									}
								</Select>
							)}
						</FormItem>
						<FormItem className="half-item" {...formItemLayout} label="创新度">
							{getFieldDecorator('innovation', {
									initialValue:(theData.innovation||theData.innovation=='0'?theData.innovation.toString():undefined)
							})(
								<Select style={{ width: 160 }} placeholder="请选择创新度"
									>
									{
										innovationList.map(function (item) {
											return	<Select.Option value={item.value} key={item.key}>{item.key}</Select.Option>
										})
									}
								</Select>
							)}
						</FormItem>
						<FormItem className="half-item" {...formItemLayout} label="成熟度">
							{getFieldDecorator('maturity', {
									initialValue:(theData.maturity||theData.maturity=='0'?theData.maturity.toString():undefined)
							})(
								<Select style={{ width: 160 }} placeholder="请选择成熟度"
									>
									{
										maturityList.map(function (item) {
											return	<Select.Option value={item.value} key={item.key}>{item.key}</Select.Option>
										})
									}
								</Select>
							)}
						</FormItem>
						<FormItem className="half-item" {...formItemLayout} label="交易形式">
							{getFieldDecorator('transferMode', {
								initialValue:(theData.transferMode||theData.transferMode=='0'?theData.transferMode.toString():undefined)
							})(
								<Select style={{ width: 160 }} placeholder="请选择交易形式"
									>
									{
										transaction.map(function (item) {
											return	<Select.Option value={item.value} key={item.key}>{item.key}</Select.Option>
										})
									}
								</Select>
							)}
						</FormItem>
					</div>
					<div className="clearfix">
						<FormItem labelCol={{ span: 3 }} wrapperCol={{ span: 18 }} label="成果(大图)">
							<PicturesWall
								fileList={this.getPictureUrl}
								pictureUrl={this.state.pictureUrl}
								visible={this.props.visible}
							/>
						</FormItem>
					</div>
					<div className="clearfix">
						<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>
					<div className="clearfix">
						<FormItem className="half-item" {...formItemLayout} label="精品成果">
							{getFieldDecorator('boutique', {
								initialValue: theData.boutique
							})(
								<Radio.Group>
									<Radio value={0}>非精品</Radio>
									<Radio value={1}>精品</Radio>
								</Radio.Group>
								)
							}
						</FormItem>
						<FormItem className="half-item" {...formItemLayout} label="热点成果">
							{getFieldDecorator('isHot', {
								initialValue: theData.isHot
							})(
								<Radio.Group>
									<Radio value={0}>非热点</Radio>
									<Radio value={1}>热点</Radio>
								</Radio.Group>
								)
							}
						</FormItem>
					</div>
					<div className="clearfix">
						<FormItem className="full-item"
							labelCol={{ span: 3 }}
							wrapperCol={{ span: 18 }} label="发布位置">
							{getFieldDecorator('publishPages', {
								rules: [ { required: false } ],
								initialValue: this.state.publishPages
							})(
								<Checkbox.Group>
									<Row>
										<Col span={6}><Checkbox value="web_index">网站首页</Checkbox></Col>
										<Col span={6}><Checkbox value="web_achievement_main">网站成果主页</Checkbox></Col>
										<Col span={6}><Checkbox value="web_achievement_list" disabled>网站成果搜索页</Checkbox></Col>
										<Col span={6}><Checkbox value="app_index">APP首页</Checkbox></Col>
										<Col span={6}><Checkbox value="app_achievement_main">APP成果首页</Checkbox></Col>
										<Col span={6}><Checkbox value="app_achievement_list" disabled>APP成果搜索页</Checkbox></Col>
										<Col span={6}><Checkbox value="web_achievement_trading_index">知识产权交易首页</Checkbox></Col>
										<Col span={6}><Checkbox value="app_achievement_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;




