/**
 * 
 * @authors cchen
 * @date    2016-08-01 10:41:13
 * @version 3.0
 */
(function(factory) {
    if ( !window.jQuery ) {
        alert('jQuery is required.');
    }

    jQuery(function() {
        factory.call( null, jQuery );
    }); 
})(function( $ ){
	function uploader(options){
		var defaults = {
			inputFile: '#filePicker',   //触发上传的div  id
			uploadUrl: '',              //上传的链接
			uploadcompress:false,       //是否开启压缩，如isCrop为true时，请设置为false
			isCrop: true,               //是否剪裁
			previewUrl: '',
			fileNumLimit: 30,           //上传文件数量的最大限制
			fileSizeLimit: 1*1024*1024, //上传文件的最大文件大小，限制不能超过1M
			cropW: 200,                 //剪裁框宽度
			cropH: 200,					//剪裁框高度
			cropFile: '#filePicker input',   //上传图片的<input type="file">控件的选择器或者DOM对象
			onclipFinish: function(dataURL){  //完成剪裁后执行函数
				$('.uploader-preview').css({
					'background-image':'url('+dataURL+')',
					'background-size': 'cover'
				});
				$('.cur-upload-input').val(dataURL);
				var clip_id = $('#filePicker2').attr('data-id');
                $('#'+clip_id).addClass('webuploader-element-invisible');
				$('body').removeClass('hidden');
			}
			
		};
		this.opt = $.extend(defaults,options);
		this.uploadObj = null;
		this.uploadFile = null;
		this.Uploader = WebUploader.Uploader;
		this.flag = 0;
		this.init();
	}
	uploader.prototype={
		init: function(){
			var _this = this;
		    if ( !_this.Uploader.support() ) {
		        alert( 'Web Uploader 不支持您的浏览器！');
		        throw new Error( 'WebUploader does not support the browser you are using.' );
		    }
		    if(_this.opt.isCrop){
			    _this.clip_id = Math.random().toString().replace('.', '');
		    	_this.clip_id = 'clipArea'+_this.clip_id;
		    	$(_this.opt.inputFile).attr('data-id',_this.clip_id);
			    var htmlStr = '<div class="cropper-wraper webuploader-element-invisible" id="'+_this.clip_id+'"><div class="clip-btn">剪裁</div></div>';
			    $('body').append(htmlStr);
		    }
			_this.uploadSetup();
		},
		uploadSetup: function(){
			var _this = this;
			var file;
			_this.uploadObj = new _this.Uploader({
                pick: {
                    id: _this.opt.inputFile,
                    multiple: false
                },
                accept: {
                	title: 'Images',
				    extensions: 'gif,jpg,jpeg,bmp,png',
				    mimeTypes: 'image/gif,image/jpg,image/jpeg,image/bmp,image/png'
                },
                thumb: {
                	quality: 70,
                    allowMagnify: false,
                    crop: false,
                    type: ''
                },
                chunked: false,
                compress: false,
                fileSingleSizeLimit: _this.opt.fileSizeLimit,
                server: _this.opt.uploadUrl,
                swf: 'Uploader.swf',
                duplicate: 1,
                fileNumLimit: _this.opt.fileNumLimit,
                onError: function(handler) {
                	switch(handler){
                		case 'Q_EXCEED_NUM_LIMIT':
                			alert('上传文件过于频繁，请刷新后再试');
                			break;
                		case 'F_EXCEED_SIZE':
                			alert('该文件过大！无法上传');
                			break;
                		case 'Q_TYPE_DENIED':
                			alert('请上传gif,jpg,jpeg,bmp,png文件');
                			break;
                	}
                }
            });
            // 当不处于剪裁模式且开启压缩时
            if(_this.opt.isCrop==false && _this.opt.uploadcompress==true){
            	_this.uploadObj.option('compress',{
            		quality: 50,
				    allowMagnify: false,
				    crop: false,
				    preserveHeaders: true,
				    noCompressIfLarger: false,
				    compressSize: 200*1024
            	});
            }
            // 剪裁模式下首次绑定photoClip
            if(_this.flag == 0&&_this.opt.isCrop){
            	_this.flag = 1;
            	setTimeout(function(){
					$("#"+_this.clip_id).photoClip({
						width: _this.opt.cropW,
						height: _this.opt.cropH,
						file: _this.opt.cropFile,
						ok: '#'+_this.clip_id+' .clip-btn',
						loadStart: function() {
							//console.log("照片读取中");
						},
						loadComplete: function() {
							//console.log("照片读取完成");
						},
						clipFinish: _this.opt.onclipFinish
					});

            	},500);
            }
            _this.uploadObj.on('fileQueued', function( _file ) {
            	_this.uploadFile = _file;
	            if(_this.opt.isCrop){
                	$('#'+_this.clip_id).removeClass('webuploader-element-invisible');
	            }
            	_this.uploadObj.makeThumb( _file, function( error, src ) {
            		if(_this.flag == 1&&_this.opt.isCrop && $('.photo-clip-rotateLayer img').get(0)){
            			$('.photo-clip-rotateLayer img').attr('src',src);
            		}
            		if(_this.opt.isCrop==false){
            			$('.uploader-pic').removeClass('uploader-preview');
		    		    $('.upload-input').removeClass('cur-upload-input');
		            	var html = '<div class="uploader-pic uploader-preview"></div>';
		                $('.uploader-box.active').find('.uploader-pic-box').append(html);
		                var input = '<input type="hidden" class="upload-input cur-upload-input">';
		                $('.uploader-box.active').find('.uploader-input-box').append(input);
		                var num = $('.uploader-box.active').find('.uploader-pic').length;
						if (num >= 30) {
							$('.uploader-box.active').find('.btn-add-photo').addClass('hide');
						}

		                $('.uploader-preview').css({
							'background-image':'url('+src+')',
							'background-size': 'cover'
						});
		            	$('.cur-upload-input').val(src);
		            	$('.uploader-box').removeClass('active');
            		}            		
                },1,1);   
            });
		}     
	};
	window['uploader'] = function(options){
		return new uploader(options);
	};
});