import React, {
  Component
} from 'react';
import CropBox from './cropBox.jsx';
import './crop.css';
import {Icon,message} from 'antd';

class CropBlock extends Component {
	constructor(props) {
		super(props);
		this.state = {
			urlArr: this.props.imgArr ? this.props.imgArr : [],
			number: this.props.number ? this.props.number : '',
			uploadData: this.props.uploadData ? this.props.uploadData : {},
			aspectRatio: this.props.aspectRatio ? this.props.aspectRatio : '',
			url: this.props.url ? this.props.url : '',
			close: true,
		}

		this.getUrl = this.getUrl.bind(this);
		this.addImg = this.addImg.bind(this);
		this.delImg = this.delImg.bind(this);
		this.getAllImg = this.getAllImg.bind(this);
	}

	getUrl(url) {
		let urlArr2 = this.state.urlArr;
		urlArr2.push(url);
		this.setState({
			urlArr: urlArr2,
			close: true
		})
		this.getAllImg(urlArr2);
	}
	addImg() {
		if(!this.state.number || (this.state.urlArr.length < this.state.number)) {
			this.setState({
				close: false
			})
		}else {
			message.warning("最多上传"+this.state.number+"张图片！");
		}
	}
	closeFun(state){
		this.setState({
			close:state
		})
	}
	delImg(index) {
		let urlArr2 = this.state.urlArr;
		urlArr2.splice(index, 1);
		this.setState({
			urlArr: urlArr2,
			close: true
		})
		this.getAllImg(urlArr2);
	}

	getAllImg(urlArr) {
		if(this.props.getAllImg) {
			this.props.getAllImg(urlArr);
		}
	}
	componentWillReceiveProps(data){
		if(data.urlArr.length>0){
			this.setState({
				urlArr:data.urlArr
			})
		}
	}
	render() {
		let imgList = this.state.urlArr.map((src, index) =>
			<div key = {index} className="crop-img-block">
				<img alt = "图片" className = "crop-img" title ="" src = {globalConfig.avatarHost + '/upload'+src} />
				<span className="del"><Icon type='delete'  onClick = {this.delImg.bind(this, index)}/></span>
			</div>
		)
		return (
			<div className = "crop-block">
			    {imgList}
				{this.state.urlArr.length < this.state.number&&<div className="crop-add-img" onClick = {this.addImg}>
					<span>+</span>
					<p>点击上传</p>
				</div>}
				<CropBox closeFun={this.closeFun.bind(this)} getUrl = {this.getUrl} uploadData = {this.state.uploadData} aspectRatio = {this.state.aspectRatio} url = {this.state.url} close = {this.state.close}/>
			</div>
		)
	}
}

export default CropBlock;


/* 
   //调用
 <Crop 
  number = {5} 
  aspectRatio = {1/1}
  url ={globalConfig.context + '/api/admin/banners/uploadPicture'}
  uploadData = {{sign: 'banners'}} 
  urlArr = {[]} 
/>

*/