/**
 * 阿里云点播上传
 * @作者 苏相锟 <admin@phpok.com>
 * @主页 https://www.phpok.com
 * @版本 5.x
 * @授权 GNU Lesser General Public License  https://www.phpok.com/lgpl.html
 * @时间 2021年5月21日
**/
;(function($){
	var fileId = '';
	var cateId = {};
	var uploader = {};
	var account = {};//阿里云账号
	var regoin = {};
	var bucket = {};
	var multi = {};
	var gateway = {};
	var refresh = {};
	var domain = {};
	var accessKeyID = {};
	var accessKeySecret = {};
	var accessToken = {};
	var folder = {};
	var extList = {};
	var tip;
	var client;
	$.phpok_aliyunoss_gateway = {
		file_id:function(identifier)
		{
			fileId = identifier;
			return fileId;
		},
		cate_id:function(val)
		{
			if(val && val != 'undefined'){
				cateId[fileId] = val;
			}
			return cateId[fileId];
		},
		account:function(val)
		{
			if(val && val != 'undefined'){
				account[fileId] = val;
			}
			return account[fileId];
		},
		regoin:function(val)
		{
			if(val && val != 'undefined'){
				regoin[fileId] = val;
			}
			return regoin[fileId];
		},
		bucket:function(val)
		{
			if(val && val != 'undefined'){
				bucket[fileId] = val;
			}
			return bucket[fileId];
		},
		multi:function(val)
		{
			if(val && val != 'undefined'){
				multi[fileId] = true;
			}else{
				multi[fileId] = false;
			}
			return multi[fileId];
		},
		gateway:function(val)
		{
			if(val && val != 'undefined'){
				gateway[fileId] = val;
			}
			return gateway[fileId];
		},
		refresh:function(val){
			if(val && val != 'undefined'){
				refresh[fileId] = val;
			}
			return refresh[fileId];
		},
		domain:function(val){
			if(val && val != 'undefined'){
				domain[fileId] = val;
			}
			return domain[fileId];
		},
		folder:function(val){
			if(val && val != 'undefined'){
				folder[fileId] = val;
			}
			return folder[fileId];
		},
		extList:function(val){
			if(val && val != 'undefined'){
				extList[fileId] = val;
			}
			return extList[fileId];
		},
		extCheck:function(val)
		{
			var c = extList[fileId];
			if(!c || c == 'undefined'){
				c = "jpg,gif,jpeg";
			}
			if(c.indexOf(val)>-1){
				return true;
			}
			return false;
		},
		ext:function(val)
		{
			if(!val || val == 'undefined'){
				return false;
			}
			var t = val.split('.');
			var count = t.length;
			if(count<2){
				return false;
			}
			var tmp = t[count-1];
			return tmp.toLowerCase();
		},
		act:function(obj,id)
		{
			var self = this;
			this.file_id(id);//
			uploader[id] = this.aliyunOSS(id);
			for(var i=0;i<obj.files.length;i++){
				var tmpext = this.ext(obj.files[i].name);
				if(!tmpext){
					continue;
				}
				if(!this.extCheck(tmpext)){
					$.dialog.tips("附件格式 "+tmpext+" 不支持，已忽略");
					continue;
				}
				var myname = obj.files[i].name;
				var timestamp = (new Date()).valueOf();
				var tmpname = folder[id]+''+$.phpok.rand(10,'fixed')+(timestamp.toString())+"."+tmpext;
				this.addFileSuccess(obj.files[i]);
				var tmpfile = obj.files[i];
				var opts = {
					progress: function(p){
						self.progress(tmpfile,p);
					},
					partSize: 100 * 1024,
					timeout: 60000
				};
				try{
					uploader[id].multipartUpload(tmpname,obj.files[i],opts).then(function(res){
						self.uploadSuccess(res,tmpfile);
					}).catch(function(res){
						self.uploadFail(tmpfile,res);
					});
				} catch(error){
					console.log(error);
				}
			}
		},
		get_sts:function(id)
		{
			var self = this;
			var url = api_url('gateway','index','id='+gateway[id]+"&file=role");
			$.phpok.json(url,function(rs){
				if(!rs || !rs.status){
					return false;
				}
				accessKeyID[id] = rs.info.access_id;
				accessKeySecret[id] = rs.info.access_secret;
				accessToken[id] = rs.info.token;
			});
		},
		progress:function (file, percent) {
			var size = this.fsize(file.size);
			var $li = $('#phpok-upfile-'+file.id),
			$percent = $li.find('.progress span');
			var width = $li.find('.progress').width();
			$percent.css( 'width', parseInt(width * percent, 10) + 'px' );
			$li.find('span.status').html(p_lang('文件大小：'+size+'，正在上传…'));
		},
		uploadSuccess:function(res,file)
		{
			$("input[type=file]").val('');
			$('#phpok-upfile-'+file.id).find('span.status').html(p_lang('上传成功'));
			$("#phpok-upfile-"+file.id).fadeOut();
			var url = api_url('gateway','index','id='+gateway[fileId]+"&file=success&cate_id="+cateId[fileId]+"&filename="+$.str.encode(res.name)+"&title="+$.str.encode(file.name));
			$.phpok.json(url,function(rs){
				if(!rs.status){
					$.dialog.tips(rs.info).lock();
					$("#phpok-upfile-"+file.id).remove();
					return false;
				}
				if(multi[fileId]){
					var t = $("#"+fileId).val();
					var v = t ? t+","+rs.info.id : rs.info.id;
					$("#"+fileId).val(v);
					//执行
					var d = $.phpok.data("upload-"+fileId);
					if(d){
						d += ","+rs.info.id;
					}else{
						d = rs.info.id;
					}
					$.phpok.data("upload-"+fileId,d);
				}else{
					var t = $("#"+fileId).val();
					if(t){
						$.phpokform.upload_delete(fileId,t);
					}
					$("#"+fileId).val(rs.info.id);
					$.phpok.data("upload-"+fileId,rs.info.id);
				}
				if(refresh[fileId]){
					$.phpok.reload();
					return false;
				}
				$("#phpok-upfile-"+file.id).remove();
				$.phpokform.upload_showhtml(fileId,multi[fileId]);
			});
		},
		//文件添加成功后
		addFileSuccess:function(file)
		{
			var size = this.fsize(file.size);
			$("#"+fileId+"_progress").show().append('<div id="phpok-upfile-' + file.id + '" class="phpok-upfile-list">' +
				'<div class="title">' + file.name + ' <span class="status">'+p_lang('文件大小：'+size+'，等待上传…')+'</span></div>' +
				'<div class="progress"><span>&nbsp;</span></div>' +
				'<div class="cancel" id="phpok-upfile-cancel-'+file.id+'"></div>' +
			'</div>' );
		},
		fsize:function(totalSize)
		{
			var size = 0;
			totalSize = parseInt(totalSize);
			if(totalSize>= 1073741824){
				size = ((totalSize/1073741824).toFixed(2)).toString() + 'GB';
			}else if(totalSize < 1073741824 && totalSize >= 1048576){
				size = ((totalSize/1048576).toFixed(2)).toString() + 'MB';
			}else if(totalSize < 1048576 && totalSize >= 1024){
				size = ((totalSize/1024).toFixed(2)).toString() + 'KB';
			}else{
				size = (totalSize).toString() + 'B';
			}
			return size;
		},
		uploadFail:function(file,err)
		{
			console.log(err);
			$('#phpok-upfile-'+file.id).find('span.status').html(p_lang('上传失败'));
			$("#phpok-upfile-"+file.id).fadeOut().remove();
		},
		aliyunOSS:function(id)
		{
			this.file_id(id);
			var opts = {
				"region": regoin[id],
				"accessKeyId": accessKeyID[id],
				"accessKeySecret": accessKeySecret[id],
				"stsToken": accessToken[id],
				"bucket": bucket[id],
				"refreshSTSTokenInterval":300000,
				"refreshSTSToken":async function(){
					var url = api_url('gateway','index','id='+gateway[id]+"&file=role");
					var rs = await $.phpok.json(url,true);
					if(!rs || !rs.status){
						return false;
					}
					return {
						accessKeyId: rs.info.access_id,
						accessKeySecret: rs.info.access_secret,
						stsToken: rs.info.token
					}
				}
			};
			return new OSS(opts);
		}
	}
})(jQuery);