<%@ 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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>任务批次</title>
<link rel="stylesheet" href="${ctx}/resources/css/main.css"
	type="text/css" />
<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' />
<link rel='stylesheet' href='${ctx}/resources/css/user-center-style.css'
	type='text/css' media='screen' />
<style>
.tongjiTab td {
	border: 1px solid #999999;
}

.first {
	width: 100px;
	height: 25px;
	text-align: center;
}

.second {
	width: 280px;
	height: 25px;
	text-align: center;
}

.myTitleTd {
	font-size: 12px;
	font-weight: normal;
	width: 100px;
	height: 25px;
	text-align: right;
}

.myValueTd {
	font-size: 12px;
	font-weight: normal;
	text-align: left;
}

.myValueTd input[type=text] {
	width: 200px;
}

.myValueTd textarea {
	width: 200px;
	height: 50px;
}

.myValueTd select {
	width: 200px;
}

.myValueTd label {
	color: red;
}

.formErrorContent {
	display: none;
}

.batchBtn {
	width: 50px;
	height: 30px;
}
</style>
</head>
<%@ 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/validator.js"></script>
<script type="text/javascript"
	src="${ctx}/resources/js/easyui-lang-zh_CN.js"></script>
<script language="javascript" type="text/javascript"
	src="${ctx}/resources/js/My97DatePicker/WdatePicker.js"></script>
<script type="text/javascript"
	src="${ctx}/resources/js/swfupload/swfupload.js"></script>
<script type="text/javascript"
	src="${ctx}/resources/js/swfupload/swfupload.queue.js"></script>
<script type="text/javascript"
	src="${ctx}/resources/js/swfupload/uploadHandlers.js"></script>
<script type="text/javascript">
function loadTaskSwfUpload() {
	new SWFUpload({
		 upload_url :"${ctx}/business/importTask",
		 post_params: {"id" : $("#batchId").val(),"name":$("#name").val(),"planStartTime":$("#planStartTime").val(),"planEndTime":$("#planEndTime").val(),"userId":${web_session_user.id }},
		 use_query_string : false,
		  
		// File Upload Settings
		file_size_limit : "100 MB",	// 100MB
		file_types : "*.xls;*.xlsx",
		file_types_description : "所有文件",
		file_upload_limit : "0",

		file_queue_error_handler : fileQueueError,
		file_dialog_complete_handler : fileDialogComplete,//选择好文件后提交
		upload_progress_handler : uploadProgress,
		upload_error_handler : uploadError,
		upload_success_handler : uploadTaskSuccess,
		upload_complete_handler : uploadComplete,
		
		// Button Settings
		button_image_url : '${ctx}/resources/images/SmallSpyGlassWithTransperancy_17x18.png',
		button_placeholder_id : "spanButtonPlaceholder",
		button_width: 300,
		button_height: 18,
		button_text : '<span class="button">导入任务(*导入的文件必须要与“批次类型”一致)<span class="buttonSmall"></span></span>',
		button_text_style : '.button { font-family: Helvetica, Arial, sans-serif; font-size: 12px; } .buttonSmall { font-size: 10px; color: #ff0000;}',
		button_text_top_padding: 0,
		button_text_left_padding: 18,
		button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,
		button_cursor: SWFUpload.CURSOR.HAND,
		
		
		// Flash Settings
		flash_url : '${ctx}/resources/js/swfupload/swfupload.swf',

		custom_settings : {
			upload_target : "importDivFileProgressContainer"
		},
		// Debug Settings
		debug: false //是否显示调试窗口
	});
};

function uploadTaskSuccess(file, serverData) {
	$(document).unmask();
	serverData=eval('(' + serverData + ')');
	if(serverData.result=='fail'){
		$("#success").hide();
		$("#firstTd").html(serverData.lineNum);
		$("#secondTd").html(serverData.msg);
		$("#error").show();
	}else if(serverData.result=='success'){
		$("#success").html("成功创建"+serverData.successNum+"条任务单记录");
		$("#success").show();
		$("#error").hide();
		$('#dg').datagrid('reload');
	}else{
		$("#firstTd").html("-");
		$("#secondTd").html(serverData.msg);
	}
}

