/*
 * webuploader 多张图片上传到七牛
 */
$(function() {
	
    scope.uploaded=0;
    scope.$apply();

//	/************* 监听分块上传过程****************/  
//  WebUploader.Uploader.register({    
//      "before-send-file":"beforeSendFile",//整个文件上传前  
//      "before-send":"beforeSend",  //每个分片上传前  
//  },  
//  {    
//      //时间点1：所有分块进行上传之前调用此函数    
//      beforeSendFile:function(file){  
//          var deferred = WebUploader.Deferred();    
//          //1、计算文件的唯一标记fileMd5，用于断点续传  如果.md5File(file)方法里只写一个file参数则计算MD5值会很慢 所以加了后面的参数：10*1024*1024  
//          (new WebUploader.Uploader()).md5File(file,0,2097152).then(function(val){    
//              fileMd5=val;   
//              jQuery.ajax({
//		        	url:"/file/check",
//		            data:{
//		            	key:fileMd5,
//		            	folder:scope.folder_current,
//		            	folder_pids:scope.folder_current_id_str,
//		            	name:file.name
//		            },
//		            dataType: "json",
//		            type: "post",
//		            timeout: 10000,
//		            success: function(data) {
//		            	if (data.status==1) {
//		            		file.percent=1;
//		            		deferred.reject();
//		            		scope.uploaded+=1;
////		            		if (scope.list_file.length>0) {
////				    			Array.prototype.unshift.apply(scope.list_file, data.data);
////				    		}else{
////				    			scope.list_file=data.data;
////				    		}
//  						scope.$apply();
//  						folder();
//		            	}else{
//		            		deferred.resolve();
//		            	}
//		            	scope.$apply();
//		            },
//		            error: function() {
//		                mui.toast("网络连接超时");
//		            }
//		        });
//          });    
//            
//          fileName=file.name; //为自定义参数文件名赋值  
//          return deferred.promise();    
//      },    
//      //时间点2：如果有分块上传，则每个分块上传之前调用此函数    
//      beforeSend:function(block){  
//      	var deferred = WebUploader.Deferred();
//      	if (localStorage.getItem(block.file.name)) {
//      		var localFileInfo = JSON.parse(localStorage.getItem(block.file.name));
//      		var now = (new Date()).getTime();
//              var before = localFileInfo.time || 0;
//              var aDay = 24 * 60 * 60 * 1000;
//	            if (localFileInfo.chunk>=block.chunk && (now - before) < aDay) {
//	            	deferred.reject();    
//	            }else{
//	            	deferred.resolve();
//	            }
//      	}else{
//      		deferred.resolve();
//      	}
//      	
//         	     
//                             
//          this.owner.options.formData.fileMd5 = fileMd5;    
//          deferred.resolve();    
//          return deferred.promise();    
//      } 
//  });  
//  /************ 监听分块上传过程******************/ 
	
	
    var options = {
        host : "http://upload.qiniu.com",
        tokenUrl : "/api/upload_token_tu",
        domain : "http://tu.106pan.com/",
        hash : true,
        max:5
    }
	
	var uploader = WebUploader.create({
        auto: true,
	    runtimeOrder:'html5',
	    server: options.host,
	    pick: "#huandengpian",
	    chunked: true,
	    chunkSize: 4194304,
	    threads: 1,
	    fileNumLimit: options.max,
	    fileSingleSizeLimit: 10485760,
	    duplicate: true
    });

    var token;
    var m = new Map();     
    
    
    uploader.on("fileQueued", function (file) {
		//读取续传数据
        var ctx = new Array();
        if (localStorage.getItem(file.name)) {
        	var localFileInfo = JSON.parse(localStorage.getItem(file.name));
	        if (localFileInfo.ctx) {
	        	var ctx_arr=localFileInfo.ctx.split(',');
	        	for(var i=0;i<ctx_arr.length;i++){
				    if (ctx_arr[i]!='') {
				    	ctx.push(ctx_arr[i]);
				    }
				}
	        }
        }
        m.set(file.name, ctx);
        uploader.makeThumb( file, function( error, src ) {
	        if ( error ) {
	            return;
	        }
			file.src=src;
	    }, 200, 200);
	    scope.$apply();
    });
	uploader.on("filesQueued", function (files) {
		for(var i=0;i<files.length;i++){
			files[i].percent=0;
		}
		scope.upload_status='正在上传';
		if (scope.files) {
			Array.prototype.unshift.apply(scope.files, files);
		}else{
			scope.files=files;
		}
		if (scope.files) {
			if (scope.files.length>options.max) {
				for(var i in files){
					uploader.removeFile(files[i]);
				}
				scope.files.splice(0,files.length);
				wd_alert({
	    			msg:'最多只能上传'+options.max+'张图片',
	    			background:'#f00'
	    		});
	    		return false;
			}
			
		}
		
		
		scope.$apply();
	});
	
	uploader.on('uploadFinished',function () {
		scope.upload_status='上传完成';
		scope.$apply();
		jQuery("#upload .upload").hide();
		jQuery("#upload .shouqi").hide();
		jQuery("#upload .huifu").show();
	});

    uploader.on("uploadStart", function(file){
        if(!options.mockToken) {
            GetToken(options.tokenUrl, file);
        } else {
            uploader.options.formData = {
                token : options.mockTokenValue
            }
            token = options.mockTokenValue;
        }
    });

    uploader.on("uploadBeforeSend", function (block, data, headers) {
        if (parseInt(block.file.size) <= parseInt(uploader.options.chunkSize)) {
            uploader.options.chunked = false;
        } else {
            uploader.options.chunked = true;
            headers['Authorization'] = 'UpToken ' + token;
            headers['Content-Type'] = 'application/octet-stream';
            block.transport.options.server = options.host + "/mkblk/" + (block.end - block.start);
            block.transport.options.sendAsBinary = true;
            block.transport.options.formData = false;
        }
    });

    uploader.on("uploadProgress", function (file, percentage) {
    	file.percent=percentage;
		scope.$apply();
    });

    uploader.on("uploadAccept", function (block, ret) {
        m.get(block.file.name)[block.chunk] = ret.ctx;
        localStorage.setItem(block.file.name,JSON.stringify({
        	ctx: m.get(block.file.name).join(','),
            chunk: block.chunk,
            chunks: block.chunks,
            offset: block.end,
            total: block.total,
            time: (new Date()).getTime()
        }));
    });

    uploader.on("uploadSuccess", function(file, res) {
    	scope.uploaded+=1;
    	scope.$apply();
        if(parseInt(file.size) <= parseInt(uploader.options.chunkSize)) {
            UploadComplete(file,res);
        } else {
            MakeFile(m.get(file.name), file, options.hash);
        }
    });
    
    uploader.on("uploadComplete", function (file) {
    	scope.$apply();
    	localStorage.removeItem(file.name);
    });

	uploader.on('error',function (e) {
    	if (e=='F_EXCEED_SIZE') {
    		wd_alert({
				msg:'您所在用户组单个文件上传大小限制为'+Math.floor(uploader.option('fileSingleSizeLimit')/1048576)+'M',
				timeout:3000,
				background:'#f00',
				color:'#fff',
				width:350
			});
    	}else if(e=='Q_EXCEED_NUM_LIMIT'){
    		wd_alert({
				msg:'最多上传5个文件',
				timeout:3000,
				background:'#f00',
				color:'#fff',
				width:350
			});
    	}
    })
    
    jQuery(document).on('click','.btn_img_del',function () {
    	var the=jQuery(this);
    	uploader.reset();          
    })
	
	function createCookie(key, value, exp) {
        var date = new Date();
        date.setTime(date.getTime() + (exp * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
        document.cookie = key + "=" + value + expires + "; path=/";
    }

    function readCookie(key) {
        var nameEQ = key + "=";
        var ca = document.cookie.split(';');
        for (var i = 0, max = ca.length; i < max; i++) {
            var c = ca[i];
            while (c.charAt(0) === ' ') {
                c = c.substring(1, c.length);
            }
            if (c.indexOf(nameEQ) === 0) {
                return c.substring(nameEQ.length, c.length);
            }
        }
        return null;
    }

    if (!window.localStorage) {
        window.localStorage = {
            setItem: function (key, value) {
                createCookie(key, value, 30);
            },
            getItem: function (key) {
                return readCookie(key);
            },
            removeItem: function (key) {
                createCookie(key, '', -1);
            }
        };
    }
	
   function GetToken(tokenUrl, file) {
        $.ajax({
            async:false,
            type: 'get',
            url: tokenUrl,
            success: function (res) {
                token = res.uptoken;
                if(options.hash) {
                    uploader.options.formData = {
                        token : token,
                    }
                } else {
                    uploader.options.formData = {
                        token : token,
                        key: file.name
                    }
                }
            }
        });
    }

    function MakeFile(ctx, file, hash) {
        var b = ctx.join(",");
        if(hash){
            $.ajax({
                type: 'POST',
                url: options.host + '/mkfile/' + file.size,
                data: b,
                contentType: "text/plain",
                contentLength: b.length,
                beforeSend: function (XMLHttpRequest) {
                    XMLHttpRequest.setRequestHeader("Authorization", 'UpToken ' + token);
                },
                success: function(res){
                    UploadComplete(file, res);
                }
            });
        } else {
            $.ajax({
                type: 'POST',
                url: options.host + '/mkfile/' + file.size + '/key/' + URLSafeBase64Encode(file.name),
                data: b,
                contentType: "text/plain",
                contentLength: b.length,
                beforeSend: function (XMLHttpRequest) {
                    XMLHttpRequest.setRequestHeader("Authorization", 'UpToken ' + token);
                },
                success: function(res){
                    UploadComplete(file, res);
                }
            });
        }
    }

    function UploadComplete(file,res) {
    	file.url=options.domain+res.key;
    	file.key=res.key;
    	console.log(file);
//      ctx = new Array();
//      uploader.options.chunked = true;
//      jQuery.ajax({
//	    	url:"/file/add",
//	        data:{
//	        	folder:scope.folder_current,
//		    	folder_pids:scope.folder_current_id_str,
//		    	key:res.key,
//		    	file_key:fileMd5,
//		    	qiniu:'QINIU_FILE1',
//		    	name:file.name,
//		    	size:file.size,
//		    	type:file.type
//	        },
//	        dataType: "json",
//	        type: "post",
//	        timeout: 10000,
//	        success: function(data) {
////	        	if (scope.list_file.length>0) {
////	    			Array.prototype.unshift.apply(scope.list_file, data.data);
////	    		}else{
////	    			scope.list_file=data.data;
////	    		}
//	    		scope.$apply();
//	    		folder();
//	        },
//	        error: function() {
//	            mui.toast("网络连接超时");
//	        }
//	    });
    }

    function URLSafeBase64Decode(data){
        data = data.replace(/_/g, '/').replace(/-/g, '+');
        var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
        var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
            ac = 0,
            dec = "",
            tmp_arr = [];

        if (!data) {
            return data;
        }

        data += '';

        do { // unpack four hexets into three octets using index points in b64
            h1 = b64.indexOf(data.charAt(i++));
            h2 = b64.indexOf(data.charAt(i++));
            h3 = b64.indexOf(data.charAt(i++));
            h4 = b64.indexOf(data.charAt(i++));

            bits = h1 << 18 | h2 << 12 | h3 << 6 | h4;

            o1 = bits >> 16 & 0xff;
            o2 = bits >> 8 & 0xff;
            o3 = bits & 0xff;

            if (h3 === 64) {
                tmp_arr[ac++] = String.fromCharCode(o1);
            } else if (h4 === 64) {
                tmp_arr[ac++] = String.fromCharCode(o1, o2);
            } else {
                tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);
            }
        } while (i < data.length);

        dec = tmp_arr.join('');

        return dec;
    }

    function utf8_encode(argString) {

        if (argString === null || typeof argString === 'undefined') {
            return '';
        }

        var string = (argString + ''); // .replace(/\r\n/g, '\n').replace(/\r/g, '\n');
        var utftext = '',
            start, end, stringl = 0;

        start = end = 0;
        stringl = string.length;
        for (var n = 0; n < stringl; n++) {
            var c1 = string.charCodeAt(n);
            var enc = null;

            if (c1 < 128) {
                end++;
            } else if (c1 > 127 && c1 < 2048) {
                enc = String.fromCharCode(
                    (c1 >> 6) | 192, (c1 & 63) | 128
                );
            } else if (c1 & 0xF800 ^ 0xD800 > 0) {
                enc = String.fromCharCode(
                    (c1 >> 12) | 224, ((c1 >> 6) & 63) | 128, (c1 & 63) | 128
                );
            } else { // surrogate pairs
                if (c1 & 0xFC00 ^ 0xD800 > 0) {
                    throw new RangeError('Unmatched trail surrogate at ' + n);
                }
                var c2 = string.charCodeAt(++n);
                if (c2 & 0xFC00 ^ 0xDC00 > 0) {
                    throw new RangeError('Unmatched lead surrogate at ' + (n - 1));
                }
                c1 = ((c1 & 0x3FF) << 10) + (c2 & 0x3FF) + 0x10000;
                enc = String.fromCharCode(
                    (c1 >> 18) | 240, ((c1 >> 12) & 63) | 128, ((c1 >> 6) & 63) | 128, (c1 & 63) | 128
                );
            }
            if (enc !== null) {
                if (end > start) {
                    utftext += string.slice(start, end);
                }
                utftext += enc;
                start = end = n + 1;
            }
        }

        if (end > start) {
            utftext += string.slice(start, stringl);
        }

        return utftext;
    }

    function URLSafeBase64Encode(data) {
        var b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
        var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
            ac = 0,
            enc = '',
            tmp_arr = [];

        if (!data) {
            return data;
        }

        data = utf8_encode(data + '');

        do { // pack three octets into four hexets
            o1 = data.charCodeAt(i++);
            o2 = data.charCodeAt(i++);
            o3 = data.charCodeAt(i++);

            bits = o1 << 16 | o2 << 8 | o3;

            h1 = bits >> 18 & 0x3f;
            h2 = bits >> 12 & 0x3f;
            h3 = bits >> 6 & 0x3f;
            h4 = bits & 0x3f;

            // use hexets to index into b64, and append result to encoded string
            tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
        } while (i < data.length);

        enc = tmp_arr.join('');

        switch (data.length % 3) {
            case 1:
                enc = enc.slice(0, -2) + '==';
                break;
            case 2:
                enc = enc.slice(0, -1) + '=';
                break;
        }

        return enc.replace(/\//g, '_').replace(/\+/g, '-');
    }
    
    
    
});

myAngular.filter("percent", function() {
	return function(x) {
		return Math.floor(x*100);
	}
});
myAngular.filter("filesize", function() {
	return function(x) {
		if (x<1024) {
			x='1KB';
		}else if (x<1048576) {
			x=Math.floor(x/1024)+'KB';
		}else if(x<1073741824){
			x=Math.floor(x/1048576)+'MB';
		}else if(x<1073741824){
			x=Math.floor(x/1099511627776*100)/100+'GB';
		}
		return x;
	}
});