$(function(){
	$('#w5').window('close',function(){
		$('#dg3').datagrid('reload');
	});
	$('#w2').window('close',function(){
		$('#dg').datagrid('reload');
	});   
	
    $('#search-form').submit(function(event){
        event.preventDefault(); 
        var param = $('#search-form').serializeJson();
        $('#dg').datagrid('load',param);
    });
    
    $('#search-formUsedPapers').submit(function(event){
        event.preventDefault(); 
        var param = $('#search-formUsedPapers').serializeJson();
        $('#usedPapersDG').datagrid('load',param);
    });
    
    $("#searchUsedPapers").on('click',function(){
    	$('#search-formUsedPapers').submit();
    });
    
    $("#addCodeBookBtn").on('click',function(){
    	$.messager.confirm("操作提示", "生成新密码本后原有的密码本都会失效,是否确定生成新密码本?", function (data) {
    		if (data) {
    			var codeNum=$("#codeNum").val();
    	    	var createBy=$("#createBy").val();
    	    	var url=$("#url").val();
    	    	var obj={
    	        		"codeNum" : codeNum,
    	        		"createBy" : createBy
    	        	};
    	    	var CodeBookLog=JSON.stringify(obj);
    	    	if(!isNaN(codeNum)&&codeNum!='0'){ 
    	    		$.ajax({
    	    			type : "POST",
    	    			url : url+"/examSetting/addCodeBook",
    	    			data :  CodeBookLog ,
    	    			contentType : "application/json; charset=utf-8",
    	    			dataType : "json",
    	    			success : function(callback) {
    	    				allback=eval(callback);
    	    				if(callback.result=='success'){
    	    					$.messager.alert("操作提示", "生成密码本成功!","info");
    	    					$('#addCode').window('close');
    	    					$('#dg').datagrid('reload');
    	    				}else{
    	    					$.messager.alert("操作提示", "生成密码本失败!","error");
    	    				}
    	    			}
    	    		});
    	    	}else{
    	    		$.messager.alert("操作提示", "生成密码条数不能为非数字或0","error");
    	    	}
    		}
    	});
    });
    
    
    
    $(".clearSearch").on('click',function(){
    	$("#code").val("");
    	$("#courseCode").val("");
    	$("#rukuType").val("").find("option").eq(0).attr("selected","selected");
    	$("#status").val("").find("option").eq(0).attr("selected","selected");
    	$("#isStorageScanned").val("").find("option").eq(0).attr("selected","selected");
    	$("#isOutBoundScanned").val("").find("option").eq(0).attr("selected","selected");
    });
    
    $("#searchDRAFT").on('click',function(){
    	$('#search-form').submit();
    });
    
    $("#search1").on('click',function(){
		$('#search-form1').submit();
	});
	
	$("#search2").on('click',function(){
		$('#search-form2').submit();
	});
	
	$("#search3").on('click',function(){
		$('#search-form3').submit();
	});
	
	$('#search-form1').submit(function(event){
	    event.preventDefault(); 
	    var param = $('#search-form1').serializeJson();
	    param = $.extend(param, {page:1,rows:10});
	    $('#dg1').datagrid('load',param);
	});
	
	$('#search-form2').submit(function(event){
	    event.preventDefault(); 
	    var param = $('#search-form2').serializeJson();
	    param = $.extend(param, {page:1,rows:10});
	    $('#usedPapersDG').datagrid('load',param);
	});
	
	$('#search-form3').submit(function(event){
	    event.preventDefault(); 
	    var param = $('#search-form3').serializeJson();
	    param = $.extend(param, {page:1,rows:10});
	    $('#dg').datagrid('load',param);
	});
});


function restoreSys(url){
	var password=$("#password").val();
	if(password==''){
		$.messager.alert('提示','还原密码不能为空!','error');
	}else{
		var obj={
			"password" : password,
			"randomCode" : $("#randomCode").html()
		};
		var CodeBook=JSON.stringify(obj);
		$.ajax({
			type : "POST",
			url : url+"/examSetting/continueRestoreSys",
			data :  CodeBook ,
			contentType : "application/json; charset=utf-8",
			dataType : "json",
			success : function(callback) {
				allback=eval(callback);
				if(allback.result=='error'){
					$.messager.alert('提示','解压密码错误!','error');
				}else if(allback.result=='error'){
					$.messager.alert('提示','还原出错,请核实上传的zip包正确性!','error');
				}else{
					$.messager.alert('提示','还原成功!','info');
					$('#w5').window('close');
				}
			}
		});
	}
}
function paperBtn(){
	var options = $('#dg').datagrid('getPager').data("pagination").options;
	var total = options.total;
	if(total>0){
		$('#w2').window('open');
	}else{
		$.messager.alert('提示','请先导入DBF试卷后再执行该操作!','error');
	}
}

