import React from 'react';
import $ from 'jquery/src/ajax';
import {
	message,
	Spin,
	Input,
	Button,
	Radio,
	Form,
	Select,
} from 'antd';
import {productType} from '@/dataDic.js';
import Editors from '@/richTextEditors';
import Crop from '@/crop/cropBlock';
import KeyWordTagGroup from '@/crop/keyword';

const NewDetailForm = Form.create()(React.createClass({
    getInitialState() {
        return {
            visible: false,
            loading: false,
            auditStatus: 0,
            textFileList: [],
            videoFileList: [],
			pictureUrl: [],
			tags:[],
			edit:{},
			edits:{}
        };
    },
    loadData(id) {
        this.setState({
            loading: true
        });
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context +  '/api/admin/news/detail' ,
            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({
					type:thisData.type,
					id:thisData.id,
					data: thisData,
					tags:thisData.keywords||[],
					auditStatus:thisData.auditStatus,
					edit:thisData.content,
                    pictureUrl: thisData.coverUrl ? thisData.coverUrl.split(',') : []
                });
            }.bind(this),
        }).always(function () {
            this.setState({
                loading: false
            });
        }.bind(this));
    },
    handleSubmit(e,index) {
		e.preventDefault();
        this.props.form.validateFields((err, values) => {
			if (!this.state.pictureUrl.length) {
				message.warning('请上传专栏图片！');
				return false;
			};
			if((this.state.edit)==undefined||!this.state.edit||(this.state.edit)=='<p><br></p>'){
				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/admin/news/updateNews' : globalConfig.context + '/api/admin/news/apply',
                    data: {
						id: this.props.data.id,
						title: values.title,
                        author: values.author,
                        titleImg: this.state.pictureUrl.join(','),
						content:this.state.edit,
						hot:values.hot,
						source:values.source,
						sourceUrl:values.sourceUrl,
						keyword:values.keyword,
						auditStatus:index,
						keyword: this.state.tags ? this.state.tags.join(",") : '',
						keywords: this.state.tags,
                        summary: values.summary,
                    }
                }).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));
            }
        });
	},
	cancelFun(){
		this.props.closeDesc();
	},
    componentWillMount() {
        if (this.props.data.id) {
            this.loadData(this.props.data.id);
        } else {
			this.state.visible=true;
			this.state.data = {};
			this.state.tags=[];
			this.state.edit='<p><br></p>';
			this.state.pictureUrl = [];
        };
    },
    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.visible=true;
				this.state.data = {};
				this.state.tags=[];
				this.state.edit='<p><br></p>';
				this.state.pictureUrl = [];
				this.state.theData={};
            };
			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">
				<Spin spinning={this.state.loading}>
					<div className="clearfix">
						<FormItem className="half-item" {...formItemLayout} label="标题">
							{getFieldDecorator('title', {
								rules: [ { required: true, message: '此项为必填项!' } ],
								initialValue: theData.title
							})(<Input placeholder="请输入您的专栏标题" />)}
						</FormItem>
						<FormItem className="half-item" {...formItemLayout} label="产品类型">
							{getFieldDecorator('productType', {
								rules: [ { required: true, message: '此项为必填项!' } ],
								initialValue: theData.productType!=undefined?String(theData.type):theData.type
							})(
								<Select placeholder="产品类型">
								{
									productType.map(item=>{
										return <Select.Option value={item.value}>{item.key}</Select.Option>
									})
								}
                    			</Select>
							)}
						</FormItem>
						<FormItem className="half-item" {...formItemLayout} label="专栏来源">
							{getFieldDecorator('source', {
								rules: [ { required: true, message: '此项为必填项!' } ],
								initialValue: theData.source
							})(<Input placeholder="请输入来源" />)}
						</FormItem>
						<FormItem className="half-item" {...formItemLayout} label="来源链接">
							{getFieldDecorator('sourceUrl', {
								initialValue: theData.sourceUrl
							})(<Input placeholder="请输入来源链接" />)}
						</FormItem>
					</div>
					<div className="clearfix">
						<FormItem  labelCol={{ span: 3 }} wrapperCol={{ span: 18 }} label="关键字">
							{getFieldDecorator('keyword', {
								initialValue: theData.keyword
							})(<KeyWordTagGroup
								keyWordArr={this.state.tags}
								tagsArr={(e)=>{this.setState({tags:e})}}
								/>)}
						</FormItem>
					</div>
					<div className="clearfix">
						<FormItem labelCol={{ span: 3 }} wrapperCol={{ span: 18 }} label="专栏图片">
							<Crop 
								getAllImg={(e)=>{this.setState({pictureUrl:e})}}
								number = {1} 
								aspectRatio = {2/1}
								url ={globalConfig.context + '/api/admin/video/upload'}
								uploadData = {{sign:'video_cover'}} 
								urlArr = {this.state.pictureUrl} 
							/>
						</FormItem>
					</div>
					<div className="clearfix">
						<FormItem labelCol={{ span: 3 }} wrapperCol={{ span: 18 }} label="简介">
							{getFieldDecorator('summary', {
								rules: [ { required: true, message: '此项为必填项!' } ],
								initialValue: theData.summary
							})(<Input type="textarea" rows={4} placeholder="输入简介" />)}
						</FormItem>
					</div>
					<div className="clearfix">
						<FormItem labelCol={{ span: 3 }} wrapperCol={{ span: 18 }} label={<span><i style={{color:"red",fontSize:14}}> * </i>专栏正文</span>}>
							<Editors textContent={this.state.edit}
								uploadUrl={'/api/user/demand/uploadPicture'}
								uploadSign={'demand_picture'}
								handleRichText={(value) => { this.state.edit = value;  }}
								visible={this.state.visible} />
						</FormItem>
					</div>
					<div className="clearfix">
						<FormItem labelCol={{ span: 3 }} wrapperCol={{ span: 18 }} label="是否发布">
							<span>{theData.releaseStatus?'已发布':'未发布'}</span>
						</FormItem>
					</div>
					<div  className="clearfix">
						<FormItem className="half-item" {...formItemLayout} label="置顶">
							{getFieldDecorator('hot', {
								initialValue: theData.hot
							})(
								<Radio.Group>
									<Radio value={0}>否</Radio>
									<Radio value={1}>是</Radio>
								</Radio.Group>
							)}
						</FormItem>
						<FormItem className="half-item" {...formItemLayout} label="推荐">
							{getFieldDecorator('hot1', {
								initialValue: theData.hot1
							})(
								<Radio.Group>
									<Radio value={0}>否</Radio>
									<Radio value={1}>是</Radio>
								</Radio.Group>
							)}
						</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) => {
										this.handleSubmit(e,2)
								}}
							>
								发布新闻
							</Button>
							<Button className="set-submit" type="ghost" onClick={this.cancelFun}>
								取消
							</Button>
						</FormItem>
					</div>
				</Spin>
			</Form>    
		</div>
        )
    }
}));
export default NewDetailForm;




