import React from 'react';
import $ from 'jquery/src/ajax';
import {
	Icon,
	Modal,
	message,
	Spin,
	Upload,
	Input,
	Button,
	Form,
	Select
} from 'antd';
import { videoType,videoPosition } from '@/dataDic.js';
import { splitUrl,getVideoStatus} 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, ',',globalConfig.videoServer) : [];
					fileList[0].url=thisData.transcoding==1?'javascript:;':globalConfig.videoServer+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,
						position:values.position||0,
                        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') {
			fileList[0].url='javascript:;';
			fileList[0].name=(fileList[0].response.data).split('/').pop();
			let theDate = fileList[0].response;
			if(theDate.error&&theDate.error.length){
				message.error(theDate.error[0].message);
				this.setState({
					fileList:[],
					loading:false,
				})
				return ;
			};
			message.success('上传成功');
			this.setState({
				fileList,
				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 });
		let video = document.getElementsByTagName('video')[0];
		video.pause();
	},
	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||!this.props.data.id?<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="视频发布位置">
							{getFieldDecorator('position', {
								initialValue: theData.position||theData.position=='0'?String(theData.position):undefined
							})(<Select placeholder="请选择发布位置">
								{videoPosition.map(item=>{
										return <Select.Option value={item.value}>{item.key}</Select.Option>
									})}
							</Select>)}
						</FormItem>
						{theData.releaseTime&&<FormItem className="half-item" {...formItemLayout} label="发布人">
							<span>{theData.owner=='1'?'管理员':theData.owner}</span>
						</FormItem>}
						{theData.createTime&&<FormItem className="half-item" {...formItemLayout} label="发布状态">
							<span>{getVideoStatus(theData.status)}</span>
						</FormItem>}
						{this.props.data.id&&<FormItem className="half-item" {...formItemLayout} label="视频状态">
							<span>{theData.transcoding=='2'?'已转码':'正在转码'}</span>
						</FormItem>}
					</div>
					<div className="clearfix">
						<FormItem wrapperCol={{ span: 12, offset: 3 }}>
							<Button className="set-submit" type="primary" htmlType="submit">
								保存草稿
							</Button>
							{(this.props.data.id&&theData.transcoding=='2')&&<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;




