var contextPath = null;
var currentDeleteModelId = null;
var isNotContractModelAdd = true;
var isNotContractModelEdit = true;
var logoUrl = null;
var logoThum = null;
var logoSize = null;
//添加文件
function contractFileAdd(){
	if(contractFileFormCheck()){
		applyTokenDo(addFile);
	}
}

//删除文件
function contractFileDelete(fileId){
	var file = contractFileUpdateInfo[fileId];
	if(file != undefined){
		deleteFile(file.path, file.id);
	}else{
		showMsg('本地缓存找不到文件');
	}
}

//从数据库删除文件
function contractFileDeleteFromDB(fileId){
	var url = contextPath + '/sys/contractModel/removeFile';
	var parameters = {'fileId':fileId};
	postData(url, 'application/x-www-form-urlencoded', parameters, contractFileDeleteFromDBSuccessCallback, errorCallbackDefault);
}

//从数据库删除文件成功回调
function contractFileDeleteFromDBSuccessCallback(data){
	if(data.success){
		showMsg('删除成功');
	}else{
		showMsg(data.message);
	}
}

//文件表单校验
function contractFileFormCheck(){
	var result = false;
	/*var description = $('#mod-file-description').val();
	if(description.length < 1){
		showMsg('请输入描述');
		return result;
	}*/
	var priority = $('#mod-file-priority').val();
	var reg = /^[0-9]*[1-9][0-9]*$/ ; 
	if(!reg.test(priority)){
		showMsg('请输入正整数的排序');
		return result;
	}
	result = true;
	return result;
}

//加载文件
function contractFileLoad(modelId, callBack){
	$("#editContractForm").children().remove('.mod-edit-file-list');
	var url = contextPath + '/sys/contractModel/loadFiles';
	var parameters = {'modelId':modelId};
	postData(url, 'application/x-www-form-urlencoded', parameters, callBack, errorCallbackDefault);
}

//加载文件成功回调
function contractFileLoadSuccessCallback(data){
	if(data.success){
		var html = '';
		$.each(data.attachs, function(i, v){
			html += '<div class="form-group mod-edit-file-list" id="' + v.id + '">';
			html += '<label class="col-sm-2 control-label"></label>';
			html += '<label class="col-sm-7 text-left"><a href="' + v.pathStart + v.path + '" target="_blank" id="file_' + v.id + '">' + v.name + '.' + v.suffix + '</a></label>';
			html += '<div class="col-sm-3 text-right">';
			html += '<button class="btn btn-primary btn-white checkbox-inline" type="button" onclick="contractFileUpdateShow(\'' + v.id + '\')">修改</button>';
			html += '<button class="btn btn-primary btn-white checkbox-inline" type="button" onclick="contractFileDelete(\'' + v.id + '\')">删除</button>';
			html += '</div></div>';
			v['isChange'] = false;
			contractFileUpdateInfo[v.id] = v;
		});
		$("#mod-edit-file-list").after(html);
	}else{
		showMsg(data.message);
	}
}

//加载文件成功回调
function contractFileLoadSuccessCallback1(data){
	if(data.success){
		var html = '';
		$.each(data.attachs, function(i, v){
			html += '<div class="form-group mod-edit-file-list" id="' + v.id + '">';
			html += '<label class="col-sm-2 control-label"></label>';
			html += '<label class="col-sm-7 text-left"><a href="' + v.pathStart + v.path + '" target="_blank" id="file_' + v.id + '">' + v.name + '.' + v.suffix + '</a></label>';
			html += '<div class="col-sm-3 text-right">';
			html += '<button class="btn btn-primary btn-white checkbox-inline" type="button" onclick="contractFileUpdateShow(\'' + v.id + '\')">修改</button>';
			html += '<button class="btn btn-primary btn-white checkbox-inline" type="button" onclick="contractFileDelete(\'' + v.id + '\')">删除</button>';
			html += '</div></div>';
			if(contractFileUpdateInfo[v.id] == undefined){
				v['isChange'] = false;
				contractFileUpdateInfo[v.id] = v;
			}
		});
		$("#mod-edit-file-list").after(html);
	}else{
		showMsg(data.message);
	}
}

//加载文件成功回调
function contractFileLoadSuccessCallback2(data){
	if(data.success){
		var keys = [];
		$.each(data.attachs, function(i, v){
			keys.push(v.id);
		});
		if(data.logo.length > 0){
			keys.push(data.logo);
		}
		if(keys.length > 0){
			deleteFiles(keys);
		}
	}else{
		showMsg(data.message);
	}
}

//更新文件
function contractFileUpdate(){
	if(contractFileFormCheck()){
		var id = $('#mod-file-attachId').val();
		if(id != undefined && id.length > 0){
			var file = contractFileUpdateInfo[id];
			if(file != undefined){
				var description = $('#mod-file-description').val();
				var priority = $('#mod-file-priority').val();
				if(description != file.description || priority != file.priority){
					file.isChange = true;
					file.description = description;
					file.priority = priority;
				}
				var doc = document.getElementById('fileId').files[0];
				if(doc != undefined && doc != null){
					applyTokenDo(updateFile);
				}
			}else{
				showMsg('本地缓存找不到文件');
			}
		}else{
			applyTokenDo(updateFile1);
		}
		$("#mod-file").modal("toggle");
	}
}

function contractFileUpdateDB(parameters){
	var url = contextPath + '/sys/contractModel/addFile';
	postData(url, 'application/json;charset=UTF-8', JSON.stringify(parameters), contractFileUpdateDBSuccessCallback, errorCallbackDefault);
}

