var files = []; //存储文件信息的数组
var fname = ""; //表示文件名，例如  XXXX.jpg;
var expire = 0;
var pathName = '';
var inpId = '';
var keyname = '';
var imgId='';
var isZip=1;
var qualityNum=90;
var response=';'
var UP = UP || {};
UP.isBatch=0;
UP.init = function(inputId, path,imageId,isBatch,isZipImg,quality) {
	inpId = inputId;
	pathName = path;
	imgId = imageId;
	if(typeof(isBatch) != 'undefined'){
		UP.isBatch = isBatch;
	}	
	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 = qlgUrl('oss/get.php?dir=' + pathName);
		 // serverUrl = 'https://img.zgqlg.com.cn/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 + ")");
		response = obj;
		// //console.log(obj);
	}
	return response;
};
// 上传文件
function upload(callback) {
	// //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 wt = plus.nativeUI.showWaiting();
	var task = plus.uploader.createUpload(server, {
		method: "POST"
	}, function(t, status) {
		//上传完成
		if (status == 200) {
			wt.close();
			if(1 == UP.isBatch){
				callback(t,status,keyname,server + '/'+keyname);
			}else{
				document.getElementById(inpId).value = keyname;
				var ele=document.getElementById(imgId);	
				ele.src=server + '/'+keyname;
				ele.setAttribute('data-src',keyname);
				mui.toast('上传成功');
				//至此上传成功，上传后的图片完整地址为server+testName
				//keyname
			}
			
		} else {
			wt.close();
			mui.toast('上传失败：' + status);
		}
	});
	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;
	task.start();

}

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

// 添加文件
var index = 1;
function uploadImg(p,callback){
	if(1 == isZip){
		compressImg(p,callback);
	}else{
		appendFile(p,callback)
	}
}
function appendFile(p,callback) {	
	// 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(callback);
}
function compressImg(src,callback) {
	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(callback);
		//_this.avatar(evt.target);
	};
	var errorCB = function(err) {
		appendFile(src,callback);
		////console.log(JSON.stringify(err));
		//mui.toast("图片压缩失败");
	};
	plus.zip.compressImage(opions, successCB, errorCB);
};
function openCamera(callback) {
	plus.nativeUI.actionSheet({
		cancel: "取消",
		buttons: [{
				title: "拍照"
			},
			{
				title: "从相册中选择"
			}
		]
	}, function(e) { //1 是拍照  2 从相册中选择
		switch (e.index) {
			case 1:
				appendByCamera(callback);
				break;
			case 2:
				appendByGallery(callback);
				break;
		}
	});
	}