Attachments.js 2.6 KB
import React,{PropTypes} from 'react'; 
import {Button,Row,Col,ProgressBar} from 'react-bootstrap';  
import cx from 'classnames'; 
import s from './Uploader.scss'; 
import Uploader from '../../components/widget/Uploader';
import UploaderResult from '../widget/UploaderResult';
import Attachment from '../../components/widget/Attachment';

export class Attachments extends React.Component { 
	constructor(props) {
        super(props); 
		this.uploadResult = this.uploadResult.bind(this);
		this.onUpload = this.onUpload.bind(this);
		this.onDelete = this.onDelete.bind(this);
		this.state={uploadResult:{}};
    }
    static propTypes = {  
    	attachments: PropTypes.array, 
		type: PropTypes.string,
		readOnly: PropTypes.bool,
		onChange: PropTypes.func
	}  

	static defaultProps(){
		readOnly:false
	}

	uploadResult(result){ 
		console.log(result);
		this.setState({
			uploaderResult:result
		})
	}

	onDelete(index){
		const {onChange, attachments} = this.props;
		const {uploader_file}=this.refs;
		const file=attachments[index];
		if(file)
			uploader_file.removeFile(file);
		// console.log(index);
		let updatedOnes = attachments.concat();
		updatedOnes.splice(index,1);
		console.log(updatedOnes);
		onChange(updatedOnes);

	}

	onUpload(newAttachments){ 
		let uploadOnes = [];
		let serverFiles=[];
		const {onChange, attachments} = this.props;
		console.log(newAttachments);
		console.log(attachments);
		newAttachments.map((attachment)=>{
			if(attachment.status==5){
				attachment.status='5';
				uploadOnes.push(attachment); 
			}
		});
		if(attachments)
		attachments.map((att,i)=>{
			if(att.status=='active'){
				serverFiles.push(att);
			}
		});
		if(uploadOnes.length>0){
			uploadOnes = uploadOnes.concat(serverFiles);
			onChange(uploadOnes);
		}   
	}

	renderExisted(){
		const {attachments, readOnly} = this.props;
		console.log(attachments);

		if(attachments&&attachments.length>0){
			return(
				<div>
					{attachments.map((attachment,index)=>{
						return (
							<Attachment readOnly={readOnly} key={index} index={index} attachment={attachment} onDelete={this.onDelete}></Attachment>)							
						})
					}

				</div>
			);
		}
		else
			return null;
	}


    render(){
    	const {readOnly, type, attachments}=this.props,self=this;  
		const {uploaderResult} = this.state;

    	return (
			<div>
				{this.renderExisted()}
				{!readOnly&&
					<div>
						<Uploader ref='uploader_file' type={type} onChange={this.onUpload} backResult={this.uploadResult}/> 
						<UploaderResult result={uploaderResult}/>
					</div>
				}
			</div>
    	)
    }
} 

export default Attachments;