function contractFileUpdateDBSuccessCallback(data){
	if(data.success){
		showMsg('添加成功');
		contractFileLoad($('#mod-edit-modelId').val(), contractFileLoadSuccessCallback1);
	}else{
		showMsg(data.message);
	}
}

function contractFileUpdateShow(fileId){
	var file = contractFileUpdateInfo[fileId];
	currentModFileOperationType = 'update';
	if(file != undefined){
		$("#fileform")[0].reset();
		$('#mod-file-attachId').val(file.id);
		$('#mod-file-attachPath').val(file.path);
		$('#mod-file-description').val(file.description);
		$('#mod-file-priority').val(file.priority);
		$("#mod-file").modal("toggle");
	}else{
		showMsg('本地缓存找不到文件');
	}
}

//添加合同范本
function contractModelAdd(){
	if(isNotContractModelAdd){
		var name = $('#mod-add-name').val();
		if(name.length < 1){
			showMsg('请输入标题');
			return ;
		}
		var priority = $('#mod-add-priority').val();
		var reg = /^[0-9]*[1-9][0-9]*$/ ; 
		if(!reg.test(priority)){
			showMsg('请输入正整数的排序');
			return ;
		}
		isNotContractModelAdd = false;
		var url = contextPath + '/sys/contractModel/add';
		var attachs = [];
		var value = null;
		for(var key in contractFileInfo){
			value = contractFileInfo[key];
			attachs.push({'description':value[0],'name':value[1],'path':value[2],'priority':value[3],'suffix':value[4]});
		}
		var parameters = {'attachs':attachs,'logo':$('#mod-add-logoPath').val(),'name':name,'priority':priority,'remark':$('#mod-add-remark').val()};
		postData(url, 'application/json;charset=UTF-8', JSON.stringify(parameters), contractModelAddSuccessCallback, contractModelAddErrorCallback);
	}else{
		showMsg('正在提交，请稍候');
	}
}

function contractModelAddErrorCallback(data){
	isNotContractModelAdd = true;
}

function contractModelAddSuccessCallback(data){
	isNotContractModelAdd = true;
	if(data.success){
		showMsg('添加成功');
		$("#mod-add").modal("toggle");
		reloadGrid();
	}else{
		showMsg(data.message);
	}
}

//删除合同范本
function contractModelDelete(modelId){
	var url = contextPath + '/sys/contractModel/remove';
	var parameters = {'modelId':modelId};
	postData(url, 'application/x-www-form-urlencoded', parameters, contractModelDeleteSuccessCallback, errorCallbackDefault);
}

function contractModelDeleteSuccessCallback(data){
	if(data.success){
		showMsg('删除成功');
		reloadGrid();
	}else{
		showMsg(data.message);
	}
}

//修改合同范本
function contractModelEdit(){
	if(isNotContractModelEdit){
		var name = $('#mod-edit-name').val();
		if(name.length < 1){
			showMsg('请输入标题');
			return ;
		}
		var priority = $('#mod-edit-priority').val();
		var reg = /^[0-9]*[1-9][0-9]*$/ ; 
		if(!reg.test(priority)){
			showMsg('请输入正整数的排序');
			return ;
		}
		isNotContractModelEdit = false;
		var url = contextPath + '/sys/contractModel/update';
		var attachs = [];
		var v = null;
		for(var k in contractFileUpdateInfo){
			v = contractFileUpdateInfo[k];
			if(v.isChange){
				attachs.push({'description':v.description,'id':v.id,'name':v.name,'path':v.path,'priority':v.priority,'suffix':v.suffix});
			}
		}
		var parameters = {'attachs':attachs,'id':$('#mod-edit-modelId').val(),'logo':$('#mod-edit-logoPath').val(),'name':name,'priority':priority,'remark':$('#mod-edit-remark').val()};
		postData(url, 'application/json;charset=UTF-8', JSON.stringify(parameters), contractModelEditSuccessCallback, contractModelEditErrorCallback);
	}else{
		showMsg('正在提交，请稍候');
	}
}

function contractModelEditErrorCallback(data){
	isNotContractModelEdit = true;
}

function contractModelEditSuccessCallback(data){
	isNotContractModelEdit = true;
	if(data.success){
		showMsg('修改成功');
		$("#mod-edit").modal("toggle");
		reloadGrid();
	}else{
		showMsg(data.message);
	}
}

function errorCallbackDefault(data){
	
}

function logoUpload(){
	applyTokenDo(uploadPic);
}

//向后台请求数据
function postData(url, contentType, parameters, successCallback, errorCallback){
	$.ajax({
	    type : "POST",
	    url : url,
	    data : parameters,
	    dataType : "json",
	    contentType:contentType,
	    success : function(data) {
	    	successCallback(data); 
	    },
	    error : function(data) {
	    	errorCallback(data);
	    }
    }); 
}

function reloadGrid(){
	myGrid.trigger('reloadGrid');
}

function showLogo(path){
	$("#mod-pic-path").val("");
	if(path.length > 0){
		var ldot = path.lastIndexOf('.');
		var suffix = '';
		if(ldot>=0){
			suffix = path.substring(ldot + 1);
		}
		$("#mod-edit-logo-a").removeClass("collapse");
		$('#mod-edit-logo-a').attr('href', logoUrl + '/' + path);
		$("#mod-edit-logo-a").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;');
		$("#mod-edit-logoPath").val(path);
		$("#mod-pic-path").val(path);
		setTimeout(function () {
			$("img.lazy").lazyload({
				threshold : 200
			});
		}, 200);
	}
}

//显示信息
function showMsg(msg){
	if(msg != undefined && msg.length > 0){
		alert(msg);
	}
}