<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ include file="../common/init.jsp"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel='stylesheet' href='${ctx}/resources/css/easyui.css' type='text/css' media='screen' />
<link rel='stylesheet' href='${ctx}/resources/css/easyui/icon.css' type='text/css' media='screen' />

<%@ include file="../common/top.jsp"%>
<script type="text/javascript" src="${ctx}/resources/js/jquery.easyui.min.js"></script>
<script type="text/javascript" src="${ctx}/resources/js/easyui-lang-zh_CN.js"></script>
<%@ include file="../common/validation.jsp"%>
<title>批次管理</title>

<script language="javascript">
$(document).ready(function(){
    $('#search-form').submit(function(event){
        event.preventDefault(); 
        var param = $('#search-form').serializeJson();
        param = $.extend(param, {page:1,rows:10});
        $('#dg').datagrid('load',param);
    });
    
    $("#searchBtn").click(function(){
    	$('#search-form').submit();
    });
});

$.extend($.fn.validatebox.defaults.rules, {
    md: {
        validator: function(value, param){
            var d1 = $.fn.datebox.defaults.parser(param[0]);
            var d2 = $.fn.datebox.defaults.parser(value);
            return d2<=d1;
        },
        message: 'The date must be less than or equals to {0}.'
    }
});

function cellStyler(value,row,index){
    return 'color:blue;text-decoration:underline;';
}
function formatDate(date){
	var d=undefined;
	if(typeof(date)=="undefined"){
		d=new Date();
	}else{
		d = new Date(date);
	}
	return (d.getFullYear()+"-"+(d.getMonth()+1)+"-"+d.getDate());
}

function removeBatch(){
	var row = $('#dg').datagrid('getSelected');
	if (row){
		var obj={
        		"batchId" : row.id
        	};
		var PaperParams=JSON.stringify(obj);
		$.ajax({
			type : "POST",
			url : "${ctx}/examPaper/validateRemoveBatch",
			data :  PaperParams ,
			contentType : "application/json; charset=utf-8",
			dataType : "json",
			success : function(callback) {
				callback=eval(callback);
				if(callback.type=="success"){
					$.ajax({
						type : "POST",
						url : "${ctx}/examPaper/removeBatch",
						data :  PaperParams ,
						contentType : "application/json; charset=utf-8",
						dataType : "json",
						success : function(callback) {
							callback=eval(callback);
							if(callback.type=="success"){
								$.messager.alert('提示','删除批次成功');
								$('#dg').datagrid('reload');
							}
						}
					});
				}else{
					$.messager.confirm("操作提示", "该批次下存在关联的试卷,确定删除该批次吗?", function (data) {
        	            if (data) {
        	            	var obj1={
    				        		"batchId" : row.id,
    				        		"deleteBatch":"true"
    				        	};
    						PaperParams=JSON.stringify(obj1);
    						$.ajax({
    							type : "POST",
    							url : "${ctx}/examPaper/removeBatch",
    							data :  PaperParams ,
    							contentType : "application/json; charset=utf-8",
    							dataType : "json",
    							success : function(callback) {
    								callback=eval(callback);
    								if(callback.type=="success"){
    									$.messager.alert('提示','删除批次成功');
    									$('#dg').datagrid('reload');
    								}
    							}
    						});
        	            }
        			});
				}
			}
		});
	}else{
		$.messager.alert('提示','请选择要删除的批次','error');
	}
}

