var files = []; //存储文件信息的数组
var fname = ""; //表示文件名，例如  XXXX.jpg;
var expire = 0;
var pathName = '';
var keyname = '';
var isZip=1;
var qualityNum=90;
var UP = UP || {};
UP.isOk=0;
UP.init = function( path,isZipImg,quality) {
	pathName = path;
	if(typeof(isZipImg) != 'undefined'){
		// //console.log(typeof(isZipImg));
		isZip =  isZipImg;
	}
	if(typeof(quality) != 'undefined'){
		qualityNum = quality;
	}	
}

function send_request() {
	var xmlhttp = null;
	if (window.XMLHttpRequest) {
		xmlhttp = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	}

	if (xmlhttp != null) {
		//		//console.log(dir)
		serverUrl = 'http://t.ect99.com/oss/get.php?dir=' + pathName;
		xmlhttp.open("GET", serverUrl, false);
		xmlhttp.send(null);
		return xmlhttp.responseText
	} else {
		mui.alert("Your browser does not support XMLHTTP.");
	}

}

function get_signature() {
	//可以判断当前expire是否超过了当前时间,如果超过了当前时间,就重新取一下.3s 做为缓冲
	now = timestamp = Date.parse(new Date()) / 1000;
	if (expire < now + 3) {
		body = send_request()
		var obj = eval("(" + body + ")");
		// //console.log(obj);
		return obj;
	}
	return false;
};
// 上传文件
function uploadInit(){
	// //console.log(files);
	if (files.length <= 0) {
		mui.toast('没有添加上传文件');
		return;
	}
	var obj = get_signature();
	if (obj) {
		server = obj['host'];
		policyBase64 = obj['policy'];
		accessid = obj['accessid'];
		signature = obj['signature'];
		expire = parseInt(obj['expire']);
		callbackbody = obj['callback'];
		path = obj['dir'];
		
	} else {
		mui.toast('初始化失败');
		return;
	}
	var suffix1 = get_suffix(fname); //文件后缀  例如   .jpg
	keyname = path + new Date().getTime() + suffix1;
	task.addData("key", keyname);
	task.addData("policy", policyBase64);
	task.addData("OSSAccessKeyId", accessid);
	task.addData("success_action_status", "200");
	// task.addData("callback", callbackbody);
	task.addData("signature", signature);
	var f = files[files.length-1];
	// //console.log(f)

	task.addFile(f.path, {
		key: "file",
		name: "file",
		mime: "image/jpeg"
	});
	//files.length = 0;
	return true;
}	
// 		//上传完成
// 		if (status == 200) {
// 			
// 			//console.log(inpId);
// 			document.getElementById(inpId).value = keyname;
// 			var ele=document.getElementById(imgId);	
// 			ele.src=server + '/'+keyname;
// 			ele.setAttribute('data-src',keyname);
// 			wt.close();
// 			mui.toast('上传成功');
// 			UP.isOk=1;
// 	if(1 == UP.isOk){
// 			var html='<div class="galleryImg photo"><img src="" class="ossfile" data-id="'+num+'" id="galleryImg['+num+']" alt=""><input type="hidden" value="" class="gallery inp" id="gallery['+num+']"><span class=""></span></div>';
// 			if($('#galleryImg['+num+']').length>0){
// 				$('#galleryImg['+num+']').parent().html(html);		
// 				
// 				
// 			}else{
// 				$(".photos_con").append(html);
// 				var maxNum = $('.photos_con').children('.galleryImg').length-1;
// 				if(num >= maxNum){
// 					html='<div class="galleryImg photo"><img src="" class="ossfile" data-id="'+num+'" id="galleryImg['+num+']" alt=""><input type="hidden" value="" class="gallery inp" id="gallery['+num+']"><span class=""></span></div>';
// 					$(".photos_con").append(html);
// 				}
// 			
// 			}
// 		}	
			//至此上传成功，上传后的图片完整地址为server+testName
		

//得到文件名的后缀
function get_suffix(filename) {
	var pos = filename.lastIndexOf('.');
	var suffix = '';
	if (pos != -1) {
		suffix = filename.substring(pos)
	}
	return suffix;
}
// 拍照添加文件
function appendByCamera() {
	plus.camera.getCamera().captureImage(function(p) {
		uploadImg(p);
	});
}
// 从相册添加文件
function appendByGallery() {
	plus.gallery.pick(function(p) {
		uploadImg(p);
	});
}

// 添加文件
var index = 1;
function uploadImg(p){
	UP.isOk=0;
	if(1 == isZip){
		compressImg(p);
	}else{
		appendFile(p)
	}
}
function appendFile(p) {	
	// var fe = document.getElementById(fileId);
	var n = p.substr(p.lastIndexOf('/') + 1);
	fname = n;
	files.push({
		name: "uploadkey" + index,
		path: p
	});
	////console.log(3);
	// index++;
	upload();
}
function compressImg(src) {
	var filename = src.substring(src.lastIndexOf('/') + 1);
	var opions = {
		src: src,
		dst: '_doc/tmp/' + filename,
		overwrite: true,
		//width: '300px', //这里指定了宽度，同样可以修改
		format: 'jpg',
		quality: qualityNum //图片质量不再修改，以免失真
	};
	var successCB = function(evt) {
		// //console.log(JSON.stringify(evt));
 		fname = filename;
// 		files[0]={
// 			name: "uploadkey",
// 			path: evt.target
// 		};
		files.push({
			name: "uploadkey" + index,
			path: evt.target
		});
		// index++;
		//上传		
		upload();
		//_this.avatar(evt.target);
	};
	var errorCB = function(err) {
		appendFile(src);
		////console.log(JSON.stringify(err));
		//mui.toast("图片压缩失败");
	};
	plus.zip.compressImage(opions, successCB, errorCB);
};
function openCamera() {
		plus.nativeUI.actionSheet({
			cancel: "取消",
			buttons: [{
					title: "拍照"
				},
				{
					title: "从相册中选择"
				}
			]
		}, function(e) { //1 是拍照  2 从相册中选择
			switch (e.index) {
				case 1:
					appendByCamera();
					break;
				case 2:
					appendByGallery();
					break;
			}
		});
	}