import React from 'react';
import $ from 'jquery/src/ajax';
import {
	message,
	Spin,
	Input,
	Button,
	Form,
} from 'antd';
import SelectContent from './selectContent' 
import {getZiYuanType} from '@/tools'

const NewDetailForm = Form.create()(React.createClass({
    getInitialState() {
        return {
            visible: false,
			loading: false,
			visibleSel:false,
            auditStatus: 0,
            textFileList: [],
			videoFileList: [],
			objData:[],
			objName:'',
			objId:''
        };
    },
    getPictureUrl(e) {
        this.setState({ pictureUrl: e });
    },
    handleSubmit(e,index) {
		e.preventDefault();
		if(this.props.data.id&&!this.state.objTitle){
			message.warning('请选择推送内容!');
			return;
		}
        this.props.form.validateFields((err, values) => {
            if (!err) {
                this.setState({
                    loading: true
				});
				let hours =new Date(),
					year = hours.getFullYear(),
					month = (hours.getMonth()+1)<10?'0'+(hours.getMonth()+1):(hours.getMonth()+1),
					day = hours.getDate()<10?'0'+hours.getDate():hours.getDate(),
					hour=hours.getHours()<10?'0'+hours.getHours():hours.getHours(),
					mins = hours.getMinutes()<10?'0'+hours.getMinutes():hours.getMinutes(),
					sec = hours.getSeconds()<10?'0'+hours.getSeconds():hours.getSeconds();
				let times = year+'-'+month+'-'+day+' '+hour+':'+mins+':'+sec;
                $.ajax({
                    method: "post",
					dataType: "json",
					async:true,
                    url: this.props.data.id?globalConfig.context +"/api/admin/message/updMessageById":globalConfig.context +"/api/admin/message/createMyMessage",
                    data: {
						subject:1,
						id: this.props.data.id,
						title: values.title,
						subject:1,					//消息类别 0-系统消息
						isDraft:index=='1'?1:0, 	//是否草稿 0-否 1-是
						deleteSign:0,	  			//删除标识 0-否 ，1-是
						isSend:index=='2'?1:0,  	//是否发送0-否 1-是
						body:values.body,
						messageCreateTime:!(this.props.data.id)?times:'null',
						resourceId:this.props.data.id?this.state.objData.rowId:'',
						resourceType:this.props.data.id?getZiYuanType(this.state.objData.fromTable):'',
						resourceName:this.props.data.id?this.state.objData.title:''
                    }
                }).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(false,false);
	},
    componentWillMount() {
        if (this.props.data.id) {
           
        } else {
			this.state.visible=true;
			this.state.data = {};
        };
	},
	visFun(state,data){
		this.setState({
			visibleSel:state,
			objData:data,
			objTitle:data.title
		});
	},
	selContent(){
		this.setState({
			visibleSel:true
		})
	},
	componentWillMount(){
		this.setState({
			objTitle:this.props.data.resourceName||''
	   })
	},
    componentWillReceiveProps(nextProps) {
        if (!this.props.visible && nextProps.visible) {
            this.state.textFileList = [];
			this.state.videoFileList = [];
            if (nextProps.data.id) {
               this.setState({
					objTitle:nextProps.data.resourceName
			   })
            } else {
				this.state.visible=true;
				this.state.visibleSel=false
				this.state.data = {};
            };
			this.props.form.resetFields();
        };
    },
    render() {
		const theData = this.props.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,1)}} id="demand-form">
				<Spin spinning={this.state.loading}>
					<div className="clearfix">
						{this.props.data&&this.props.data.id?<div>
							<FormItem className="half-item" {...formItemLayout} label="创建人">
								<span>{theData.admin?theData.admin:'管理员'}</span>
							</FormItem>	
							</div>:''}	
					</div>
					<div className="clearfix">
						<FormItem  labelCol={{ span: 3 }} wrapperCol={{ span: 14 }} label="标题">
							{getFieldDecorator('title', {
								rules: [ { required: true, message: '此项为必填项!' } ],
								initialValue: theData.title
							})(<Input placeholder="请输入消息标题" />)}
						</FormItem>
					</div>
					<div className="clearfix">
						<FormItem labelCol={{ span: 3 }} wrapperCol={{ span: 18 }} label="消息内容">
							{getFieldDecorator('body', {
								rules: [ { required: true, message: '此项为必填项!' } ],
								initialValue: theData.body
							})(<Input type="textarea" rows={4} placeholder="输入内容" />)}
						</FormItem>
					</div>
					{this.props.data&&this.props.data.id?<div className="clearfix">
						<FormItem labelCol={{ span: 3 }} wrapperCol={{ span: 18 }} label={<span><strong style={{color:'#f00'}}> * </strong>推送内容</span>}>
							<div>
								<span>{this.state.objTitle}</span>
								<Button 
									onClick={this.selContent.bind(this)} 
									type="primary" 
									style={{marginLeft:10}}>选择</Button>
							</div>
						</FormItem>
					</div>:''}
					{this.props.data&&this.props.data.id?<div>
						<div className="clearfix">
							<FormItem labelCol={{ span: 3 }} wrapperCol={{ span: 18 }} label="创建时间">
								<span>{theData.createTime}</span>
							</FormItem>
						</div>
					</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"
								style={{background: 'rgb(63, 207, 158)',border:'none',color:'#FFF'}}
								type="ghost"
								onClick={(e) => {
										this.handleSubmit(e,2)
								}}
							>
								推送
							</Button>:''}
							<Button className="set-submit" type="ghost" onClick={this.cancelFun}>
								取消
							</Button>
						</FormItem>
					</div>
				</Spin>
			</Form>  
			<SelectContent 
				visible={this.state.visibleSel}
				visFun={this.visFun.bind(this)}
			/>  
		</div>
        )
    }
}));
export default NewDetailForm;