function cellStyler(value,row,index){
	if (value==null||value=="0"){
        return 'background-color:#ffee00;color:red;text-align:center;';
    }else{
    	return 'color:green;text-align:center;';
    }
}
function codeCellStyler(value,row,index){
    return 'color:gray;font-size:15px;font-weight:bold;';
}

function formatBooleanData(data){
	if(data==null||data=="0"){
		return "×";
	}else{
		return "√";
	}
}

function formatSeparentPaperData(data){
	if(data==null||data=="0"){
		return "/";
	}else{
		return "√";
	}
}

function formatData(data){
	if(data=='0'){
		return '<p style="color: red;">否</p>';
	}else{
		return '<p style="color: green;">是</p>';
	}
}

function answerSheetDataCellStyler(value, row, index){
	if(row.isSpecialAnswerSheet == 1){
		if(row.answerSheetPath == null){
			return 'background-color:#ffee00;color:red;text-align:center;';
		}else{
			return 'color:green;text-align:center;';
		}
	}else{
		return 'color:green;text-align:center;';
	}
}

function separatePaperCellStyler(value, row, index){
	if(row.separatePaperPath != null){
		if(row.isSeparatePaperReturn == 1 ){
			return 'color:green;text-align:center;';
		}else{
			return 'background-color:#ffee00;color:red;text-align:center;';
		}
	}else{
		return 'color:green;text-align:center;';
	}
}

function separatePaperCellStylerRuku(value, row, index){
	return 'color:green;text-align:center;';
}

function formatSeparatePaperReturn(value, row, index){
	if(row.separatePaperPath != null){
		if(row.isSeparatePaperReturn == 1 ){
			return "√";
		}else{
			return "×";
		}
	}else{
		return "/";
	}
}

function formatDFData(value, row, index){
	if(row.df==0){
		return '<a style="color: green;" href="javascript:;">待定</a>';
	}else if(row.df==1){
		return '<a style="color: red;" href="javascript:;">否定</a>';
	}
}

function formatAnswerSheetData(value, row, index){
	if(row.isSpecialAnswerSheet == 1){
		if(row.answerSheetPath == null){
			return "×";
		}else{
			return "√";
		}
	}else{
		return "/";
	}
}

function formatAnswerSheetReturn(value, row, index){
	if(row.isSpecialAnswerSheet == 1){
		if(row.isAnswerSheetReturn==0){
			return "×";
		}else{
			return "√";
		}
	}else{
		return "/";
	}
}

function answerSheetReturnCellStyler(value, row, index){
	if(row.isSpecialAnswerSheet == 1){
		if(row.isAnswerSheetReturn==0){
			return 'background-color:#ffee00;color:red;';
		}else{
			return 'color:green;';
		}
	}else{
		return 'color:green;';
	}
}

function formatStatus(data){
	if(data=="DRAFT"){
		return "毛坯";
	}else if(data=="FORMAL"){
		return "清样";
	}else if(data=="USED"){
		return "启用";
	}else{
		return "";
	}
}

function formatZK(data){
	if(data=="1"){
		return "有";
	}else{
		return "不详";
	}
}
function downFORMALDBF(url,batchId){
	var form=$("<form>");//定义一个form表单
   	form.attr("style","display:none");
   	form.attr("target","");
   	form.attr("method","post");
   	form.attr("enctype","multipart/form-data");
   	form.attr("action",url+"/examPaper/downFORMALDBF");
   	var input1=$("<input>");
   	input1.attr("type","hidden");
   	
   	var input2=$("<input>");
   	input2.attr("type","hidden");
   	input2.attr("name","batchId");
   	input2.attr("value",batchId);
   	
   	var input3=$("<input>");
   	input3.attr("type","hidden");
   	input3.attr("name","name");
   	input3.attr("value",name);
   	
   	$("body").append(form);//将表单放置在web中
   	form.append(input1);
   	form.append(input2);
   	form.append(input3);
   	form.submit();//表单提交 
}