function loadRevertSwfUpload() {
	new SWFUpload({
		 upload_url :"${ctx}/attachment/upload",
		 post_params: {"userId":"${sessionScope.web_session_user.id}"},
		 use_query_string : false,
		  
		// File Upload Settings
		file_size_limit : "100 MB",	// 100MB
		
		file_types : "*.qrzk",
		file_types_description : "启明泰和数据文件",
		file_upload_limit 	:	0,

		file_queue_error_handler : fileQueueError,
		file_dialog_complete_handler : fileDialogComplete,//选择好文件后提交
		upload_progress_handler : uploadProgress,
		upload_error_handler : uploadError,
		upload_success_handler : uploadRevertSuccess,
		upload_complete_handler : uploadComplete,
		
		// Button Settings
		button_image_url : '${ctx}/resources/images/SmallSpyGlassWithTransperancy_17x18.png',
		button_placeholder_id : "spanRevertButtonPlaceholder",
		button_width: 180,
		button_height: 18,
		button_text : '<span class="button">点击这里上传备份文件<span class="buttonSmall"></span></span>',
		button_text_style : '.button { font-family: Helvetica, Arial, sans-serif; font-size: 12px; } .buttonSmall { font-size: 10px; color: #ff0000;}',
		button_text_top_padding: 0,
		button_text_left_padding: 18,
		button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,
		button_cursor: SWFUpload.CURSOR.HAND,
		button_action: SWFUpload.BUTTON_ACTION.SELECT_FILE,
		
		
		// Flash Settings
		flash_url : '${ctx}/resources/js/swfupload/swfupload.swf',

		custom_settings : {
			upload_target : "importDivFileProgressContainer"
		},
		// Debug Settings
		debug: false //是否显示调试窗口
	});
};

function uploadRevertSuccess(file, serverData) {
	$(document).unmask();
	serverData=eval('(' + serverData + ')');
	if(serverData.flag=='success'){
		$("#uploadedRevertFileName").text("已上传文件：" + serverData.att.originalName);
		$("#uploadedRevertAttId").val(serverData.att.id);
		$("#confirmUploadedRevert").attr("disabled",false);
	}else{
		$.messager.alert('提示',serverData.msg,'error');
	}
}

function loadDg(){
	$('#dg').datagrid({
		url:'${ctx}/business/queryBatch'
    });
}

