var appServer = null;
var bucket = null;
var currentDeleteDivId = null;
var currentDeleteKey = null;
var currentDeleteKeys = null;
var region = null;
var Buffer = OSS.Buffer;
var OSS = OSS.Wrapper;
var STS = OSS.STS;

var addFile = function(client) {
	 var file = document.getElementById('fileId').files[0];
	 var fileName = UUIDjs.create().hex;
	 var fileType = getFileType(file.name);
     var key = "contractModel/"+fileName+"."+fileType;
     return client.multipartUpload(key, file, {
        progress: progress
    }).then(function(res) {
    	addFileSuccessCallBack(res, key, fileName);
    });
};

var applyTokenDo = function(func) {
    var url = appServer;
    $.ajax({
        type: "POST",
        url: url,
        data: "",
        dataType: "jsonp",
        success: function(e) {
            var client = new OSS({
                region: region,
                accessKeyId: e.AccessKeyId,
                accessKeySecret: e.AccessKeySecret,
                stsToken: e.SecurityToken,
                bucket: bucket
            });
            return func(client);
        },
        error: function(data) {
            console.log(data);
        }
    });
};

var deleteFile = function(key, id) {
	currentDeleteDivId = id;
	currentDeleteKey = key;
	return applyTokenDo(deleteFileFromOss);
};

var deleteFileFromOss = function(client) {
	return client.delete(currentDeleteKey, {
        progress: progress
    }).then(function(res) {
    	deleteFileSuccessCallBack(res);
    });
};

var deleteFiles = function(keys) {
	currentDeleteKeys = keys;
	return applyTokenDo(deleteFilesFromOss);
};

var deleteFilesFromOss = function(client) {
	return client.deleteMulti(currentDeleteKeys, {
        progress: progress
    }).then(function(res) {
    	deleteFilesSuccessCallBack(res);
    });
};

var getFileURL = function(client) {
    console.log(client);
    var object = data[0].name;
    var filename = object.replace(/^.*[\\\/]/, '');
    console.log(object + ' => ' + filename);
    var result = client.signatureUrl(object, {
        response: {
            'content-disposition': 'attachment; filename="' + filename + '"'
        }
    });
};

var progress = function(p) {//上传成功的进度条
	return function (done) {
		done();
	};
};

var updateFile = function(client) {
	 var file = document.getElementById('fileId').files[0];
	 var fileName = UUIDjs.create().hex;
	 var fileType = getFileType(file.name);
     var key = "contractModel/"+fileName+"."+fileType;
     return client.multipartUpload(key, file, {
        progress: progress
    }).then(function(res) {
    	updateFileSuccessCallBack(res, key, client);
    });
};

var updateFile1 = function(client) {
	 var file = document.getElementById('fileId').files[0];
	 var fileName = UUIDjs.create().hex;
	 var fileType = getFileType(file.name);
     var key = "contractModel/"+fileName+"."+fileType;
     return client.multipartUpload(key, file, {
        progress: progress
    }).then(function(res) {
    	updateFileSuccessCallBack1(res, key, fileName);
    });
};

var uploadPic = function(client) {
	var file = document.getElementById('picFileId').files[0];
	var key = $('#mod-pic-path').val();
	var fileType = getFileType(file.name);
	if(key.length < 1){
		var fileName = UUIDjs.create().hex;
	    key = "contractModel/logo/"+fileName+"."+fileType;
	}else{
		var ldot = key.lastIndexOf('.');
		if(ldot >= 0){
			key = key.substring(0, ldot);
		}
		key += "." + fileType;
	}
    return client.multipartUpload(key, file, {
        progress: progress
    }).then(function(res) {
    	updatePicSuccessCallBack(res, key);
    });
};

//添加文件到oss成功后回调
function addFileSuccessCallBack(res, path, key){
	var file = document.getElementById('fileId').files[0].name;
	var ldot = file.lastIndexOf('.');
	var name = '';
	var suffix = '';
	if(ldot>=0){
		name = file.substring(0, ldot);
		suffix = file.substring(ldot + 1);
	}
	contractFileInfo[key] = [$('#mod-file-description').val(), name, path, $('#mod-file-priority').val(), suffix];
	var html = '<div class="form-group" id="' + key + '">';
	html += '<label class="col-sm-2 control-label"></label>';
	html += '<label class="col-sm-8 text-left">' + file + '</label>';
	html += '<div class="col-sm-2 text-right">';
	html += '<button class="btn btn-primary btn-white checkbox-inline" type="button" onclick="deleteFile(\'' + path + '\',\'' + key + '\')">删除</button>';
	html += '</div></div>';
	$("#mod-add-file-list").after(html);
	$("#mod-file").modal("toggle");
}

function deleteFilesSuccessCallBack(res){
	contractModelDelete(currentDeleteModelId);
}

function deleteFileSuccessCallBack(res){
	delete contractFileUpdateInfo[currentDeleteDivId];
	$("#" + currentDeleteDivId).remove();
	contractFileDeleteFromDB(currentDeleteDivId);
}

function getFileType(fileName){
	var ldot = fileName.lastIndexOf('.')
	if(ldot>=0)
		return fileName.substring(ldot + 1);
	else
		return "";
}

//更新文件到oss成功后回调
function updateFileSuccessCallBack(res, path, client){
	var file = document.getElementById('fileId').files[0].name;
	var ldot = file.lastIndexOf('.');
	var name = '';
	var suffix = '';
	if(ldot>=0){
		name = file.substring(0, ldot);
		suffix = file.substring(ldot + 1);
	}
	var id = $('#mod-file-attachId').val();
	$('#file_' + id).html(file);
	var file = contractFileUpdateInfo[id];
	file.isChange = true;
	file.name = name;
	file.path = path;
	file.suffix = suffix;
	client.delete($('#mod-file-attachPath').val(), {
        progress: progress
    });
}

//更新文件到oss成功后回调
function updateFileSuccessCallBack1(res, path, key){
	var file = document.getElementById('fileId').files[0].name;
	var ldot = file.lastIndexOf('.');
	var name = '';
	var suffix = '';
	if(ldot>=0){
		name = file.substring(0, ldot);
		suffix = file.substring(ldot + 1);
	}
	var parameters = {'description':$('#mod-file-description').val(),'id':$('#mod-edit-modelId').val(),'name':name,'path':path,'priority':$('#mod-file-priority').val(),'suffix':suffix};
	contractFileUpdateDB(parameters);
}

function updatePicSuccessCallBack(res, path){
	var ldot = path.lastIndexOf('.');
	var suffix = '';
	if(ldot>=0){
		suffix = path.substring(ldot + 1);
	}
	var linkId = '';
	var logoId = '';
	if(currentPicOperationType == 'add'){
		linkId = 'mod-add-logo-a';
		logoId = 'mod-add-logoPath';
	}else{
		linkId = 'mod-edit-logo-a';
		logoId = 'mod-edit-logoPath';
	}
	$("#" + linkId).removeClass("collapse");
	$('#' + linkId).attr('href', logoUrl + '/' + path);
	$("#" + linkId).html('<img class="lazy" src="' + contextPath + '/static/img/loading.gif" data-original="' + logoThum + '/' + path + logoSize + suffix + '?t=' + new Date().getTime() + '" height="30" width="30"/>&emsp;');
	$("#" + logoId).val(path);
	$("#mod-pic-path").val(path);
	$("#mod-pic").modal("toggle");
	setTimeout(function () {
		$("img.lazy").lazyload({
			threshold : 200
		});
	}, 200);
}