function downLoadDBF(name,url,batchId){
	var options = $('#usedPapersDG').datagrid('getPager').data("pagination").options;
	var total = options.total;
	var arrCode=new Array();
	var row = $('#usedPapersDG').datagrid('getSelected');

	var form=$("<form>");//定义一个form表单
	form.attr("style","display:none");
	form.attr("target","");
	form.attr("method","post");
	form.attr("enctype","multipart/form-data");
	form.attr("action",url+"/examPaper/downLoadDBF");
	
   	var input1=$("<input>");
   	input1.attr("type","hidden");
   	input1.attr("name","batchId");
   	input1.attr("value",batchId);
   	
   	var input2=$("<input>");
   	input2.attr("type","hidden");
   	input2.attr("name","name");
   	input2.attr("value",name);
   	
	if (row){
		var rows = $('#usedPapersDG').datagrid("getSelections");
		for(var i =0;i<rows.length;i++){
			arrCode.push(rows[i].code);
		}

		var input3=$("<input>");
       	input3.attr("type","hidden");
       	input3.attr("name","arrCode");
       	input3.attr("value",arrCode);
       	
       	$("body").append(form);//将表单放置在web中
       	form.append(input1);
       	form.append(input2);
       	form.append(input3);
       	form.submit();//表单提交 
	}else{
		$.messager.confirm("操作提示", "是否选择下载全部试卷信息?", function (data) {
			if (data) {
				if(total!=0){
			       	$("body").append(form);//将表单放置在web中
			       	form.append(input1);
			       	form.append(input2);
			       	form.submit();//表单提交 
				}
			}
		});
	}
}

function downLoadExcel(url,batchId){
	var form=$("<form>");//定义一个form表单
   	form.attr("style","display:none");
   	form.attr("target","");
   	form.attr("method","post");
   	form.attr("enctype","multipart/form-data");
   	form.attr("action",url+"/examPaper/downExcel");
   	var input1=$("<input>");
   	input1.attr("type","hidden");
   	input1.attr("name","batchId");
   	input1.attr("value",batchId);
   	
   	$("body").append(form);//将表单放置在web中
   	form.append(input1);
   	form.submit();//表单提交 
}

function downPassword(url){
	var form=$("<form>");//定义一个form表单
   	form.attr("style","display:none");
   	form.attr("target","");
   	form.attr("method","post");
   	form.attr("enctype","multipart/form-data");
   	form.attr("action",url+"/examSetting/downPasswordExcel");
   	
   	$("body").append(form);//将表单放置在web中
   	form.submit();//表单提交 
}