$(function(){
	$(window).resize(function(){
		qmth_layout();
		$('#mm1').height(44);
	});
	
	$("#downTemplate").on('click',function(){
		//window.location.href="${ctx}/resources/downloads/命题任务单导入模板.xls";
	});
	
	$("#downMingTiTmp").on('click',function(){
		window.location.href="${ctx}/resources/downloads/命题任务单导入模板.xls";
	});

	$("#downShenTiTmp").on('click',function(){
		window.location.href="${ctx}/resources/downloads/审题任务单导入模板.xls";
	});
	
	$("#viewTasksBtn").click(function(){
		var rowData = $("#dg").datagrid('getSelected');
		if(rowData != null){
			if(rowData.batchType == 'RU_WEI_MING_TI'){
				var url = "${ctx}/business/paperTaskList/"+rowData.id;
				window.location.href = url;
			}else{
				var url = "${ctx}/business/auditQuesTaskList/"+rowData.id;
				window.location.href = url;
			}
		}
		
	});
	
	$("#emptyData").click(function(){
		$.messager.confirm("操作提示", "您确定要清空数据吗，系统将清空所有的试题数据和任务数据，请先做好备份工作", function (data) {
			if (data) {
				$.messager.confirm("操作提示", "再次确认是否要清空数据，系统将清空所有的试题数据和任务数据，请先做好备份工作", function (data) {
					$(document).mask('正在清空数据，请稍等...');
					$.ajax({
						type : "POST",
			    		url : "${ctx}/business/emptyData",
			    		data : {},
						success : function(callback) {
							$(document).unmask();
							if(callback.flag == 'success'){
								$.messager.alert('提示', '操作成功!', 'info');
								$('#dg').datagrid('reload');
							}else{
								$.messager.alert('提示', callback.msg, 'error');
							}
						}
					});
				});
			}
		});
	});
	
	$("#dg").datagrid({
	    onDblClickRow: function (rowIndex, rowData) {
	    	$("#viewTasksBtn").click();
	    }
	});
	
	 $("#addBatchBtn").on('click',function(){
	    	$("#addTaskBatchDiv").window('open');
	    });
	 $("#cancleEditBtn").on('click',function(){
		 $("#addTaskBatchDiv").window('close');
	 });
	 $("#importBtn").on('click',function(){
		 var row = $('#dg').datagrid('getSelected');
		 if(row){
			 $("#importTaskDiv").window('open'); 
			 $("#error").hide();
			 $("#batchId").val(row.id);
			 $("#name").val(row.name);
			 $("#planStartTime").val(row.planStartTime);
			 $("#planEndTime").val(row.planEndTime);
			 loadTaskSwfUpload();
		 }else{
			 $.messager.alert('提示','请选择要导入的任务批次','error');			 
		 }
		 
	 });
	 $("#saveEditBtn").on('click',function(){
		 var planStartTime=$("#planStartTime").val();
		 var planEndTime=$("#planEndTime").val();
		 var name=$("#name").val();
		 var batchType=$("#batchType").val();
		 
		 if(name==''||planStartTime==''||planEndTime==''){
			 $.messager.alert('提示', "请输入完整的任务批次信息", 'error');
		 }else{
			 if(dateCompare(planStartTime,planEndTime)){
				 var param={
						 "name":name,
						 "planStartTime":planStartTime,
						 "planEndTime":planEndTime,
						 "batchType":batchType
				 };
				 $(document).mask('正在保存数据，请稍等...');
				$.ajax({
					type : "POST",
					url : "${ctx}/business/addTaskBatch",
					data : param, 
					success : function(callback) {
						$(document).unmask();
						if(callback.flag == 'success'){
							$.messager.alert('提示', '添加成功!', 'info');
							$("#addTaskBatchDiv").window('close');
							$('#dg').datagrid('reload');
						}else{
							$.messager.alert('提示', "新增任务批次失败，请稍后操作!", 'error');
						}
					}
				});  
			 }else{
				 $.messager.alert('提示','开始日期不能大于结束日期','error');
			 }
		 }
	 });
	 
	 $("#saveModifyEditBtn").on('click',function(){
		 var planStartTime=$("#planStartTimeForEdit").val();
		 var planEndTime=$("#planEndTimeForEdit").val();
		 var name=$("#nameForEdit").val();
		 
		 if(name==''||planStartTime==''||planEndTime==''){
			 $.messager.alert('提示', "请输入完整的任务批次信息", 'error');
		 }else{
			 if(dateCompare(planStartTime,planEndTime)){
				 var param={
						 "id":$("#idForEdit").val(),
						 "name":name,
						 "planStartTime":planStartTime,
						 "planEndTime":planEndTime
				 };
				 $(document).mask('正在保存数据，请稍等...');
				$.ajax({
					type : "POST",
					url : "${ctx}/business/updateTaskBatch",
					data : param, 
					success : function(callback) {
						$(document).unmask();
						if(callback.flag == 'success'){
							$.messager.alert('提示', '修改成功!', 'info');
							$("#modifyTaskBatchDiv").window('close');
							$('#dg').datagrid('reload');
						}else{
							$.messager.alert('提示', "修改任务批次失败，请稍后操作!", 'error');
						}
					}
				});  
			 }else{
				 $.messager.alert('提示','开始日期不能大于结束日期','error');
			 }
		 }
	 });
	 
	 $("#exportTask").click(function(){
			var rowData = $("#dg").datagrid('getSelected');
			if(rowData != null){
				var url = "${ctx}/business/taskList/"+rowData.id;
				$(document).mask('正在生成导出数据文件，请稍等...');
		    	$.ajax({
		    		type : "POST",
		    		url : "${ctx}/business/exportTask/"+rowData.id,
		    		data : {}, 
		    		success : function(res) {
		    			$(document).unmask();
		    			if(res.flag=='success'){
		    				$("#downloadForm").attr("action","${ctx}/attachment/download/" + res.att.id);
		    				$("#downloadForm").submit();
		    			}else{
		    				$.messager.alert('提示', "生成导出数据文件失败，请刷新后操作!", 'error');
		    			}
		    		}
		    	});
			}else{
				 $.messager.alert('提示','请选择要导出备份的任务批次','error');			 
			 }
		});
	loadRevertSwfUpload();
	$("#revertTask").click(function(){
		$("#uploadedRevertFileName").text("");
		$("#uploadedRevertAttId").val("");
		$("#confirmUploadedRevert").attr("disabled",true);
		$("#uploadRevertDiv").window('open'); 
	});
	
	$("#confirmUploadedRevert").click(function(){
		if($("#uploadedRevertAttId").val() == ""){
			$.messager.alert('提示', '请先上传备份文件！', 'error');
			return false;
		}
		$.messager.confirm("操作提示", "您确定要还原备份数据吗，系统会自动覆盖相同的数据，请先做好备份工作", function (data) {
	        if (data) {
	        	$(document).mask('正在提交数据，请稍等...');
				$.post('${ctx}/business/revertTask/' + $("#uploadedRevertAttId").val(),{},function(res){
					$(document).unmask();
					if(res.flag=='failed'){
			           $.messager.alert('提示', res.msg, 'error', function () {
			        	   //do nothing
			           });
			           return false;
					}else{
						reloadWin();
					}
				});
	        }
		});
    });
	
	$("#delTaskBatch").click(function(){
		var rowData = $("#dg").datagrid('getSelected');
		if(rowData == null){
			$.messager.alert('提示', '请选择一条任务批次后再删除！', 'error');
			return false;
		}
		$.messager.confirm("操作提示", "您确定要删除此任务批次吗？（注意：只能删除空的任务批次）", function (data) {
	        if (data) {
	        	$(document).mask('正在删除数据，请稍等...');
				$.post('${ctx}/business/delTaskBatch/' + rowData.id,{},function(res){
					$(document).unmask();
					if(res.flag=='failed'){
			           $.messager.alert('提示', res.msg, 'error', function () {
			        	   //do nothing
			           });
			           return false;
					}else{
						$('#dg').datagrid('reload');
					}
				});
	        }
		});
    });
	
	$("#modifyData").click(function(){
		var rowData = $("#dg").datagrid('getSelected');
		if(rowData == null){
			$.messager.alert('提示', '请选择一条任务批次后进行修改！', 'error');
			return;
		}
		$(document).mask('正在加载数据，请稍等...');
		$.post('${ctx}/business/getTaskBatch/' + rowData.id,{},function(res){
			$(document).unmask();
			$("#idForEdit").val(res.id);
			$("#nameForEdit").val(res.name);
			$("#batchTypeForEdit").val(res.batchType);
			$("#planStartTimeForEdit").val(formatDate(res.planStartTime));
			$("#planEndTimeForEdit").val(formatDate(res.planEndTime));
			$("#modifyTaskBatchDiv").window('open');
		});
	});
	
	$("#cancelUploadedRevert").click(function(){
    	$('#uploadRevertDiv').window('close');
		return false;
    });
	
	window.setTimeout(function(){loadDg();},200);
});
function dateCompare(startdate,enddate){   
    var arr=startdate.split("-");    
    var starttime=new Date(arr[0],arr[1],arr[2]);    
    var starttimes=starttime.getTime();   
      
    var arrs=enddate.split("-");    
    var lktime=new Date(arrs[0],arrs[1],arrs[2]);    
    var lktimes=lktime.getTime();   
      
    if(starttimes>=lktimes){   
		return false;   
	}else{
		return true;
	}
 }
