import React, {
  Component
} from 'react';
import $ from 'jquery';
import Cropper from 'react-cropper';
import 'cropperjs/dist/cropper.css';
import {Button,message} from 'antd';

class CropBox extends Component {
	constructor(props) {
		super(props);
		this.state = {
		  src: '',
		  imgName:'',
	      close: this.props.close ? this.props.close : true,
	      url: this.props.url ? this.props.url : '',
	      uploadData: this.props.uploadData ? this.props.uploadData : {},
	      aspectRatio: this.props.aspectRatio ? this.props.aspectRatio : ''
	    }
	    this.onChange = this.onChange.bind(this);
	    this.cropImage = this.cropImage.bind(this);
	    this.convertBase64UrlToBlob = this.convertBase64UrlToBlob.bind(this);
	    this.submitUpload = this.submitUpload.bind(this);
	    this.closeBox = this.closeBox.bind(this);
	}
	componentWillReceiveProps(nextProps) {
        this.setState({
            close: nextProps.close
        })
    }
	onChange(e) {
	    e.preventDefault();
	    let files;
	    if (e.dataTransfer) {
	      	files = e.dataTransfer.files;
	    } else if (e.target) {
	      	files = e.target.files;
	    }
	    let reader = new FileReader();
	    reader.onload = () => {
	      this.setState({
	        src: reader.result
	      });
		};
		this.setState({
			imgName:files[0].name
		})
	    reader.readAsDataURL(files[0]);
	}
	cropImage() {
	    if (typeof this.cropper.getCroppedCanvas() == 'undefined'||this.cropper.getCroppedCanvas()==undefined) {
			message.warning('请选择图片!')
			return;
	    }
		let img64Data = this.cropper.getCroppedCanvas().toDataURL();
		let imgblobDates = this.convertBase64UrlToBlob(img64Data);  //二进制文件格式
		let imgfileDate = this.dataURLtoFile(img64Data,this.state.imgName); //文件流格式
	    this.submitUpload(imgfileDate,img64Data);
	}
	submitUpload(imgBlob,img64Data) {
		if(imgBlob.size>(2097152/2)){
			message.warning('图片不能超过1M.');
			return false;
		}
		this.props.closeFun(true);
		let _this = this,dataList={};
		//转换为文件流传输
		/* let fd = new FormData();
		for(let key in this.state.uploadData) {
			fd.append(key, this.state.uploadData[key]);
		} 
		fd.append('file',imgBlob); */
		dataList.filename=this.state.imgName;
		dataList.sign=this.state.uploadData['sign'];
		dataList.picturebase=img64Data.split(',')[1];
		$.ajax({
		    url: this.state.url,
		    type: 'POST',
			dataType: 'json',
			// processData: false,  // 注意：让jQuery不要处理数据
            // contentType: false,  // 注意：让jQuery不要设置contentType
			data:dataList,
		    success: function (data) {
	    		if(data.error&&data.error.length>0){
					message.error(data.error[0].message);
				}else{
					if(_this.props.getUrl) {
						_this.props.getUrl(data.data);
					}
					message.success('上传成功');
				}
	    		_this.setState({
	    			close: true,
	    			src: ''
				})
		    },
		    error: function(err) {
		    	message.error(err)
		    }
		});
	}
	//将base64转换为文件
    dataURLtoFile(dataurl, filename) {
		var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
		bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
		while(n--){
			u8arr[n] = bstr.charCodeAt(n);
		}
		return new File([u8arr], filename, {type:mime});
	}
	//base64转二进制文件格式
	convertBase64UrlToBlob(urlData) {
		var bytes=window.atob(urlData.split(',')[1]);        //去掉url的头，并转换为byte  
	    //处理异常,将ascii码小于0的转换为大于0  
	    var ab = new ArrayBuffer(bytes.length);  
	    var ia = new Uint8Array(ab);  
	    for (var i = 0; i < bytes.length; i++) {  
	        ia[i] = bytes.charCodeAt(i);  
	    }  
	    return new Blob( [ab] , {type : 'image/png'});
	}
	selFile(){
		document.querySelector('.crop-input input[type=file]').click();
	}
	closeBox() {
		this.setState({
			close: true
		})
		this.props.closeFun(true)
	}
	render() {
		return (
			<div className = "crop-box" style = {this.state.close ? {"display": "none"} : {"display": "block"}}>
				<div className="crop-box-bg"></div>
				<div className="crop-box-content">
					<div className="crop-input">	
						<Button type="primary" style={{marginTop:10}} onClick={this.selFile.bind(this)}>选择图片</Button>
						<input type="file" className="selectFile" onChange={this.onChange} key = {this.state.src}/>
						<div className="crop-close" onClick = {this.closeBox}>x</div>
					</div>
					<div className="crop-area">
						<Cropper key = {this.state.src}
				            style={{ height: 400, width: 400 }}
						    aspectRatio = {this.state.aspectRatio}
						    preview = ".img-preview"
				            guides={true}
				            src={this.state.src}
				            ref={cropper => { this.cropper = cropper; }}
				        />
					</div>
					<div className="btnGrounpCrop">
						<Button type="primary" className = "crop-sure-btn" onClick={this.cropImage}>确认裁剪</Button>
						<Button onClick = {this.closeBox}>取消</Button>
					</div>
				</div>
			</div>
		);
	}
}

export default CropBox;