function downLoadPaper(name,url,batchId){
	var options = $('#usedPapersDG').datagrid('getPager').data("pagination").options;
	var total = options.total;
	
	var arrCode=new Array();
	
	var status;
	var flag=true;
	if(name=='QYKJS'){
		status='DRAFT';
	}else if(name=='CJ'){
		status='FORMAL';
	}
	
	var row = $('#usedPapersDG').datagrid('getSelected');
	if (row){
		
		var selectedRows = $('#usedPapersDG').datagrid('getSelections');
		//验证下载的状态
    	for(var i = 0; i < selectedRows.length; i++){
            if(selectedRows[i].status!=status){
            	flag=false;
            }
        }
    	
    	if(flag){
    		var obj={
            		"batchId" : batchId
            	};
    		$.ajax({
    			type : "POST",
    			url : url+"/examSetting/validateCodeBook",
    			data :  JSON.stringify(obj) ,
    			contentType : "application/json; charset=utf-8",
    			dataType : "json",
    			success : function(callback) {
    				callback=eval(callback);
    				if(callback.result=='success'){
    					$(document).mask('正在下载，请稍等...');
    					var rows = $('#usedPapersDG').datagrid("getSelections");
    					for(var i =0;i<rows.length;i++){
    						arrCode.push(rows[i].code);
    					}
    					var obj={
	    						"batchId":batchId,
	    						"arrCode":arrCode,
	    						"name" : name
	    					}
    					$.ajax({
        	    			type : "POST",
        	    			url : url+"/examPaper/downLoadPaper",
        	    			data :  JSON.stringify(obj) ,
        	    			contentType : "application/json; charset=utf-8",
        	    			dataType : "json",
        	    			success : function(res) {
        	    				res=eval(res);
        	    				if(res.type=="success"){
        	    					$(document).unmask();
        	    					var form=$("<form>");//定义一个form表单
        	    			       	form.attr("style","display:none");
        	    			       	form.attr("target","");
        	    			       	form.attr("method","post");
        	    			       	form.attr("enctype","multipart/form-data");
        	    			       	form.attr("action",url+"/examPaper/beginDown");
        	    			       	var input1=$("<input>");
        	    			       	input1.attr("type","hidden");
        	    			       	input1.attr("name","paperPath");
        	    			       	input1.attr("value",res.downLoadPath);
        	    			       	
        	    			       	var input3=$("<input>");
        	    			       	input3.attr("type","hidden");
        	    			       	input3.attr("name","name");
        	    			       	input3.attr("value",res.zipName);
        	    			       	
        	    			       	$("body").append(form);//将表单放置在web中
        	    			       	form.append(input1);
        	    			       	form.append(input3);
        	    			       	form.submit();//表单提交 
        	    				}else{
        	    					$(document).unmask();
        	    					$.messager.alert('提示','下载试卷失败!','error');
        	    				}
        	    			}
    					});
    				}else{
    					$.messager.alert("操作提示", "下载失败,密码本密码已用完,请重新生成可用的密码本","error");
    				}
    			}
    		});
    	}else{
    		if(status=='FORMAL'){
    			$.messager.alert('提示','无法下载操作,选中行包含状态为非清样的试卷','error');
        	}else if(status=='USED'){
        		$.messager.alert('提示','无法下载操作,选中行包含状态为非启用的试卷','error');
        	}
    		
    	}
	}else{
		$.messager.confirm("操作提示", "是否选择下载全部试卷?", function (data) {
            if (data) {
            	
            	if(total!=0){
            		
            		var allRows = $('#usedPapersDG').datagrid('getRows');
            		
                	for(var i = 0; i < allRows.length; i++){
                        if(allRows[i].status!=status){
                        	flag=false;
                        }
                    }
                	if(flag){
                		var obj={
                        		"batchId" : batchId
                        	};
                		$.ajax({
                			type : "POST",
                			url : url+"/examSetting/validateCodeBook",
                			data :  JSON.stringify(obj) ,
                			contentType : "application/json; charset=utf-8",
                			dataType : "json",
                			success : function(callback) {
                				callback=eval(callback);
                				if(callback.result=='success'){
                					$(document).mask('正在下载，请稍等...');
                    				var obj={
                    					"batchId" :batchId
                    				};
                    				$.ajax({
                    	    			type : "POST",
                    	    			url : url+"/examPaper/makeZIPFile",
                    	    			data :  JSON.stringify(obj) ,
                    	    			contentType : "application/json; charset=utf-8",
                    	    			dataType : "json",
                    	    			success : function(callback) {
                    	    				callback=eval(callback);
                    	    				if(callback.type=="success"){
                    	    					var obj={
                    	    						"batchId":batchId,
                    	    						"name":name
                    	    					}
                    	    					$.ajax({
                                	    			type : "POST",
                                	    			url : url+"/examPaper/downLoadPaper",
                                	    			data :  JSON.stringify(obj) ,
                                	    			contentType : "application/json; charset=utf-8",
                                	    			dataType : "json",
                                	    			success : function(res) {
                                	    				res=eval(res);
                                	    				if(res.type=="success"){
                                	    					$(document).unmask();
                                	    					var form=$("<form>");//定义一个form表单
                                	    			       	form.attr("style","display:none");
                                	    			       	form.attr("target","");
                                	    			       	form.attr("method","post");
                                	    			       	form.attr("enctype","multipart/form-data");
                                	    			       	form.attr("action",url+"/examPaper/beginDown");
                                	    			       	var input1=$("<input>");
                                	    			       	input1.attr("type","hidden");
                                	    			       	input1.attr("name","paperPath");
                                	    			       	input1.attr("value",res.downLoadPath);
                                	    			       	
                                	    			       	var input3=$("<input>");
                                	    			       	input3.attr("type","hidden");
                                	    			       	input3.attr("name","name");
                                	    			       	input3.attr("value",res.zipName);
                                	    			       	
                                	    			       	$("body").append(form);//将表单放置在web中
                                	    			       	form.append(input1);
                                	    			       	form.append(input3);
                                	    			       	form.submit();//表单提交 
                                	    				}else{
                                	    					$(document).unmask();
                                	    					$.messager.alert('提示','下载试卷失败!','error');
                                	    				}
                                	    			}
                    	    					});
                    	    				}
                    	    			}
                    				});
                				}else{
                					$.messager.alert("操作提示", "下载失败,密码本密码已用完,请重新生成可用的密码本","error");
                				}
                			}
                		});
                	}else{
                		if(status=='FORMAL'){
                			$.messager.alert('提示','无法下载操作,选中行包含状态为非清样的试卷','error');
                    	}else if(status=='USED'){
                    		$.messager.alert('提示','无法下载操作,选中行包含状态为非启用的试卷','error');
                    	}
                		
                	}
            		
    			}else{
    				$.messager.alert('提示','该批次下无可下载的试卷!');
    			}
            }
        });
	}
}

	function checkCode(url,operation,id,batchId){
		var code=$("#"+id).val();
		if(code==""){
			$.messager.alert('提示','试卷编号不能为空!');
			$("#"+id).focus();
			return false;
		}else{
			var ur="";
			$("#passBtn").focus();
			var obj={
    				"code" : code,
    				"batchId" : batchId
    			};
    		var PaperParams = JSON.stringify(obj);
			if(operation=="入库"){
				ur=url+"/examPaper/instorage";
				
			}else if(operation=="出库"){
				ur=url+"/examPaper/outbound";
			}
			$.ajax({
				type : "POST",
				url : ur,
				data : PaperParams,
				contentType : "application/json; charset=utf-8",
				dataType : "json",
				success : function(callback) {
					callback=eval(callback);
					
					if(callback.type=="fail"&&operation=="入库"){
						$('#dg').datagrid('reload');
						$("#"+id).val("");
						$("#promptW3").css("color","red");
						$("#promptW3").css("font-size","18px");
						$("#promptW3").html("扫描结果:请上传 "+code+" " + callback.message);
						$("#promptW3").show();
						$("#"+id).focus();
						$("#infoW3").hide();
						$("#sound").attr("src",url+"/resources/sound/scanfail.wav");
					}else if(callback.type=="success"&&operation=="入库"){
						$("#"+id).val("");
						$("#promptW3").css("color","green"); 
						$("#promptW3").css("font-size","18px");
						$("#promptW3").html("扫描结果:试卷编号 "+code+" 入库扫描成功！");
						$("#lastW3").val(code);
						$("#promptW3").show();
						$("#"+id).focus();
						$("#infoW3").show();
						$("#sound").attr("src",url+"/resources/sound/scansuccess.wav");
						//var Rhtml='<table class="listTable" style="border:solid 1px #000000"><tr><td>试卷编码</td><td>课程代码</td><td>课程名称</td><td>教材名称</td><td>作者</td><td>出版社</td><td>版次</td><td>学校</td></tr>'
						var Rhtml='<table id="skelTbl"><tr><td>试卷编码</td><td>课程代码</td><td>课程名称</td><td>教材名称</td><td>编者</td><td>出版社</td><td>版次</td><td>学校</td></tr>'
						+'<tr><td>'+callback.paper.code+'</td><td>'+callback.paper.courseCode+'</td><td>'+callback.paper.courseName+'</td><td>'+callback.paper.bookName+'</td><td>'+callback.paper.bookAuthor+'</td><td>'+callback.paper.bookPress+'</td><td>'+callback.paper.bookPressYear+'</td><td>'+callback.paper.school+'</td></tr></table>';
						$("#infoW3").html(Rhtml);
					}else if(callback.type=="success"&&operation=="出库"){
						$("#"+id).val("");
						$("#promptW4").css("color","green"); 
						$("#promptW3").css("font-size","18px");
						$("#promptW4").html("扫描结果:试卷编号 "+code+" 出库扫描成功");
						$("#lastW4").val(code);
						$("#promptW4").show();
						$("#"+id).focus();
						$("#infoW4").show();
						var Rhtml='<table  id="skelTbl"><tr><td>试卷编码</td><td>课程代码</td><td>课程名称</td><td>教材名称</td><td>编者</td><td>出版社</td><td>版次</td><td>学校</td></tr>'
							+'<tr><td>'+callback.paper.code+'</td><td>'+callback.paper.courseCode+'</td><td>'+callback.paper.courseName+'</td><td>'+callback.paper.bookName+'</td><td>'+callback.paper.bookAuthor+'</td><td>'+callback.paper.bookPress+'</td><td>'+callback.paper.bookPressYear+'</td><td>'+callback.paper.school+'</td></tr></table>';
						$("#infoW4").html(Rhtml);
						$("#sound").attr("src",url+"/resources/sound/scansuccess.wav");
					}else if(callback.type=="fail"&&operation=="出库"){
						$("#"+id).val("");
						$("#promptW4").css("color","red"); 
						$("#promptW3").css("font-size","18px");
						$("#promptW4").html("扫描结果:试卷编号 "+code+" 在当前批次不存在!");
						$("#promptW4").show();
						$("#"+id).focus();
						$("#infoW4").hide();
						$("#sound").attr("src",url+"/resources/sound/scanfail.wav");
					}
					$('#dg').datagrid('reload');
					$('#usedPapersDG').datagrid('reload');
				}
			});
			return false;
		}
	}
	
	
	
	function addPapers(url,batchId){
        window.location.href = url+"/examPaper/batchPapers/addPapers/"+batchId;
    }
	
	function printBatchPaperInfo(url,batchId){
		var win = open();
		win.location.href = url+"/examPaper/batchPaperInfoPrint/"+batchId;
	}