</script>
<body>
	<%@ include file="../common/header.jsp"%>
	<div id="content" class="content">
		<%@ include file="../common/sub_menu.jsp"%>
		<div id="page">
			<div class="page-header">任务批次列表</div>
			<div class="page-body">
				<div id="tb">
					<a href="#" class="easyui-linkbutton" iconCls="icon-add"
						id="addBatchBtn">新建批次</a> <a href="#" class="easyui-linkbutton"
						iconCls="icon-search" id="viewTasksBtn">查看任务</a> <a href="#"
						class="easyui-linkbutton" iconCls="icon-upload" id="importBtn">导入任务</a>
					<a href="#" class="easyui-splitbutton"
						data-options="menu:'#mm1',plain:false,iconCls:'icon-download'"
						id="downTemplate">下载任务模板</a>
					<div id="mm1" style="width: 100px;">
						<div id="downMingTiTmp">命题任务模板</div>
						<div id="downShenTiTmp">审题任务模板</div>
					</div>
					<a href="#" class="easyui-linkbutton" iconCls="icon-remove"
						id="delTaskBatch">删除</a> <a href="#" class="easyui-linkbutton"
						iconCls="icon-export" id="exportTask">导出</a> <a href="#"
						class="easyui-linkbutton" iconCls="icon-import" id="revertTask">还原</a>
					<a href="#" class="easyui-linkbutton" iconCls="icon-empty"
						id="emptyData">清空</a> <a href="#" class="easyui-linkbutton"
						iconCls="icon-modify" id="modifyData">修改</a>
				</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="fitColumns:true,singleSelect:true,striped:true,pagination:true,toolbar: '#tb'">
							<thead>
								<tr class="title">
									<th data-options="field:'id',width:80">批次ID</th>
									<th data-options="field:'name',width:150">批次编号</th>
									<th data-options="field:'batchTypeName',width:150">批次类型</th>
									<th
										data-options="field:'planStartTime',width:70,formatter: formatDate">开始日期</th>
									<th
										data-options="field:'planEndTime',width:80,formatter: formatDate">结束日期</th>
									<th
										data-options="field:'createdTime',width:80,formatter: formatToNormalDateStr">创建时间</th>
								</tr>
							</thead>
						</table>
					</div>
				</div>
			</div>
		</div>
	</div>

	<div style="display: none;">
		<div id="addTaskBatchDiv" title="新增任务批次" class="easyui-window"
			data-options="modal:true,closed:true,iconCls:'icon-import'"
			style="width: 500px; height: 240px; padding: 10px; overflow: hidden;">
			<div id="barcode-scan" style="font-size: 12px;">
				<form action="#" id="formForEdit">
					<input type="hidden" name="id" id="idForEdit" />
					<table style="width: 450px;" cellpadding="5" border="0">
						<tr>
							<td class="myTitleTd">批次名称</td>
							<td class="myValueTd"><input type="text" name="name"
								id="name" maxlength="40" /><label>*</label></td>
						</tr>
						<tr>
							<td class="myTitleTd">批次类型</td>
							<td class="myValueTd"><select name="batchType"
								id="batchType">
									<c:forEach var="map" items="${taskBatchTypes }">
										<option value="${map.key}">${map.value}</option>
									</c:forEach>
							</select></td>
						</tr>
						<tr>
							<td class="myTitleTd">开始时间</td>
							<td class="myValueTd"><input type="text"
								name="planStartTime" id="planStartTime" maxlength="50"
								class="validate[required]" onclick='WdatePicker()'
								readonly="readonly" value="" /><label>*</label></td>
						</tr>
						<tr>
							<td class="myTitleTd">结束时间</td>
							<td class="myValueTd"><input type="text" name="planEndTime"
								id="planEndTime" maxlength="50" class="validate[required]"
								onclick='WdatePicker()' readonly="readonly" value="" /><label>*</label></td>
						</tr>

						<tr>
							<td colspan="2" align="center"><input type="button"
								id="saveEditBtn" value="保存" class="batchBtn" /> <input
								type="button" id="cancleEditBtn" value="取消" class="batchBtn" />
							</td>
						</tr>
					</table>
				</form>
			</div>
		</div>

		<div id="modifyTaskBatchDiv" title="修改任务批次" class="easyui-window"
			data-options="modal:true,closed:true,iconCls:'icon-import'"
			style="width: 500px; height: 240px; padding: 10px; overflow: hidden;">
			<div id="barcode-scan" style="font-size: 12px;">
				<form action="#" id="formForEdit">
					<input type="hidden" name="id" id="idForEdit" />
					<table style="width: 450px;" cellpadding="5" border="0">
						<tr>
							<td class="myTitleTd">批次名称</td>
							<td class="myValueTd"><input type="text" name="name"
								id="nameForEdit" maxlength="40" /><label>*</label></td>
						</tr>
						<tr>
							<td class="myTitleTd">批次类型</td>
							<td class="myValueTd"><select name="batchType"
								id="batchTypeForEdit" disabled="disabled">
									<c:forEach var="map" items="${taskBatchTypes }">
										<option value="${map.key}">${map.value}</option>
									</c:forEach>
							</select></td>
						</tr>
						<tr>
							<td class="myTitleTd">开始时间</td>
							<td class="myValueTd"><input type="text"
								name="planStartTime" id="planStartTimeForEdit" maxlength="50"
								class="validate[required]" onclick='WdatePicker()'
								readonly="readonly" value="" /><label>*</label></td>
						</tr>
						<tr>
							<td class="myTitleTd">结束时间</td>
							<td class="myValueTd"><input type="text" name="planEndTime"
								id="planEndTimeForEdit" maxlength="50" class="validate[required]"
								onclick='WdatePicker()' readonly="readonly" value="" /><label>*</label></td>
						</tr>

						<tr>
							<td colspan="2" align="center"><input type="button"
								id="saveModifyEditBtn" value="保存" class="batchBtn" /> <input
								type="button" id="cancleEditBtn" value="取消" class="batchBtn" />
							</td>
						</tr>
					</table>
				</form>
			</div>
		</div>


		<div>
			<form id="downloadForm" action="#"></form>
		</div>

		<div id="uploadRevertDiv" title="上传备份文件" class="easyui-window"
			data-options="modal:true,closed:true,iconCls:'icon-import'"
			style="width: 400px; height: 190px; padding: 10px; overflow: hidden;">
			<table cellpadding="5" width="380px;">
				<tr>
					<td id="swfUploadTd"><span id="spanRevertButtonPlaceholder"></span></td>
				</tr>
				<tr>
					<td style="height: 50px; vertical-align: middle;"><span
						id="uploadedRevertFileName"></span> <input type="hidden"
						id="uploadedRevertAttId" /></td>
				</tr>
				<tr>
					<td align="center">
						<button class="btn myMargin3" id="confirmUploadedRevert"
							disabled="disabled">确定</button>
						<button class="btn" id="cancelUploadedRevert">取消</button>
					</td>
				</tr>
			</table>
		</div>

		<div id="importTaskDiv" title="导入任务" class="easyui-window"
			data-options="modal:true,closed:true,minimizable:false,resizable:false,iconCls:'icon-import'"
			style="width: 500px; height: 300px; padding: 10px;">
			<div style="display: inline; padding: 2px;">
				<input type="hidden" id="batchId" value="" /> <input type="hidden"
					id="name" value="" /> <input type="hidden" id="planStartTime"
					value="" /> <input type="hidden" id="planEndTime" value="" /> <span
					id="spanButtonPlaceholder"></span>

				<div style="padding-top: 25px;">
					<div id="success" style="display: none;"></div>

					<div id="error" style="display: none;">
						<div>
							<span>行数据存在错误信息无法导入:</span>
						</div>
						<table style="border-collapse: collapse;" class="tongjiTab">
							<tr>
								<td class="first">行号</td>
								<td class="second">错误信息</td>
							</tr>
							<tr style="color: red;">
								<td class="first" id="firstTd"></td>
								<td class="second" id="secondTd"></td>
							</tr>
							<!-- <tr>
				        		<td class="first">22</td>
				        		<td class="second">22</td>
				        	</tr> -->
						</table>
					</div>
				</div>
			</div>
		</div>
	</div>
</body>
</html>