import React from 'react';
import $ from 'jquery/src/ajax';
import {
	Icon,
	Modal,
	message,
	Spin,
	Upload,
	Input,
	Button,
	Form,
	Select
} from 'antd';
import { videoType } from '@/dataDic.js';
import { getVideoType,getReleaseStateList,splitUrl} from '@/tools.js';	
import Crop from '@/crop/cropBlock';

const NewDetailForm = Form.create()(React.createClass({
    getInitialState() {
        return {
            visible: false,
            loading: false,
			auditStatus: 0,
			fileList:[],
            textFileList: [],
			videoImg: [],
			vedioUrl:[],
			previewVisible:false,
			previewImage:''
        };
    },
    loadData(id) {
        this.setState({
            loading: true
        });
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context +  '/api/admin/video/getVideoById' ,
            data: {
                id: id
            },
            success: function (data) {
                let thisData = data.data,provice=[];
                if (!thisData) {
                    if (data.error && data.error.length) {
                        message.warning(data.error[0].message);
                    };
                    thisData = {};
				};
				let fileList =thisData.url ? splitUrl(thisData.url, ',','http://118.190.205.7:8000') : [];
					fileList[0].url=thisData.transcoding==1?'javascript:;':'http://118.190.205.7:8000'+thisData.url;
					fileList[0].name=(thisData.url).split('/').pop();
					fileList[0].thumbUrl=globalConfig.avatarHost + '/upload'+thisData.coverUrl;
                this.setState({
					id:thisData.id,
					data: thisData,
					fileList:fileList,
                    videoImg: 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) => {
			//url转化
			let theVideoUrl = [];
            if (this.state.fileList.length) {
                let picArr = [];
                this.state.fileList.map(function (item) {
                    if ( item.response && item.response.data && item.response.data.length ){
                        picArr.push(item.response.data);
                    }
                });
                theVideoUrl = picArr.join(",");
			}else{
				message.warning('请上传视频文件！');
				return false;
			};
			if(!theVideoUrl.length){
				message.warning('请上传视频文件！');
				return false;
			};
            if (!this.state.videoImg.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/admin/video/updateVideo' : globalConfig.context + '/api/admin/video/insertVideo',
                    data: {
						id: this.props.data.id,
						type:values.type,
						name: values.name,
                        url: theVideoUrl.length?theVideoUrl:'',
						summary:values.summary,
						coverUrl:this.state.videoImg.join(','),
						status:index?index:0
                    }
                }).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.state.edit={};
		this.props.closeDesc();
	},
    componentWillMount() {
        if (this.props.data.id) {
            this.loadData(this.props.data.id);
        } else {
			this.state.data = {};
			this.state.videoImg = [];
			this.state.fileList=[];
        };
	},
    componentWillReceiveProps(nextProps) {
        if (!this.props.visible && nextProps.visible) {
            if (nextProps.data.id) {
                this.loadData(nextProps.data.id);
            } else {
				this.state.data = {};
				this.state.videoImg = [];
				this.state.theData={};
				this.state.fileList=[];
            };
			this.props.form.resetFields();
        };
	},
	//视频上传
	handleChange(info) {
		let fileList = info.fileList;
        this.setState({ fileList,loading:true });
        if (info.file.status !== 'uploading') {
        }
        if (info.file.status === 'done') {
			message.success(`上传成功`);
			fileList[0].url='javascript:;';
			fileList[0].name=(fileList[0].response.data).split('/').pop();
			this.setState({
				fileList:fileList
			})
            this.setState({
				loading:false,
            })
        } else if (info.file.status === 'error') {
			message.error(`上传失败`);
			this.setState({
				loading:false,
            })
        }
	},
    beforeUpload(info){
		if(info.type.indexOf('video')<0){
			message.warning('请上传MP4格式视频文件.');
			return false;
		};
		let sizeMb = info.size/(1024*1024),size=100;
		if(sizeMb>size){  //100Mb之内
			message.warning(`视频大小不超过${size}`);
			return false;
		};
	},
	handleCancel() {
		this.setState({ previewVisible: false });
	},
	handlePreview(file) {
		this.setState({
			previewImage: file.url || file.thumbUrl,
			previewVisible: true
		});
	},
	videoRemove(file){
		let fileList = this.state.fileList;
		this.setState(({ fileList }) => {
			const index = (fileList).indexOf(file);
			const newFileList = fileList.slice();
			newFileList.splice(index, 1);
			return {
			  fileList: newFileList,
			  loading:false,
			};
		  });
	},
    render() {
        const theData = this.state.data || {};
        const { getFieldDecorator } = this.props.form;
        const FormItem = Form.Item;
        const formItemLayout = {
            labelCol: { span: 6 },
            wrapperCol: { span: 12 },
		};
		const fileList= this.state.fileList||[];
        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('name', {
								rules: [ { required: true, message: '此项为必填项!' } ],
								initialValue: theData.name
							})(<Input placeholder="请输入视频的名称" />)}
						</FormItem>
						<FormItem className="half-item" {...formItemLayout} label="视频类型">
							{getFieldDecorator('type', {
								rules: [ { required: true, message: '此项为必填项!' } ],
								initialValue: theData.type||theData.type=='0'?String(theData.type):theData.type
							})(<Select placeholder="请选择视频类型">
									{videoType.map(item=>{
										return <Select.Option value={item.value}>{item.key}</Select.Option>
									})}
								</Select>)}
						</FormItem>
					</div>
					<div className="clearfix">
						<FormItem
							className="half-item" 
							{...formItemLayout} 
							label={<span><strong style={{color:'#f00',fontSize:12}}>* </strong>视频文件</span>}
						>
							{theData.transcoding==1?<Upload
								action={globalConfig.context +'/api/admin/video/upload' }
								data={{ sign:'video' }}
								fileList={this.state.fileList}
								listType="text"
								beforeUpload={this.beforeUpload.bind(this)}
								onChange={this.handleChange.bind(this)}
								onRemove ={this.videoRemove}
							>
								{fileList.length >= 1 ? null : <div>
									<Button type="primary">点击上传</Button>
								</div>}
							</Upload>:
							<div className="clearfix">
									<Upload
										action={globalConfig.context + '/api/admin/video/upload'}
										data={{ sign: 'video'}}
										listType="picture-card"
										fileList={this.state.fileList}
										onPreview={this.handlePreview}
										onChange={this.handleChange}
										onRemove ={this.videoRemove}
										beforeUpload={this.beforeUpload.bind(this)}
									>
										{this.state.fileList.length >= 1 ? null : <div>
											<Icon type="plus" />
											<div className="ant-upload-text">点击上传</div>
										</div>}
									</Upload>
									<Modal maskClosable={false} visible={this.state.previewVisible} footer={null} onCancel={this.handleCancel}>
										<video controls alt="example" style={{ width: '100%' }} src={this.state.previewImage}></video>
									</Modal>
								</div>}
						</FormItem>
						<FormItem 
							className="half-item" 
							{...formItemLayout} 
							label={<span><strong style={{color:'#f00',fontSize:12}}>* </strong>封面图片</span>}
						>
							<Crop 
								getAllImg={(e)=>{this.setState({videoImg:e})}}
								number = {1} 
								aspectRatio = {1/1}
								url ={globalConfig.context + '/api/admin/video/upload'}
								uploadData = {{sign:'video_cover'}} 
								urlArr = {this.state.videoImg} 
							/>
						</FormItem>
					</div>
					<div className="clearfix">
						<FormItem labelCol={{ span: 3 }} wrapperCol={{ span: 18 }} label="视频简介">
							{getFieldDecorator('summary', {
								initialValue: theData.summary
							})(<Input type="textarea" rows={4} placeholder="输入视频简介" />)}
						</FormItem>
					</div>
					<div className="clearfix">
						<FormItem className="half-item" {...formItemLayout} label="发布人">
							<span>{theData.owner?theData.owner:'管理员'}</span>
						</FormItem>
						{theData.createTime&&<FormItem className="half-item" {...formItemLayout} label="发布状态">
							<span>{getReleaseStateList(theData.status)}</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) => {
										this.handleSubmit(e,1)
								}}
							>
								发布视频
							</Button>
							<Button className="set-submit" type="ghost" onClick={this.cancelFun}>
								取消
							</Button>
						</FormItem>
					</div>
				</Spin>
			</Form>    
		</div>
        )
    }
}));
export default NewDetailForm;