</script>
</head>
<body>
<div class="container-fluid">
    <%@ include file="../common/header.jsp"%>
    <div class="row-fluid">
        <%@ include file="../common/sub_menu.jsp"%>
        
        <div class="span10">
			<ul class="breadcrumb">
	            <li class="active">批次管理</li>
            </ul>
            
	        <div class="page-body">
	           	 <div class="change">
		            <form id="search-form" method="post" >
			              	<ul>
				               <li><span>批次代码</span><input class="input-medium" type="text" name="code"  id="code" placeholder="批次代码"></li>
				               <!-- 
				               <li><span>批次开始日期</span><input name="startDate" id="startDate" class="easyui-datebox" placeholder="批次开始日期" data-options="editable:false"/></li>
				               <li><span>批次结束日期</span><input name="endDate" id="endDate" class="easyui-datebox" placeholder="批次结束日期" data-options="editable:false"/></li>
				                -->
				               <li><span>批次类型</span>
				               		<select class="select-medium" name="type">
				               			<option value="all">全部</option>
				               			<option value="${batchType_ruku }">${batchType_ruku }</option>
				               			<option value="${batchType_qingyang }">${batchType_qingyang }</option>
				               			<option value="${batchType_qiyong }">${batchType_qiyong }</option>
				               			<option value="${batchType_gongjuan }">${batchType_gongjuan }</option>
			               			</select>
		               			</li>
					             <li><a id="searchBtn" href="#" type="submit" class="btn"><i class="icon-search"></i> 查询</a></li>
			             	</ul>
		            </form>
		         </div>
				<div style="clear:both; margin-bottom:10px;"></div>
		        
		        <div class="right" style="min-height:300px;position: relative;">
		             <div id="list-wrap posts" class="listview">
		                 <table id="dg" class="easyui-datagrid"
		                     data-options="
		                       url:'${ctx}/examPaper/queryBatch', 
		                       fitColumns:true
		                       ,singleSelect:true
		                       ,striped:true
		                       ,pagination:true
		                       ,toolbar: '#tb'
		                       ,onClickCell:onClickCell
		                       ">
		                     <thead>
		                         <tr class="title">
		                         	 <th rowspan="2" data-options="field:'ck',checkbox:true"></th>
		                         	 <th data-options="field:'id' " style="display: none">批次ID</th>
		                             <th data-options="field:'code',width:80,
		                               styler:cellStyler,
		                               editor:{
		                                   type:'validatebox',
		                                   options:{
		                                       required:true
		                                       }
		                                   }">批次代码</th>
		                             <th data-options="field:'type',width:60,
		                               editor:{
				                            type:'combobox',
				                            options:{
					                            panelHeight:'110',
				                                data:[{typeValue:1,typeName:'${batchType_ruku }'}
				                                     ,{typeValue:2,typeName:'${batchType_qingyang }'}
				                                     ,{typeValue:3,typeName:'${batchType_qiyong }'}
				                                     ,{typeValue:4,typeName:'${batchType_gongjuan }'}],
				                                valueField:'typeName',
				                                editable:false,
	                                            textField:'typeName',
				                                required:true
				                            }
				                        }">类型</th>
		                             <th data-options="field:'startDate',width:100,editor:{type:'datebox',options:{editable:false,required:true}},formatter: formatDate">开始日期</th>
		                             <th data-options="field:'endDate',width:100,editor:{type:'datebox',options:{editable:false,required:true}},formatter: formatDate ">结束日期</th>
		                             <th data-options="field:'admin',width:80,editor:'text'">负责人</th>
		                             <th data-options="field:'remark',width:150,editor:'text'">备注</th>
		                             <th data-options="field:'createdTime',width:150,formatter: formatDate">创建日期</th>
		                             <th data-options="field:'updatedTime',width:150,formatter: formatDate">更新日期</th>
		                         </tr>
		                     </thead>
		                   </table>
		                   
		                    <div id="tb" style="height:auto">
						        <a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'easyui-icon-add',plain:true" onclick="append()">添加批次</a>
						        <a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'easyui-icon-save',plain:true" onclick="accept()">保存</a>
						        <a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'easyui-icon-cancel',plain:true" onclick="reject()">撤销</a>
						        <a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'easyui-icon-remove',plain:true" onclick="removeBatch()">删除批次</a>
						    </div>
		               </div>
		            </div>
		        </div>
       	 	</div>
    	</div>
    </div>
    <div id="footer">版权所有：武汉启明泰和软件服务有限公司</div>
    <script type="text/javascript">
        var editIndex = undefined;
        var rowIndex;
        function endEditing(){
            if (editIndex == undefined){return true;}
            if ($('#dg').datagrid('validateRow', editIndex)){
            	rowIndex=editIndex;
                var ed = $('#dg').datagrid('getEditor', {index:editIndex,field:'type'});
                var type = $(ed.target).combobox('getText');
                $('#dg').datagrid('getRows')[editIndex]['type'] = type;
                $('#dg').datagrid('endEdit', editIndex);
                editIndex = undefined;
                return true;
            } else {
                return false;
            }
        }
        function onDblClickRow(index){
            if (editIndex != index){
                if (endEditing()){
                    $('#dg').datagrid('selectRow', index)
                            .datagrid('beginEdit', index);
                    editIndex = index;
                    var code=$('#dg').datagrid('getRows');
                } else {
                    $('#dg').datagrid('selectRow', editIndex);
                }
            }
        }
        function append(){
            if (endEditing()){
                $('#dg').datagrid('appendRow',{status:'P'});
                editIndex = $('#dg').datagrid('getRows').length-1;
                $('#dg').datagrid('selectRow', editIndex).datagrid('beginEdit', editIndex);
            }
        }
        function removeit(){
            if (editIndex == undefined){return};
            $('#dg').datagrid('cancelEdit', editIndex)
                    .datagrid('deleteRow', editIndex);
            editIndex = undefined;
        }
        
        function dateCompare(startdate,enddate){   
	        var date1=Date.parse(startdate.replace(/-/g,"/"));
	        var date2=Date.parse(enddate.replace(/-/g,"/"));
	        
	        return date2 >= date1;
         }  
        function accept(){
        	 if (endEditing()){
                 var code=$('#dg').datagrid('getRows')[rowIndex]['code'];
                 var type=$('#dg').datagrid('getRows')[rowIndex]['type'];
                 
                 var startDate=$('#dg').datagrid('getRows')[rowIndex]['startDate'];
                 if(startDate=="")startDate=new Date();
                 
                 var endDate=$('#dg').datagrid('getRows')[rowIndex]['endDate'];
                 if(endDate=="")endDate=new Date();
                 
                 var admin=$('#dg').datagrid('getRows')[rowIndex]['admin'];
                 
                 var createdTime=$('#dg').datagrid('getRows')[rowIndex]['createdTime'];
                 if(typeof(createdTime)=="undefined")createdTime=new Date();
                 
                 
                 var updatedTime=$('#dg').datagrid('getRows')[rowIndex]['updatedTime'];
                 if(typeof(updatedTime)=="undefined")updatedTime=new Date();
                 
                 var remark=$('#dg').datagrid('getRows')[rowIndex]['remark'];
                 if(dateCompare(startDate,endDate)){
                 	obj = {
         					"code" : code,
         					"type" : type,
         					"startDate" : startDate,
         					"endDate" : endDate,
         					"admin" : admin,
         					"createdBy" : "${web_session_user.id}",
         					"createdTime" : createdTime,
         					"updatedBy" : "${web_session_user.id}",
         					"updatedTime" : updatedTime,
         					"remark" :remark
         				};
                     var PaperBatch = JSON.stringify(obj);
                     $.ajax({
                 		type : "POST",
                 		url : "${ctx}/examPaper/saveBatch",
                 		data : PaperBatch,
                 		contentType : "application/json; charset=utf-8",
                 		dataType : "json",
                 		success : function(callback) {
                 			callback=eval(callback);
                 			if(callback.result=="fail"){
                 				$.messager.alert("操作提示", "批次代码不允许与列表重复,请修改后再进行保存!","error");
                 				$('#dg').datagrid('selectRow', rowIndex).datagrid('beginEdit', rowIndex);
                 				//$('#dg').datagrid('rejectChanges');
                 	            //editIndex = undefined;
                 			}else{
                 				//$('#dg').datagrid('acceptChanges');
                 				$('#dg').datagrid('reload');
                 			}
                 		}
                 	});
                 }else{
                	 $('#dg').datagrid('selectRow', rowIndex).datagrid('beginEdit', rowIndex);
                	//$('#dg').datagrid('rejectChanges');
      	            //editIndex = undefined;
                 	$.messager.alert('提示','开始日期不能大于结束日期','error');
                 }
         	}
        }
        function reject(){
            $('#dg').datagrid('rejectChanges');
            editIndex = undefined;
        }
        function onClickCell(index, field){
        	if(field=="code"){
        		var batchId = $('#dg').datagrid('getRows')[index]['id'];
        		window.location.href = "${ctx}/examPaper/batchPapers/"+batchId ;
        	}
        }
    </script>
</body>
</html>