'use strict';
angular.module('qrzk')
.controller('BatchListCtrl',function($cookieStore,$scope,$http,appConst,$state,toaster,$modal,$stateParams){
	
	$scope.pageModel = {};
	$scope.pageModel.pageSize = 10;
	$scope.search = {};

	$scope.load = function(){
		_goPage(1);
	};
	
	$scope.load();
	
	$scope.goPage = function(pageNum){
		_goPage(pageNum);
	};
	
	function _goPage(pageNum){
		if(pageNum < 1 || (pageNum > $scope.pageModel.totalPage && $scope.pageModel.totalPage > 0)){
			return;
		}
		
		$scope.pageModel.curPage = pageNum;

		var url = 'business/queryBatch';
		var params = {'page': pageNum
				, 'rows': $scope.pageModel.pageSize
				, 'keyword': $scope.search.keyword};
		$http.post(url, params).success(function(data){
			$scope.pageModel.array = data.rows;
			$scope.pageModel.total = data.total;
			$scope.pageModel.totalPage = Math.ceil(data.total / $scope.pageModel.pageSize);
		})
		.error(function(data, code){alert(code);});
	}
	
	$scope.load();
	
	$scope.showInfo = function(row){
		var nextState = null;
		if(row.batchType == 'RU_WEI_MING_TI'){
			nextState = 'batch.info.paperTasks';
		}else if(row.batchType == 'SHEN_TI'){
			nextState = 'batch.info.auditTasks';
		}else if(row.batchType == 'TI_KA_LU_RU'){
			nextState = 'batch.info.inputTasks';
		}else if(row.batchType == 'TI_KU_JIAN_SHE'){
			nextState = 'batch.info.tkjsTasks';
		}else if(row.batchType == 'SHI_JUAN_FU_SHEN'){
			nextState = 'batch.info.reviewTasks';
		}
		
		if(nextState != null){
			$state.go(nextState, {id:row.id});
		}else{
			alert('批次类型错误，请联系管理员！');
		};
		
	};
	
	$scope.showInputStat = function() {
		window.open("business/inputStat");
	};
	
	$scope.deleteBatch = function(id){
		$http.post('business/delTaskBatch/' + id)
		.success(function(data){
			if(data.flag == 'failed'){
				toaster.pop('error', data.msg);
			}
			else{
				toaster.pop('success', '操作成功！');
				$scope.load();
			}
		})
		.error(function(data,code){
			alert(code);
		});
	};
	
	$scope.edit = function(id){
		$state.go('batch.edit', {'id':id});
	};
	
	$scope.exportBatch = function(id){
		if(id != null){
			
			$scope.loadingMsg = '正在生成备份导出数据文件，请稍等...！';
			
			$scope.loading = $http.post('business/exportTask/' + id)
				.success(function(data){
					if(data.flag == 'failed'){
						alert('error', data.msg);
					}
					else{
						$("#downloadForm").attr("action","attachment/download/" + data.attId);
	    				$("#downloadForm").submit();
						toaster.pop('success', data.msg);
					}
				})
				.error(function(data,code){alert(code);});
		}
	};
	
	$scope.expTkjsForClient = function(id){
		if(id != null){
			
			$scope.loadingMsg = '正在生成客户端导出数据文件，请稍等...！';
			
			$scope.loading = $http.post('business/expTkjsForClient/' + id)
				.success(function(data){
					if(data.flag == 'failed'){
						alert('error', data.msg);
					}
					else{
						$("#downloadForm").attr("action","attachment/download/" + data.attId);
	    				$("#downloadForm").submit();
						toaster.pop('success', data.msg);
					}
				})
				.error(function(data,code){alert(code);});
		}
	};
})
.controller('BatchAddCtrl',function($scope,$http,$state,$stateParams,toaster){
	
	$scope.load = function(){
		if($stateParams.id != null){
			var url = 'business/getById/'+ $stateParams.id;
			$http.get(url).success(function(data){
				$scope.model = data;
			})
			.error(function(data, code){alert(code);});
		}else{
			$scope.model = {};
			$scope.model.status = 1;
		}
		
	};
	$scope.load();
	
	$scope.submit = function(){
		if($scope.form.$invalid){
			toaster.pop('error', "校验失败，请检查表单中红框部分的内容！");
			$scope.submitted = true;
			return;
		}
		
		if(($scope.model.name).length < 8){
			toaster.pop('error', "批次名称长度必须为八位");
			return false;
		}
		
		var batch = {};
		batch.id = $scope.model.id;
		batch.name = $scope.model.name;
		batch.batchType = $scope.model.batchType;
		batch.planStartTime = $scope.model.planStartTime;
		batch.planEndTime = $scope.model.planEndTime;
		
		$scope.myPromise = $http.post('business/save',batch)
			.success(function(data){
				if(data.flag == 'failed'){
					toaster.pop('error', data.msg);
				}
				else{
					toaster.pop('success', '操作成功！');
					$state.go('batch.list');
				}
			})
			.error(function(data,code){
				alert(code);
			});
	};
	
	$scope.check = function(batchType){
		if(batchType == 'RU_WEI_MING_TI'){
		$scope.showMessage = "批次名称将用于试题编号";
		}else{
			$scope.showMessage = "";
		}
    }
})
.controller('BatchInfoCtrl',function($scope,$http,$state,$location,$modal,toaster,$stateParams){
	$http.post('business/queryBatchById/' + $stateParams.id).success(function(data){
		$scope.batch = data;
		//alert(JSON.stringify($scope.batch));
	})
	.error(function(data, code){
		alert(code);
	});
	
})

.controller('BatchRevertCtrl',function($cookieStore, $scope, $http, FileUploader,appConst, $q,$stateParams,toaster,$state,$modal){
	var uploader = $scope.uploader = new FileUploader({
        url: 'attachment/upload'
    });
	$scope.upload = function() {
		$scope.loading = $q.defer().promise;
		$scope.loadingMsg = '正在上传批次数据文件，请稍等...！';
		uploader.queue[0].upload();
    };
    $scope.model = {};
    uploader.onSuccessItem = function(fileItem, response, status, headers) {
		$scope.loadingMsg = '正在还原批次数据文件，请稍等...！';
    	$scope.loading = $http.post('business/revertTask/' + response.att.id)
		.success(function(data){
			if(data.flag == 'failed'){
				toaster.pop('error', data.msg);
			}
			else{
				toaster.pop('success', '操作成功！');
				$scope.load();
				$state.go("batch.list");
			}
		})
		.error(function(data,code){
			alert(code);
		});
    };
    
    $scope.files = $scope.uploader.queue;
    $scope.uploader.onCompleteAll = function() {
		//$scope.loading = null;
		$scope.uploader.clearQueue();
	}
    
})

/** 
 * 题卡审核批次
 *  **/
.controller('AuditTaskListCtrl',function($scope,$http,$state,$location,$modal,toaster,$stateParams){
	$scope.load = function(){
		$http.post('business/allAuditQuesTasks/' + $stateParams.id).success(function(data){
			$scope.array = data.rows;
		})
		.error(function(data, code){
			alert(code);
		});
	};
	$scope.load();
	
	$scope.orderByColumn = 'courseCode';
	$scope.orderByReverse = false;
	
	$scope.orderArray = function(column){
		if($scope.orderByColumn == column){
			$scope.orderByReverse = !$scope.orderByReverse;
		}else{
			$scope.orderByColumn = column
			$scope.orderByReverse = false;
		}
	}
	
	$scope.delete = function(row){
		var param = {'taskIds':[row.id]};
		if(confirm('确认要删除课程（' + row.course.code + '-' + row.course.name + ')吗？')){
			$.post('business/delAuditQuesTasks',param,function(res){
				if(res.flag=='failed'){
					toaster.pop('error', "操作失败！");
				}else{
					toaster.pop('success', "操作成功！");
					$scope.load();
				}
			});
		}
	}
	
	var statModal = $modal({title:'按审题教师统计',scope: $scope, templateUrl: 'resources/app/batch/auditTasks.stat.html', show: false});
	
	$scope.showStatModal = function() {
		
		$http.post('business/statBatchAuditorJob/' + $stateParams.id).success(function(res){
			if(res.flag=='failed'){
				toaster.pop('error', res.msg);
			}else{
				$scope.stat = res.auditorJob;
				statModal.$promise.then(statModal.show);
			}
		});
		
	};
	
	var statModal2 = $modal({title:'按课程统计',scope: $scope, templateUrl: 'resources/app/batch/auditTasks.stat2.html', show: false});
	
	$scope.showStatModal2 = function() {
		
		$http.post('business/allAuditQuesTasksWithStat/' + $stateParams.id).success(function(res){
			if(res.flag=='failed'){
				toaster.pop('error', res.msg);
			}else{
				$scope.rows = res.rows;
				statModal2.$promise.then(statModal2.show);
			}
		});
		
	};
})

/** 上传命题任务单 **/
.controller('AuditTaskImportCtrl',function($cookieStore, $scope, $http, FileUploader, $q,$stateParams,toaster,$state){
	var uploader = $scope.uploader = new FileUploader({
        url: 'business/importTask/' + $stateParams.id
    });
	
	$scope.upload = function() {
		$scope.loading = $q.defer().promise;
		uploader.queue[0].upload();
    };	
    
    $scope.model = {};
    uploader.onSuccessItem = function(fileItem, response, status, headers) {
    	if(response.result == 'error'){
    		toaster.pop('error', response.msg);
    	}else if(response.result == 'fail'){
    		toaster.pop('error', '第'+response.lineNum+'行校验失败，原因：' + response.msg);
    	}else if(response.result == 'success'){
    		toaster.pop('success', '上传成功 ' + response.successNum + ' 条命题任务！');
    		$state.go('batch.info.auditTasks');
    	}
    };
    
    $scope.files = $scope.uploader.queue;
    
    $scope.uploader.onCompleteAll = function() {
		$scope.loading = null;
		$scope.uploader.clearQueue();
	}
})


.controller('AuditBatchAddCourseCtrl',function($scope,$http,$state,$location,$modal,toaster,$stateParams){
	$scope.pageModel = {};
	$scope.pageModel.pageSize = 6;
	$scope.search = {};
	
	$scope.load = function(){
		$http.post('business/allAuditQuesTasks/' + $stateParams.id).success(function(data){
			$scope.auditTasks = data.rows;
			_goPage(1);
		})
	};
	$scope.load();
	
	$scope.goPage = function(pageNum){
		_goPage(pageNum);
	}
	
	function _goPage(pageNum){
		if(pageNum < 1 || (pageNum > $scope.pageModel.totalPage && $scope.pageModel.totalPage > 0)){
			return;
		}
		
		$scope.pageModel.curPage = pageNum;
		
		var url = 'course/queryCourses';
		var params = {'page': pageNum
						, 'rows' : $scope.pageModel.pageSize
						, 'keyword' : $scope.search.keyword};
		$http.post(url, params).success(function(data){
			$scope.pageModel.array = data.rows;
			$scope.pageModel.total = data.total;
			$scope.pageModel.totalPage = Math.ceil(data.total / $scope.pageModel.pageSize);
			
			for(var i = 0; i < $scope.pageModel.array.length; i++){
				var course = $scope.pageModel.array[i];
				for(var j=0; j<$scope.auditTasks.length; j++){
					var inCourse = $scope.auditTasks[j];
					if(course.code == inCourse.courseCode){
						course.inBatch = true;
						break;
					}
				}
			}
		})
		.error(function(data, code){alert(code);});
	}
	
	$scope.addAuditCourse = function(row){
		var param = {'courseId':row.id,'batchId':$stateParams.id};
		$http.post('business/addAuditQuesTask',param).success(function(res){
			if(res.flag=='failed'){
				toaster.pop('error', "操作失败！");
	           return false;
			}else{
				row.inBatch = true;
				toaster.pop('success', "操作成功！");
			}
		});
	}
})

.controller('AuditTaskRelatedTeachersCtrl', function($scope,$http,$state,$location,$modal,toaster,$stateParams){
	$scope.pageModel = {};
	$scope.pageModel.pageSize = 6;
	$scope.relatedBooks = [];
	$scope.search = {};
	
	function _goPage(pageNum){
		if(pageNum < 1 || (pageNum > $scope.pageModel.totalPage && $scope.pageModel.totalPage > 0)){
			return;
		}
		
		$scope.pageModel.curPage = pageNum;
		
		var url = 'user/queryUsers';
		var params = {'page': pageNum
						, 'rows': $scope.pageModel.pageSize
						, 'keyword': $scope.search.keyword
						, 'userType' : 10
						,'isEnabled': 1};
		$http.post(url, params).success(function(data){
			$scope.pageModel.array = data.rows;
			$scope.pageModel.total = data.total;
			$scope.pageModel.totalPage = Math.ceil(data.total / $scope.pageModel.pageSize);
		})
		.error(function(data, code){alert(code);});
	}
	
	$scope.goPage = function(pageNum){
		_goPage(pageNum);
	}
	
	$scope.load = function(){
		_goPage(1);
		
		$http.post('business/allAuditQuesTasks/' + $stateParams.id).success(function(data){
			$scope.tasks = data.rows;
			if(data.rows.length > 0){
				if($scope.curTask == null){
					$scope.curTask = data.rows[0];
				}
			}
		})
		.error(function(data, code){
			alert(code);
		});
	};
	$scope.load();
	
	$scope.selectTask = function(row){
		$scope.curTask = row;
	}
	
	$scope.addRelatedTeacher = function(row){
		var exists = false;
		for(var i=0; i < $scope.curTask.auditorList.length; i++){
			var item = $scope.curTask.auditorList[i];
			if(item.id == row.id){
				exists = true;
			}
		}
		if(!exists){
			$scope.curTask.auditorList.push(row);
			$scope.submit();
		}else{
			toaster.pop('warning', '已关联!');
		}
	}
	
	$scope.deleteRelatedTeacher = function(row){
		var i=0; 
		for(;i < $scope.curTask.auditorList.length; i++){
			var item = $scope.curTask.auditorList[i];
			if(item.id == row.id){
				break;
			}
		}
		$scope.curTask.auditorList.splice(i,1);
		$scope.submit();
	}
	
	$scope.submit = function(){
		var links = [];
		for(var i=0;i < $scope.curTask.auditorList.length; i++){
			var item = $scope.curTask.auditorList[i];
			links.push(item.id);
		}
		
		$http.post('business/saveLinkUsers/' + $scope.curTask.id, links).success(function(res){
			if(res.flag=='failed'){
				toaster.pop('error', "操作失败！");
	           return false;
			}else{
				toaster.pop('success', "操作成功！");
				$scope.load();
			}
		});
	}
})

.controller('PaperTaskListCtrl',function($scope,$http,$state,$location,$modal,toaster,$stateParams,paperTaskStatus){
	$scope.search = {
			status: '!ARCHIVED'
	};
	$scope.paperTaskStatus = paperTaskStatus.array;
	
	$scope.load = function(){
		$scope.isBusinessManager = true;
		var param = {'batchId':$stateParams.id, 'rows':9999};
		$http.post('business/queryPaperTask', param).success(function(data){
			$scope.array = data.rows;
			if($scope.array){
				var course = '';
				$scope.courseCount = 0;//批次下的课程数
				$scope.unfinishedCourseCount = 0; //未完成的课程数
				var courseStatusMap = {};
				angular.forEach($scope.array, function(task){
					if(task.course.code != course){
//						console.log('-----last course: ' + course + " cur course: " + task.course.code);
						$scope.courseCount ++;//统计批次下的课程数
						course = task.course.code;
					}
					
					if(task.status != 'ARCHIVED' && !courseStatusMap[task.course.code]){
						courseStatusMap[task.course.code] = 'unFinished';
						$scope.unfinishedCourseCount ++;
					}
				})
			}
		})
		.error(function(data, code){
			alert(code);
		});
	};
	$scope.load();
	
	$scope.showTaskDetail = function(row){
		$state.go('batch.info.paperTask.detail', {taskId: row.id});
	}
	
	$scope.viewPaper = function(row){
		if(row.paperId > 0){
			window.open("zujuan/manualAdd?taskId=" + row.id,
					"paper_win_" + row.taskNo);
		}else{
			toaster.pop('warning', '命题教师1（' + row.propositionTeacherBean.name + '）尚未组卷！');
		}
	}
	
	$scope.viewTeacherAssessment = function(row){
		if(row.teacherAssessmentId > 0){
			var url = $state.href('task.paperTask.teacherAssessment', {taskId: row.id, userId: row.propositionTeacherBean.id});
			window.open(url,'_blank');
		}else{
			toaster.pop('warning', '学科秘书1（' + row.primarySecretaryBean.name + '）尚未创建评价表！');
		}
	}
	
	$scope.viewDifficultyEstimate = function(row){
		if(row.difficultyEstimateTableId > 0){
			var url = $state.href('task.paperTask.difficultyEstimate', {taskId: row.id, paperId: row.paperId});
			window.open(url,'_blank');
		}else{
			toaster.pop('warning', '命题教师1（' + row.propositionTeacherBean.name + '）尚未创建及格分数预估表！');
		}
	}
	
	$scope.filterBy = function(keyValues){
		$scope.search = keyValues;
		$scope.matchType = true;
	}
	
	$scope.filterByPaperId = function(){
		if($scope.nonPaper){
			$scope.search = { paperId: null , batchType : '!SHI_JUAN_FU_SHEN'};
		}else{
			$scope.search = {};
		}
	}
	
	$scope.filterByAssessmentId = function(){
		if($scope.nonAssessment){
			$scope.search = { teacherAssessmentId: null , batchType : '!SHI_JUAN_FU_SHEN'};
		}else{
			$scope.search = {};
		}
	}
	
	$scope.filterByDifficultyEstimateTableId = function(){
		if($scope.nonDifficultyEstimate){
			$scope.search = { difficultyEstimateTableId: null , batchType : '!SHI_JUAN_FU_SHEN'};
		}else{
			$scope.search = {};
		}
	}

	$scope.enableTeachers = function(row) {
		if(row){
			$scope.isBusinessManager = true;
			$http.post('business/enableTeachers/' + row.id).success(function(data){
				$scope.load();
			})
			.error(function(data, code){
				alert(code);
			});
		}
	};

	  //删除细目表
	$scope.deleteDetail = function(row){
		if(confirm('确认删除该试卷细目表吗？')){
			var taskId = row.id;
			$http.post('business/deleteDetailTask?id=' + taskId)
			.success(function(data){
				if(data.flag == 'failed'){
					toaster.pop('error', data.msg);
				}
				else{
					toaster.pop('success', '操作成功！');
					$scope.load();
				}
			})
			.error(function(data,code){
				alert(code);
			});
		}
	};
	
	$scope.disableTeachers = function(row) {
		if(row){
			$scope.isBusinessManager = true;
			$http.post('business/disableTeachers/' + row.id).success(function(data){
				$scope.load();
			})
			.error(function(data, code){
				alert(code);
			});
		}
	};
	
	/** 添加命题任务 **/
    var addPaperTaskModal = $modal({title:'添加命题任务',scope: $scope, templateUrl: 'resources/app/batch/paperTask.add.html', show: false});
	
	$scope.showAddPaperTaskModal = function(row) {
	//	deleteDetail(row);
		if(row){
			$scope.editPaperTask = row;
		}else{
			$scope.editPaperTask = null;
		}
		addPaperTaskModal.$promise.then(addPaperTaskModal.show);
	};
	
	$scope.hideAddPaperTaskModal = function() {
		addPaperTaskModal.hide();
		$scope.load();
	};
	
	$scope.exportAllFiles = function() {
		$scope.isBusinessManager = true;
		$http.post('business/exportAllFiles/' + $stateParams.id).success(function(data){
			window.open("attachment/download/" + data.att.id);
		})
		.error(function(data, code){
			alert(code);
		});
	};
	
	$scope.exportRkData = function() {
		$scope.isBusinessManager = true;
		$http.post('business/exportRkData/' + $stateParams.id).success(function(data){
			window.open("attachment/download/" + data.att.id);
		})
		.error(function(data, code){
			alert(code);
		});
	};
	//导出命题教师签到
	$scope.exportMTJSQD = function() {
		$scope.isBusinessManager = true;
		$http.post('business/exportMTJSQD/' + $stateParams.id).success(function(data){
			window.open("attachment/download/" + data.att.id);
		})
		.error(function(data, code){
			alert(code);
		});
	};	
	//导出分工表
	$scope.exportMTSTFGB = function() {
		$scope.isBusinessManager = true;
		$http.post('business/exportMTSTFGB/' + $stateParams.id).success(function(data){
			window.open("attachment/download/" + data.att.id);
		})
		.error(function(data, code){
			alert(code);
		});
	};	
})

/** 手工添加任务单 **/
.controller('PaperTaskAddCtrl',function($scope,$http,$state,$location,$modal,toaster,$stateParams,userType){
	$scope.pageModel = {};
	$scope.pageModel.pageSize = 5;
	$scope.search = {};
	$scope.userSearch = {};
	$scope.paperTaskModel = {
			course: {},
			teacher1: {},
			teacher2: {},
			secretary1: {},
			inputer: {},
			operStep: 1
	};
	
	$scope.load = function(){
		if($scope.editPaperTask){
			var paperTask = $scope.editPaperTask;
			$scope.paperTaskModel = {
					course: paperTask.course,
					teacher1:paperTask.propositionTeacherBean,
					teacher2: paperTask.auditTeacherBean,
					secretary1: paperTask.primarySecretaryBean,
					inputer: paperTask.typesetterBean,
					operStep: 2,
					paperTaskId: paperTask.id
			};
		}
		_goPage(1);
	}
	$scope.load();
	
	$scope.selectCourse = function(row){
		$scope.paperTaskModel.operStep = 2;
		$scope.paperTaskModel.course = row;
		delete $scope.search.keyword;
		_goPage(1);
	}
	
	$scope.selectUser = function(row){
		switch($scope.paperTaskModel.operStep){
		case 2: $scope.paperTaskModel.teacher1 = row;break;
		case 3: $scope.paperTaskModel.teacher2 = row;break;
		case 4: $scope.paperTaskModel.secretary1 = row;break;
		// case 5: $scope.paperTaskModel.secretary2 = row;break;
		case 5: $scope.paperTaskModel.inputer = row;break;
		}
		if($scope.paperTaskModel.operStep != 6){
			$scope.paperTaskModel.operStep++;
			delete $scope.search.keyword;
			_goPage(1);
		}
	}
	
	$scope.goStep = function(step){
		$scope.paperTaskModel.operStep = step;
		delete $scope.search.keyword;
		_goPage(1);
	}
	
	$scope.savePaperTask = function(){
		if(!$scope.paperTaskModel.course.id){
			toaster.pop('error', '请选择课程！');
		}else if(!$scope.paperTaskModel.teacher1.id){
			toaster.pop('error', '请选择命题教师1！');
		}else if(!$scope.paperTaskModel.teacher2.id){
			toaster.pop('error', '请选择命题教师2！');
		}else if(!$scope.paperTaskModel.secretary1.id){
			toaster.pop('error', '请选择学科秘书！');
		}else if(!$scope.paperTaskModel.inputer.id){
			toaster.pop('error', '请选择排版员！');
		}else{
			//修改命卷任务相关人员
			if($scope.paperTaskModel.paperTaskId){
				var params = {
						id: $scope.paperTaskModel.paperTaskId,
						propositionTeacher: $scope.paperTaskModel.teacher1.id,
						auditTeacher: $scope.paperTaskModel.teacher2.id,
						primarySecretary: $scope.paperTaskModel.secretary1.id,
						typesetter: $scope.paperTaskModel.inputer.id
				};
				$http.post('business/updatePaperTask', params).success(function(data){
					if(data.flag == 'failed'){
						toaster.pop('error', data.msg);
					}else{
						toaster.pop('success', '更新成功！');
						$scope.hideAddPaperTaskModal();
					}
				});
			}else{
				//新增命卷任务
				var params = {
						course: {id: $scope.paperTaskModel.course.id, code: $scope.paperTaskModel.course.code},
						
						teacher1: {id: $scope.paperTaskModel.teacher1.id
							, loginName: $scope.paperTaskModel.teacher1.loginName},
							
							teacher2: {id: $scope.paperTaskModel.teacher2.id
								, loginName: $scope.paperTaskModel.teacher2.loginName},
								
								secretary1: {id: $scope.paperTaskModel.secretary1.id
									, loginName: $scope.paperTaskModel.secretary1.loginName},
										
										inputer: {id: $scope.paperTaskModel.inputer.id
											, loginName: $scope.paperTaskModel.inputer.loginName}
				}
				
				$http.post('business/addPaperTask/' + $stateParams.id, params).success(function(data){
					if(data.flag == 'failed'){
						toaster.pop('error', data.msg);
					}else{
						toaster.pop('success', '保存成功！');
						$scope.hideAddPaperTaskModal();
					}
				});
			}
		}
	}
	
	$scope.goPage = function(pageNum){
		_goPage(pageNum);
	}
	
	function _goPage(pageNum){
		if(pageNum < 1 || (pageNum > $scope.pageModel.totalPage && $scope.pageModel.totalPage > 0)){
			return;
		}
		
		$scope.pageModel.curPage = pageNum;
		
		if($scope.paperTaskModel.operStep == 1){
			var url = 'course/queryCourses';
			var params = {'page': pageNum
					, 'rows' : $scope.pageModel.pageSize
					, 'keyword' : $scope.search.keyword};
		}else{
			switch($scope.paperTaskModel.operStep){
			case 2: 
			case 3: $scope.search.userType = userType.teacher;break;
			case 4: $scope.search.userType = userType.secretary;break;
			case 5: $scope.search.userType = userType.inputer;break;
			}
			var url = 'user/queryUsers';
			var params = {'page': pageNum
					, 'rows' : $scope.pageModel.pageSize
					, 'keyword' : $scope.search.keyword
					, 'userType': $scope.search.userType};
		}
		
		$http.post(url, params).success(function(data){
			$scope.pageModel.array = data.rows;
			$scope.pageModel.total = data.total;
			$scope.pageModel.totalPage = Math.ceil(data.total / $scope.pageModel.pageSize);
			
			if($scope.paperTaskModel.operStep == 1){
				angular.forEach($scope.array, function(paperTask){
					angular.forEach($scope.pageModel.array, function(course){
						if(course.id == paperTask.courseId){
							course.inBatch = true;
						}
					})
				})
			}
		})
		.error(function(data, code){alert(code);});
	}
})

/** 上传命题任务单 **/
.controller('PaperTaskUploadCtrl',function($cookieStore, $scope, $http, FileUploader, $q,$stateParams,toaster,$state){
	var uploader = $scope.uploader = new FileUploader({
        url: 'business/importTask/' + $stateParams.id
    });
	
	$scope.upload = function() {
		$scope.loading = $q.defer().promise;
		uploader.queue[0].upload();
    };	
    
    $scope.model = {};
    uploader.onSuccessItem = function(fileItem, response, status, headers) {
    	if(response.result == 'error'){
    		toaster.pop('error', response.msg);
    	}else if(response.result == 'fail'){
    		toaster.pop('error', '第'+response.lineNum+'行校验失败，原因：' + response.msg);
    	}else if(response.result == 'success'){
    		toaster.pop('success', '上传成功 ' + response.successNum + ' 条命题任务！');
    		$state.go('batch.info.paperTasks');
    	};
    };
    
    $scope.files = $scope.uploader.queue;
    
    $scope.uploader.onCompleteAll = function() {
		$scope.loading = null;
		$scope.uploader.clearQueue();
	};
})

/** 上传复审任务单 **/
.controller('ReviewTaskUploadCtrl',function($cookieStore, $scope, $http, FileUploader, $q,$stateParams,toaster,$state){
	var uploader = $scope.uploader = new FileUploader({
        url: 'business/importTask/' + $stateParams.id
    });
	
	$scope.upload = function() {
		$scope.loading = $q.defer().promise;
		uploader.queue[0].upload();
    };	
    
    $scope.model = {};
    uploader.onSuccessItem = function(fileItem, response, status, headers) {
    	if(response.result == 'error'){
    		toaster.pop('error', response.msg);
    	}else if(response.result == 'fail'){
    		toaster.pop('error', '第'+response.lineNum+'行校验失败，原因：' + response.msg);
    	}else if(response.result == 'success'){
    		toaster.pop('success', '上传成功 ' + response.successNum + ' 条复审任务！');
    		$state.go('batch.info.reviewTasks');
    	};
    };
    
    $scope.files = $scope.uploader.queue;
    
    $scope.uploader.onCompleteAll = function() {
		$scope.loading = null;
		$scope.uploader.clearQueue();
	};
})

.controller('PaperTaskInfoCtrl',function($scope,$http,$state,$location,$modal,toaster,$stateParams){
	$http.post('user/queryCurUser').success(function(data){
		$scope.curUser = data;
	});
	
	$http.post('taskCenter/getPaperTask/' + $stateParams.taskId).success(function(data){
		$scope.task = data;
		
		$http.post('business/queryBatchById/' + $scope.task.batchId).success(function(data){
			$scope.batch = data;
		});
	})
	.error(function(data, code){
		alert(code);
	});
	
})

.controller('ReviewTaskInfoCtrl',function($scope,$http,$state,$location,$modal,toaster,$stateParams){
	$http.post('user/queryCurUser').success(function(data){
		$scope.curUser = data;
	});
	
	$http.post('taskCenter/getPaperTask/' + $stateParams.taskId).success(function(data){
		$scope.task = data;
		
		$http.post('business/queryBatchById/' + $scope.task.batchId).success(function(data){
			$scope.batch = data;
		});
	})
	.error(function(data, code){
		alert(code);
	});
	
})

.controller('paperTaskDetailCtrl',function($scope,$http,$state,$location,$modal,
		toaster,$stateParams,$filter,FileUploader, $q, paperTaskStatus){
	$scope.paperTaskStatus = paperTaskStatus.array;
							
	$scope.load = function(){
		$http.post('business/getOpenWordType').success(function(data){
			$scope.openWordStatus = data.type;
		});
		
		$http.post('user/queryCurUser').success(function(data){
			$scope.curUser = data;
		});
		
		$http.post('taskCenter/updateMsgStatus/' + $stateParams.taskId).success(function(data){
			
		});
		
		$http.post('taskCenter/getAppPath').success(function(data){
			$scope.appPath = data.appPath;
			$scope.rootPath = window.location.protocol + "//" + window.location.host + $scope.appPath;
		});
		
		$http.post('taskCenter/getPaperTask/' + $stateParams.taskId).success(function(data){
			$scope.task = data;
			var curStatusIndex = -1;
			for(var i = 0; i < $scope.paperTaskStatus.length; i++){
				if($scope.task.status == $scope.paperTaskStatus[i].key){
					curStatusIndex = i;
				}
				if(curStatusIndex == -1 || curStatusIndex >= i){
					$scope.paperTaskStatus[i].finished = true;
				}else{
					$scope.paperTaskStatus[i].finished = false;
				}
			}
		})
		.error(function(data, code){
			alert(code);
		});
		
	}
	$scope.load();
	
	var confirmModal = null;
	$scope.doYes = function(){
		confirmModal.hide();
		$scope.confirmParams.doYes();
	};
	
	var skelModal = null;
	
	$scope.createSkel = function(){
		var url = "paperSkeleton/redirect/paperSkeleton?taskId=" 
			+ $scope.task.id 
			+ "&courseId=" + $scope.task.course.id 
			+ "&courseCode=" + $scope.task.course.code 
			+ "&bookId=" + $scope.task.book.id 
			+ "&name=" + $scope.task.taskNo;
		//window.open(url, "skel_win_" + $scope.task.taskNo);
		$scope.skelDialogTitle = "新建细目表";
		$scope.skelUrl = url;
		$scope.openSkelWin();
	}
	
	$scope.viewSkel = function(){
		var url = "paperSkeleton/viewskeletondetail/" + $scope.task.paperSkeleton.id;
		//window.open(url, "skel_win_" + $scope.task.taskNo);
		$scope.skelDialogTitle = "细目表详情";
		$scope.skelUrl = url;
		$scope.openSkelWin();
	}
	
	$scope.openSkelWin = function(){
		skelModal = $modal({title:'制定任务细目表',scope: $scope, 
			templateUrl: 'resources/app/batch/loadSkel.html',
			show: false, backdrop:'static',
			onShow:function(){
				$("#skelFrame").attr("src",$scope.skelUrl);
			}
			});
		var width = $(window).width();
		var height = $(window).height();
		$scope.skelDialogWidth = width - 10;
		$scope.skelDialogHeight = height - 0;
		$scope.skelFrameWidth = width - 10;
		$scope.skelFrameHeight = height - 45;
		
		skelModal.$promise.then(skelModal.show);
	}
	
	$scope.createSkelToView = function(){
		$scope.skelDialogTitle = "细目表详情";
		$scope.load();
	}
	
	$scope.closeSkelModal = function(){
		skelModal.hide();
	}
	
	$scope.viewPaper = function(){
		window.open("zujuan/manualAdd?taskId=" + $scope.task.id,
					"paper_win_" + $scope.task.taskNo);
	}
	
	$scope.showDifficultyEstimateWindow = function(isPropositionTeacher){
		if(isPropositionTeacher){
			$http.post('zujuan/countBlankQuesNum/' + $scope.task.pagerConstruct.id).success(function(data){
				var blankQuesNum = data.blankQuesNum - 0;
				if(blankQuesNum > 0){
					toaster.pop('warning', "当前试卷里面还有" + blankQuesNum + "道空题，请组卷完成后再操作!");
				}else{
					var url = $state.href('task.paperTask.difficultyEstimate', {taskId: $scope.task.id, paperId: $scope.task.pagerConstruct.id});
					window.open(url,'_blank');
				}
			})
		}else{
			if($scope.task.difficultyEstimateTableId > 0){
				var url = $state.href('task.paperTask.difficultyEstimate', {taskId: $scope.task.id, paperId: $scope.task.pagerConstruct.id});
				window.open(url,'_blank');
			}else{
				toaster.pop('warning', "命题教师1（" + $scope.task.propositionTeacherBean.name + '）尚未创建及格分数预估表！');
			}
		}
	}
	
	$scope.showTeacherAssessmentWindow = function(isPrimarySecretary){
		if(isPrimarySecretary || $scope.task.teacherAssessmentId > 0){
			var url = $state.href('task.paperTask.teacherAssessment', {taskId: $scope.task.id, userId: $scope.task.propositionTeacherBean.id});
			window.open(url,'_blank');
		}else{
			toaster.pop('warning', '学科秘书（' + $scope.task.primarySecretaryBean.name + '）尚未创建评价表！');
		}
	}
	
	$scope.workflow  = {
		remark:null,
		nextDealer:null,
		auditResult:2
	}
	
	/** 题卡设置 **/
	var toTikaCfgModal = $modal({title:'答题卡设置',scope: $scope, templateUrl: 'resources/app/batch/paperTask.paper.tikaCfg.html', show: false});
	
	$scope.tikaCfg = {};
	$scope.toTikaCfg = function(){
		$scope.tikaCfg.tikaType = $scope.task.pagerConstruct.tikaType;
		$scope.zhuanyinAtt = null;
		$scope.toUpload = true;
		toTikaCfgModal.$promise.then(toTikaCfgModal.show);
	}
	
	var zhuanyinUploader = $scope.zhuanyinUploader = new FileUploader({
        url: 'attachment/upload'
    });
	
	$scope.toReupload = function(){
		$scope.zhuanyinAtt = null;
		$scope.toUpload = true;
	}
	$scope.uploadZhuanyin = function() {
		//$scope.loading = $q.defer().promise;
		//$scope.loadingMsg = '正在上传转印说明文件，请稍等...！';
		zhuanyinUploader.queue[0].upload();
    };
    zhuanyinUploader.onSuccessItem = function(fileItem, response, status, headers) {
    	$scope.zhuanyinAtt = response.att;
    	//$scope.tikaCfg.tikaType = 'SPECIAL';
    	$scope.toUpload = false;
    	$scope.zhuanyinUploader.clearQueue();
    	$("#zhuanyinFile").val("");
    	toaster.pop('success','上传成功！');
    };
    
    $scope.zhuanyinFiles = $scope.zhuanyinUploader.queue;
    $scope.zhuanyinUploader.onCompleteAll = function() {
		//$scope.loading = null;
		$scope.zhuanyinUploader.clearQueue();
	}
    
    $scope.toEditZhuanyin = function(index){
    	var params = "taskId=" + $scope.task.id + "&index=" + index;
    	$http.post('taskCenter/getZhuanyinAtt?' + params).success(function(data){
			if(data.flag=="success") {	
				var fileName = null;
				var lastZhuanyinWord = null;
				lastZhuanyinWord = data.lastZhuanyinWord;
				if (index == 1) {
					fileName = encodeURIComponent($scope.task.taskNo + "转印说明附件");
				} 
//				else if (index == 2) {
//					fileName = encodeURIComponent($scope.task.taskNo + "转印说明附件二");
//				}
				$http.post('attachment/openword/' + lastZhuanyinWord
						+ "?fileName=" + fileName + "&userId=" + $scope.curUser.id + "&taskUserId=" + $scope.task.curDealer
						+ "&paperId=" + $scope.task.pagerConstruct.id + "&attType=ZHUANYIN").success(function(data){
					var code = data.code;
					if(code == "0"){
						var attachmentId = data.attachmentId;
						var tempPath = data.tempPath;
						var title = data.title;
						tempPath = encodeURIComponent(tempPath.replace(/\\/g, "\\\\"));
						var hostUrl = $scope.rootPath + "/resources/app/word/tempEdit.jsp?attachmentId=" + lastZhuanyinWord
						+ "&fileName=" + fileName + "&userId=" + $scope.curUser.id + "&taskUserId=" + $scope.task.curDealer
						+ "&paperId=" + $scope.task.pagerConstruct.id + "&attType=ZHUANYIN" + "&title=" + title + "&tempPath=" + tempPath;
						window.open(hostUrl);
					}else{
						toaster.pop('error', '非法访问!');
					}
				});
			}
			else{
				toaster.pop('error', data.msg);
			}
		});
    }
    
    $scope.saveTikaCfg = function(){
    	//if($scope.tikaCfg.tikaType == 'SPECIAL' && $scope.zhuanyinAtt == null){
    	//	toaster.pop('error','请选择文件后点击“上传”按钮！');
    	//	return false;
    	//}
    	var params = "taskId=" + $scope.task.id + "&paperId=" + $scope.task.pagerConstruct.id + "&tikaType=" + $scope.tikaCfg.tikaType;
    	//if($scope.tikaCfg.tikaType == 'SPECIAL'){
    	//	params = params + "&lastZhuanyinWord=" + $scope.zhuanyinAtt.id;
    	//}
    	$http.post('taskCenter/saveTikaCfg?' + params).success(function(data){
			if(data.flag=="success"){
				toaster.pop('success','保存成功！');
				toTikaCfgModal.hide();
				$state.reload();
			}
			else{
				toaster.pop('error', data.msg);
			}
		});
    }
	
	/** 提交审核 **/
	var workflowSubmitModal = $modal({title:'提交审核',scope: $scope, templateUrl: 'resources/app/batch/paperTask.workflow.submit.html', show: false});
	$scope.showWorkflowSubmitModal = function() {
		$scope.workflow.nextDealer = $scope.task.defaultNextDealer;
		workflowSubmitModal.$promise.then(workflowSubmitModal.show);
	};
	$scope.workflowSubmit = function(){
		workflowSubmitModal.hide();
		var params = "taskId=" + $scope.task.id + "&nextDealer=" + $scope.workflow.nextDealer + "&remark=" + $scope.workflow.remark;
		//$scope.loadingMsg = "正在提交中，请等待...";
		$scope.loading = $http.post('taskCenter/normalSubmit?' + params).success(function(data){
			if(data.flag=="success"){
				toaster.pop('success','操作成功！');
				$scope.workflow.nextDealer = null;
				$scope.workflow.remark = null;
				//workflowSubmitModal.hide();
				$scope.load();
				
				if($scope.imCount > 0){
					$scope.imCount = $scope.imCount - 1;
					$scope.updateTaskCount();
				}
			}
			else{
				toaster.pop('error', data.msg);
			}
		});
	};
	
	/** 审核结果 **/
	var workflowAuditModal = $modal({title:'提交审核结果',scope: $scope, templateUrl: 'resources/app/batch/paperTask.workflow.audit.html', show: false});
	$scope.showWorkflowAuditModal = function() {
		//console.log($scope.task);
        if($scope.task.status == "TO_AUDIT_PAPER" && $scope.task.curDealer == $scope.task.primarySecretary && $scope.task.teacherAssessmentId == null){
            toaster.pop('error', '学科秘书（' + $scope.task.primarySecretaryBean.name + '）未填写命题教师评价表，无法提交！如已填写评价表，请刷新当前页面。');
            return;
        }
		if($scope.task.pagerConstruct){
			$http.post('zujuan/countBlankQuesNum/' + $scope.task.pagerConstruct.id).success(function(data){
				var blankQuesNum = data.blankQuesNum - 0;
				if(blankQuesNum > 0){
					toaster.pop('warning', "当前试卷里面还有" + blankQuesNum + "道空题，请组完卷后再提交!");
				}else{
					$scope.workflow.nextDealer = $scope.task.defaultNextDealer;
					workflowAuditModal.$promise.then(workflowAuditModal.show);
				}
			})
		}else{
			$scope.workflow.nextDealer = $scope.task.defaultNextDealer;
			workflowAuditModal.$promise.then(workflowAuditModal.show);
		}
		
	};
	$scope.workflowAudit = function(){
		var params = "taskId=" + $scope.task.id 
					+ "&nextDealer=" + $scope.workflow.nextDealer 
					+ "&auditResult=" + $scope.workflow.auditResult 
					+ "&remark=" + $scope.workflow.remark;
		$http.post('taskCenter/saveAuditResult?' + params).success(function(data){
			if(data.flag=="success"){
				toaster.pop('success','更新成功！');
				$scope.workflow.nextDealer = null;
				$scope.workflow.remark = null;
				workflowAuditModal.hide();
				$scope.load();
			}
			else{
				toaster.pop('error', data.msg);
			}
		});
	};
	
	$scope.submitPaperToTypeset = function(){
		if($scope.task.pagerConstruct.tikaType == null || $scope.task.pagerConstruct.tikaType == ''){
            toaster.pop('error', '您还未设置题卡类型，请设置后再提交排版！');
            return;
        }
		$http.post('zujuan/countBlankQuesNum/' + $scope.task.pagerConstruct.id).success(function(data){
			var blankQuesNum = data.blankQuesNum - 0;
			if(blankQuesNum > 0){
				toaster.pop('warning', "当前试卷里面还有" + blankQuesNum + "道空题，请组完卷后再提交!");
			}else{
				$scope.showWorkflowSubmitModal();
			}
		})
		.error(function(data, code){
			alert(code);
		});
	};
	
	$scope.submitByTypeset = function(){
		confirmModal = $modal({title:'提示',scope: $scope, templateUrl: 'resources/app/common/confirm.html', show: false});
		$scope.confirmParams = {
				title: '提示',
				msg: '您确定要提交吗？（提交前请确认是否已经上传了排版后的Word试卷及答案）',
				doYes:function(){
					$scope.showWorkflowSubmitModal();
				}
		};
		confirmModal.$promise.then(confirmModal.show);
	};
	
	$scope.finalTypesetSubmitByTypeset = function(){
		confirmModal = $modal({title:'提示',scope: $scope, templateUrl: 'resources/app/common/confirm.html', show: false});
		$scope.confirmParams = {
				title: '提示',
				msg: '您确定要提交吗？（提交前请确认是否已经上传了排版后的Word试卷及答案）',
				doYes:function(){
					$scope.showWorkflowAuditModal();
				}
		};
		confirmModal.$promise.then(confirmModal.show);
	};
	
	
	/** 下载试卷与标答 **/
	$scope.downloadPaperWord = function(){
		if($scope.openWordStatus == '2'){
			var downloadTime = $filter('date')(new Date(), 'yyyy-MM-dd HH:mm:ss');
			var fileName = encodeURIComponent($scope.task.taskNo + "testPaper_" + downloadTime);
			//window.open("attachment/download/" + $scope.task.pagerConstruct.lastPaperWord + "?fileName=" + fileName);
			//window.open("attachment/download/" + $scope.task.pagerConstruct.lastPaperWord);
			
			$http.post('attachment/openword/' + $scope.task.pagerConstruct.lastPaperWord
					+ "?fileName=" + fileName + "&userId=" + $scope.curUser.id + "&taskUserId=" + $scope.task.curDealer
					+ "&paperId=" + $scope.task.pagerConstruct.id + "&attType=PAPER").success(function(data){
				var code = data.code;
				if(code == "0"){
					var attachmentId = data.attachmentId;
					var tempPath = data.tempPath;
					var title = data.title;
					tempPath = encodeURIComponent(tempPath.replace(/\\/g, "\\\\"));
					var hostUrl = $scope.rootPath + "/resources/app/word/" + ($scope.task.status == "ARCHIVED"?"tempView":"tempEdit") + ".jsp?attachmentId=" + $scope.task.pagerConstruct.lastPaperWord
					+ "&fileName=" + fileName + "&userId=" + $scope.curUser.id + "&taskUserId=" + $scope.task.curDealer
					+ "&paperId=" + $scope.task.pagerConstruct.id + "&attType=PAPER" + "&title=" + title + "&tempPath=" + tempPath;
					var url = "PageOffice://|" + hostUrl + "|width=1000px;height=630px;||";
					window.open(hostUrl);
				}else{
					toaster.pop('error', '非法访问!');
				}
			});
//			var hostUrl = $scope.rootPath + "/attachment/openword/" + $scope.task.pagerConstruct.lastPaperWord
//			+ "?fileName=" + fileName + "&userId=" + $scope.curUser.id + "&taskUserId=" + $scope.task.curDealer
//			+ "&paperId=" + $scope.task.pagerConstruct.id + "&attType=PAPER";
//			var url = "PageOffice://|" + hostUrl + "|width=1000px;height=630px;||";
//			window.location.href = url;
		}else if($scope.openWordStatus == '1'){
			window.open("attachment/download/" + $scope.task.pagerConstruct.lastPaperWord);
		}
	};
	$scope.downloadAnswerWord = function(){
		if($scope.openWordStatus == '2'){
			var downloadTime = $filter('date')(new Date(), 'yyyy-MM-dd HH:mm:ss');
			var fileName = encodeURIComponent($scope.task.taskNo + "答案_" + downloadTime);
			
			$http.post('attachment/openword/' + $scope.task.pagerConstruct.lastAnswerWord
					+ "?fileName=" + fileName + "&userId=" + $scope.curUser.id + "&taskUserId=" + $scope.task.curDealer
					+ "&paperId=" + $scope.task.pagerConstruct.id + "&attType=DA").success(function(data){
				var code = data.code;
				if(code == "0"){
					var attachmentId = data.attachmentId;
					var tempPath = data.tempPath;
					var title = data.title;
					tempPath = encodeURIComponent(tempPath.replace(/\\/g, "\\\\"));
					var hostUrl = $scope.rootPath + "/resources/app/word/" + ($scope.task.status == "ARCHIVED"?"tempView":"tempEdit") + ".jsp?attachmentId=" + $scope.task.pagerConstruct.lastAnswerWord
					+ "&fileName=" + fileName + "&userId=" + $scope.curUser.id + "&taskUserId=" + $scope.task.curDealer
					+ "&paperId=" + $scope.task.pagerConstruct.id + "&attType=ANSWER" + "&title=" + title + "&tempPath=" + tempPath;
					window.open(hostUrl);
				}else{
					toaster.pop('error', '非法访问!');
				}
			});
//			var hostUrl = $scope.rootPath + "/attachment/openword/" + $scope.task.pagerConstruct.lastAnswerWord
//			+ "?fileName=" + fileName + "&userId=" + $scope.curUser.id + "&taskUserId=" + $scope.task.curDealer
//			+ "&paperId=" + $scope.task.pagerConstruct.id + "&attType=ANSWER";
//			var url = "PageOffice://|" + hostUrl + "|width=1000px;height=630px;||";
//			window.location.href = url;
		}else if($scope.openWordStatus == '1'){
			window.open("attachment/download/" + $scope.task.pagerConstruct.lastAnswerWord);
		}
	};
	$scope.downloadWangpingWord = function(){
		if($scope.openWordStatus == '2'){
			var downloadTime = $filter('date')(new Date(), 'yyyy-MM-dd HH:mm:ss');
			var fileName = encodeURIComponent($scope.task.taskNo + "网评卷_" + downloadTime);
			
			$http.post('attachment/openword/' + $scope.task.pagerConstruct.lastWangpingWord
					+ "?fileName=" + fileName + "&userId=" + $scope.curUser.id + "&taskUserId=" + $scope.task.curDealer
					+ "&paperId=" + $scope.task.pagerConstruct.id + "&attType=WPJ").success(function(data){
				var code = data.code;
				if(code == "0"){
					var attachmentId = data.attachmentId;
					var tempPath = data.tempPath;
					var title = data.title;
					tempPath = encodeURIComponent(tempPath.replace(/\\/g, "\\\\"));
					var hostUrl = $scope.rootPath + "/resources/app/word/" + ($scope.task.status == "ARCHIVED"?"tempView":"tempEdit") + ".jsp?attachmentId=" + $scope.task.pagerConstruct.lastWangpingWord
					+ "&fileName=" + fileName + "&userId=" + $scope.curUser.id + "&taskUserId=" + $scope.task.curDealer
					+ "&paperId=" + $scope.task.pagerConstruct.id + "&attType=WANGPING" + "&title=" + title + "&tempPath=" + tempPath;
					window.open(hostUrl);
				}else{
					toaster.pop('error', '非法访问!');
				}
			});
//			var hostUrl = $scope.rootPath + "/attachment/openword/" + $scope.task.pagerConstruct.lastWangpingWord
//			+ "?fileName=" + fileName + "&userId=" + $scope.curUser.id + "&taskUserId=" + $scope.task.curDealer
//			+ "&paperId=" + $scope.task.pagerConstruct.id + "&attType=WANGPING";
//			var url = "PageOffice://|" + hostUrl + "|width=1000px;height=630px;||";
//			window.location.href = url;
		}else if($scope.openWordStatus == '1'){
			window.open("attachment/download/" + $scope.task.pagerConstruct.lastWangpingWord);
		}
	};
	//题卡都是生成最新的，而且不可编辑
	$scope.downloadTikaWord = function(){
		$scope.loadingMsg = "正在加载题卡文件...";
		$scope.loading = $http.post('zujuan/previewTika/' + $scope.task.pagerConstruct.id).success(function(data){
			if(data.flag=="success"){
				var fileName = encodeURIComponent(data.att.originalName);
				if($scope.openWordStatus == '2'){
					$http.post('attachment/openword/' + data.att.id
							+ "?fileName=" + fileName + "&userId=" + $scope.curUser.id + "&taskUserId=" + $scope.task.curDealer
							+ "&paperId=" + $scope.task.pagerConstruct.id + "&attType=TIKA").success(function(data){
						var code = data.code;
						if(code == "0"){
							var attachmentId = data.attachmentId;
							var tempPath = data.tempPath;
							var title = data.title;
							tempPath = encodeURIComponent(tempPath.replace(/\\/g, "\\\\"));
							var hostUrl = $scope.rootPath + "/resources/app/word/tempView.jsp?attachmentId=" + $scope.task.pagerConstruct.lastWangpingWord
							+ "&fileName=" + fileName + "&userId=" + $scope.curUser.id + "&taskUserId=" + $scope.task.curDealer
							+ "&paperId=" + $scope.task.pagerConstruct.id + "&attType=TIKA" + "&title=" + title + "&tempPath=" + tempPath;
							window.open(hostUrl);
						}else{
							toaster.pop('error', '非法访问!');
						}
					});
					
//					var hostUrl = $scope.rootPath + "/attachment/openword/" + data.att.id
//					+ "?fileName=题卡&userId=" + $scope.curUser.id + "&taskUserId=" + $scope.task.curDealer
//					+ "&paperId=" + $scope.task.pagerConstruct.id + "&attType=TIKA";
//					var url = "PageOffice://|" + hostUrl + "|width=1000px;height=630px;||";
//					window.location.href = url;
				}else if($scope.openWordStatus == '1'){
					window.open("attachment/download/" + data.att.id);
				}
			}else{
				toaster.pop('error', data.msg);
			}
		});
	};
	
	$scope.downloadZhuanyin = function(readonly,index){
		$scope.loadingMsg = "正在加载转印说明...";
		var params = "taskId=" + $scope.task.id + "&index=" + index;
		$scope.loading = $http.post('taskCenter/getZhuanyinAtt?' + params).success(function(data){
			if(data.flag=="success"){
				var lastZhuanyinWord = data.lastZhuanyinWord;
				var fileName = null;
				if (index == 1) {
					fileName = encodeURIComponent($scope.task.taskNo + "转印说明附件一");
				} else if (index == 2) {
					fileName = encodeURIComponent($scope.task.taskNo + "转印说明附件二");
				}				
				$http.post('attachment/openword/' + lastZhuanyinWord
						+ "?fileName=" + fileName + "&userId=" + $scope.curUser.id + "&taskUserId=" + $scope.task.curDealer
						+ "&paperId=" + $scope.task.pagerConstruct.id + "&attType=ZHUANYIN").success(function(data){
					var code = data.code;
					if(code == "0"){
						var attachmentId = data.attachmentId;
						var tempPath = data.tempPath;
						var title = data.title;
						tempPath = encodeURIComponent(tempPath.replace(/\\/g, "\\\\"));
						var hostUrl = $scope.rootPath + "/resources/app/word/" + (readonly || $scope.task.status == "ARCHIVED"?"tempView":"tempEdit") + ".jsp?attachmentId=" + lastZhuanyinWord
						+ "&fileName=" + fileName + "&userId=" + $scope.curUser.id + "&taskUserId=" + $scope.task.curDealer
						+ "&paperId=" + $scope.task.pagerConstruct.id + "&attType=ZHUANYIN" + "&title=" + title + "&tempPath=" + tempPath;
						window.open(hostUrl);
					}else{
						toaster.pop('error', '非法访问!');
					}
				});
			}
			else{
				toaster.pop('error', data.msg);
			}
		});
	};
	
	/** 上传试卷与标答 **/
	$scope.uploadParams = {
			accept: '.doc,.docx',
			template: null,
			fileType: null,
			title: ''
	};
	var uploadModal = $modal({title:'上传文档',scope: $scope, templateUrl: 'resources/app/common/upload.html', show: false});
	
	$scope.showUploadModal = function(fileType) {
		$scope.uploadParams.fileType = fileType;
		if(fileType == 'PAPER'){
			$scope.uploadParams.title = '上传试卷';
		}else if(fileType == 'ANSWER'){
			$scope.uploadParams.title = '上传答案';
		}else if(fileType == 'WANGPING'){
			$scope.uploadParams.title = '上传网评卷';
		}else if(fileType == 'TIKA'){
			$scope.uploadParams.title = '上传题卡';
		}
		uploadModal.$promise.then(uploadModal.show);
	};
	
	var uploader = $scope.uploader = new FileUploader({
        url: 'attachment/upload'
    });
	
	$scope.upload = function() {
		$scope.loading = $q.defer().promise;
		uploader.queue[0].upload();
    };	
    
    $scope.model = {};
    uploader.onSuccessItem = function(fileItem, response, status, headers) {
    	if(response.att){
    		var params = "taskId=" + $scope.task.id 
							+ "&paperId=" + $scope.task.pagerConstruct.id 
							+ "&attId=" + response.att.id 
							+ "&wordType=" + $scope.uploadParams.fileType;
    		
    		$http.post('taskCenter/submitCurWord?' + params).success(function(res){
    			if(res.flag=='failed'){
    				toaster.pop('error', "上传失败，请联系管理员。");
    	           return false;
    			}else{
    				toaster.pop('success', "上传成功。");
    				uploadModal.hide();
    				$scope.load();
    			}
    		});
    	}else{
    		alert(response.msg);
    	}
    };
    
    $scope.files = $scope.uploader.queue;
    
    $scope.uploader.onCompleteAll = function() {
		$scope.loading = null;
		$scope.uploader.clearQueue();
	}
    
    /** 归档 **/
    /** 审核结果 **/
	var workflowArchiveModal = $modal({title:'归档',scope: $scope, templateUrl: 'resources/app/batch/paperTask.workflow.archive.html', show: false});
	$scope.showWorkflowArchiveModal = function() {
		if($scope.task.teacherAssessmentId == null){
			toaster.pop('error', '学科秘书1（' + $scope.task.primarySecretaryBean.name + '）未填写命题教师评价表，无法归档！如已填写评价表，请刷新当前页面。');
		}else if($scope.task.difficultyEstimateTableId == null){
			toaster.pop('error', '命题教师1（' + $scope.task.propositionTeacherBean.name + '）未填写及格分数预估表，无法归档！如已填写预估表，请刷新当前页面。');
		}else{
			$http.post('zujuan/countBlankQuesNum/' + $scope.task.pagerConstruct.id).success(function(data){
				var blankQuesNum = data.blankQuesNum - 0;
				if(blankQuesNum > 0){
					toaster.pop('warning', "当前试卷里面还有" + blankQuesNum + "道空题，请组完卷后再提交!");
				}else{
					workflowArchiveModal.$promise.then(workflowArchiveModal.show);
				}
			})
			.error(function(data, code){
				alert(code);
			});
		}
		
	};
	$scope.workflowArchive = function(){
		var params = "taskId=" + $scope.task.id 
		+ "&remark=" + $scope.workflow.remark;
		$http.post('taskCenter/saveArchiveResult?' + params).success(function(data){
			if(data.flag=="success"){
				toaster.pop('success','更新成功！');
				$scope.workflow.remark = null;
				workflowArchiveModal.hide();
				$scope.load();
			}
			else{
				toaster.pop('error', data.msg);
			}
		});
	};

})

/**
 * 复审
 */
.controller('reviewTaskDetailCtrl',function($scope,$http,$state,$location,$modal,toaster,
		$stateParams,$filter,FileUploader, $q, paperTaskStatus, reviewTaskStatus){
	$scope.reviewTaskStatus = reviewTaskStatus.array;
	
	$scope.load = function(){
		$http.post('business/getOpenWordType').success(function(data){
			$scope.openWordStatus = data.type;
		});
		
		$http.post('user/queryCurUser').success(function(data){
			$scope.curUser = data;
		});
		
		$http.post('taskCenter/updateMsgStatus/' + $stateParams.taskId).success(function(data){
			
		});
		
		$http.post('taskCenter/getReivewTask/' + $stateParams.taskId).success(function(data){
			$scope.task = data.row;
			$scope.appPath = data.appPath;
			$scope.rootPath = window.location.protocol + "//" + window.location.host + $scope.appPath;
			//console.log($scope.task);
			var curStatusIndex = -1;
			for(var i = 0; i < $scope.reviewTaskStatus.length; i++){
				if($scope.task.status == $scope.reviewTaskStatus[i].key){
					$scope.task.statusName = $scope.reviewTaskStatus[i].value;
					curStatusIndex = i;
				}
				if(curStatusIndex == -1 || curStatusIndex >= i){
					$scope.reviewTaskStatus[i].finished = true;
				}else{
					$scope.reviewTaskStatus[i].finished = false;
				}
			}
		})
		.error(function(data, code){
			alert(code);
		});
		
	}
	$scope.load();
	
	$scope.viewPaper = function(){
		window.open("zujuan/manualAdd?taskId=" + $scope.task.id,
					"paper_win_" + $scope.task.taskNo);
	}
	
	$scope.workflow  = {
		remark:null,
		nextDealer:null,
		auditResult:2
	}
	
	/** 提交审核 **/
	var workflowSubmitModal = $modal({title:'提交审核',scope: $scope, templateUrl: 'resources/app/batch/reviewTask.workflow.submit.html', show: false});
	$scope.showWorkflowSubmitModal = function() {
		$scope.workflow.nextDealer = $scope.task.defaultNextDealer;
		workflowSubmitModal.$promise.then(workflowSubmitModal.show);
	};
	$scope.workflowSubmit = function(){
		var params = "taskId=" + $scope.task.id + "&nextDealer=" + $scope.workflow.nextDealer + "&remark=" + $scope.workflow.remark;
		$http.post('taskCenter/reviewSubmit?' + params).success(function(data){
			if(data.flag=="success"){
				toaster.pop('success','更新成功！');
				$scope.workflow.nextDealer = null;
				$scope.workflow.remark = null;
				workflowSubmitModal.hide();
				$scope.load();
				
				if($scope.imCount > 0){
					$scope.imCount = $scope.imCount - 1;
					$scope.updateTaskCount();
				}
			}
			else{
				toaster.pop('error', data.msg);
			}
		});
	};
	
	/** 审核结果 **/
	var workflowAuditModal = $modal({title:'提交审核结果',scope: $scope, templateUrl: 'resources/app/batch/paperTask.workflow.audit.html', show: false});
	$scope.showWorkflowAuditModal = function() {
		if($scope.task.pagerConstruct){
			$http.post('zujuan/countBlankQuesNum/' + $scope.task.pagerConstruct.id).success(function(data){
				var blankQuesNum = data.blankQuesNum - 0;
				if(blankQuesNum > 0){
					toaster.pop('warning', "当前试卷里面还有" + blankQuesNum + "道空题，请组完卷后再提交!");
				}else{
					$scope.workflow.nextDealer = $scope.task.defaultNextDealer;
					workflowAuditModal.$promise.then(workflowAuditModal.show);
				}
			})
		}else{
			$scope.workflow.nextDealer = $scope.task.defaultNextDealer;
			workflowAuditModal.$promise.then(workflowAuditModal.show);
		}
		
	};
	$scope.workflowAudit = function(){
		var params = "taskId=" + $scope.task.id 
					+ "&nextDealer=" + $scope.workflow.nextDealer 
					+ "&auditResult=" + $scope.workflow.auditResult 
					+ "&remark=" + $scope.workflow.remark;
		$http.post('taskCenter/saveAuditResult?' + params).success(function(data){
			if(data.flag=="success"){
				toaster.pop('success','更新成功！');
				$scope.workflow.nextDealer = null;
				$scope.workflow.remark = null;
				workflowAuditModal.hide();
				$scope.load();
			}
			else{
				toaster.pop('error', data.msg);
			}
		});
	};
	
	$scope.submitByTypeset = function(){
		if(confirm('您确定要提交吗？')){
			$scope.showWorkflowSubmitModal();
		}
	};
	
	/** 下载试卷与标答 **/
	$scope.downloadPaperWord = function(){
		if($scope.openWordStatus == '2'){
			var downloadTime = $filter('date')(new Date(), 'yyyy-MM-dd HH:mm:ss');
			var fileName = encodeURIComponent($scope.task.taskNo + "试卷_" + downloadTime);
			//console.log($scope.task);
			$http.post('attachment/openword/' + $scope.task.pagerConstruct.lastPaperWord
					+ "?fileName=" + fileName + "&userId=" + $scope.curUser.id + "&taskUserId=" + $scope.task.curDealer
					+ "&paperId=" + $scope.task.pagerConstruct.id + "&attType=HJ").success(function(data){
				var code = data.code;
				if(code == "0"){
					var attachmentId = data.attachmentId;
					var tempPath = data.tempPath;
					var title = data.title;
					tempPath = encodeURIComponent(tempPath.replace(/\\/g, "\\\\"));
					var hostUrl = $scope.rootPath + "/resources/app/word/tempView.jsp?attachmentId=" + $scope.task.pagerConstruct.lastPaperWord
					+ "&fileName=" + fileName + "&userId=" + $scope.curUser.id + "&taskUserId=" + $scope.task.curDealer
					+ "&paperId=" + $scope.task.pagerConstruct.id + "&attType=HJ" + "&title=" + title + "&tempPath=" + tempPath;
					var url = "PageOffice://|" + hostUrl + "|width=1000px;height=630px;||";
					window.open(hostUrl);
				}else{
					toaster.pop('error', '非法访问!');
				}
			});
			
//			var hostUrl = $scope.rootPath + "/attachment/openword/" + $scope.task.pagerConstruct.lastPaperWord
//			+ "?fileName=" + fileName + "&userId=" + $scope.curUser.id + "&taskUserId=" + $scope.task.curDealer
//			+ "&paperId=" + $scope.task.pagerConstruct.id + "&attType=HJ";
////			var hostUrl = $scope.rootPath + "/resources/app/word/editWord.jsp?" + $scope.task.pagerConstruct.lastPaperWord
////			+ "&fileName=" + fileName + "&userId=" + $scope.curUser.id + "&taskUserId=" + $scope.task.curDealer
////			+ "&paperId=" + $scope.task.pagerConstruct.id + "&attType=HJ";
//			var url = "PageOffice://|" + hostUrl + "|width=1000px;height=630px;||";
////			var url = hostUrl;
////			window.open(url);
//			window.location.href = url;
		}else if($scope.openWordStatus == '1'){
			window.open("attachment/download/" + $scope.task.pagerConstruct.lastPaperWord);
		}
	};
	$scope.downloadAnswerWord = function(){
		if($scope.openWordStatus == '2'){
			var downloadTime = $filter('date')(new Date(), 'yyyy-MM-dd HH:mm:ss');
			var fileName = encodeURIComponent($scope.task.taskNo + "答案_" + downloadTime);
			
			$http.post('attachment/openword/' + $scope.task.pagerConstruct.lastAnswerWord
					+ "?fileName=" + fileName + "&userId=" + $scope.curUser.id + "&taskUserId=" + $scope.task.curDealer
					+ "&paperId=" + $scope.task.pagerConstruct.id + "&attType=DA").success(function(data){
				var code = data.code;
				if(code == "0"){
					var attachmentId = data.attachmentId;
					var tempPath = data.tempPath;
					var title = data.title;
					tempPath = encodeURIComponent(tempPath.replace(/\\/g, "\\\\"));
					var hostUrl = $scope.rootPath + "/resources/app/word/tempEdit.jsp?attachmentId=" + $scope.task.pagerConstruct.lastAnswerWord
					+ "&fileName=" + fileName + "&userId=" + $scope.curUser.id + "&taskUserId=" + $scope.task.curDealer
					+ "&paperId=" + $scope.task.pagerConstruct.id + "&attType=DA" + "&title=" + title + "&tempPath=" + tempPath;
					window.open(hostUrl);
				}else{
					toaster.pop('error', '非法访问!');
				}
			});
//			var hostUrl = $scope.rootPath + "/attachment/openword/" + $scope.task.pagerConstruct.lastAnswerWord
//			+ "?fileName=" + fileName  + "&userId=" + $scope.curUser.id + "&taskUserId=" + $scope.task.curDealer
//			+ "&paperId=" + $scope.task.pagerConstruct.id + "&attType=DA";
//			var url = "PageOffice://|" + hostUrl + "|width=1000px;height=630px;||";
//			window.location.href = url;
		}else if($scope.openWordStatus == '1'){
			window.open("attachment/download/" + $scope.task.pagerConstruct.lastAnswerWord);
		}
	};
	$scope.downloadWangpingWord = function(){
		if($scope.openWordStatus == '2'){
			var downloadTime = $filter('date')(new Date(), 'yyyy-MM-dd HH:mm:ss');
			var fileName = encodeURIComponent($scope.task.taskNo + "网评卷_" + downloadTime);
			
			$http.post('attachment/openword/' + $scope.task.pagerConstruct.lastWangpingWord
					+ "?fileName=" + fileName + "&userId=" + $scope.curUser.id + "&taskUserId=" + $scope.task.curDealer
					+ "&paperId=" + $scope.task.pagerConstruct.id + "&attType=WPJ").success(function(data){
				var code = data.code;
				if(code == "0"){
					var attachmentId = data.attachmentId;
					var tempPath = data.tempPath;
					var title = data.title;
					tempPath = encodeURIComponent(tempPath.replace(/\\/g, "\\\\"));
					var hostUrl = $scope.rootPath + "/resources/app/word/tempEdit.jsp?attachmentId=" + $scope.task.pagerConstruct.lastWangpingWord
					+ "&fileName=" + fileName + "&userId=" + $scope.curUser.id + "&taskUserId=" + $scope.task.curDealer
					+ "&paperId=" + $scope.task.pagerConstruct.id + "&attType=WPJ" + "&title=" + title + "&tempPath=" + tempPath;
					window.open(hostUrl);
				}else{
					toaster.pop('error', '非法访问!');
				}
			});
//			var hostUrl = $scope.rootPath + "/attachment/openword/" + $scope.task.pagerConstruct.lastWangpingWord
//			+ "?fileName=" + fileName  + "&userId=" + $scope.curUser.id + "&taskUserId=" + $scope.task.curDealer
//			+ "&paperId=" + $scope.task.pagerConstruct.id + "&attType=WPJ";
//			var url = "PageOffice://|" + hostUrl + "|width=1000px;height=630px;||";
//			window.location.href = url;
		}else if($scope.openWordStatus == '1'){
			window.open("attachment/download/" + $scope.task.pagerConstruct.lastWangpingWord);
		}
	};
	$scope.downloadTikaWord = function(){
		window.open("attachment/download/" + $scope.task.pagerConstruct.lastTikaWord);
	};
	
	//废弃？
	$scope.downloadZhuanyin = function(readonly,index){
		$scope.loadingMsg = "正在加载转印说明...";
		var params = "taskId=" + $scope.task.id + "&index=" + index;
		$scope.loading = $http.post('taskCenter/getZhuanyinAtt?' + params).success(function(data){
			if(data.flag=="success"){
				var lastZhuanyinWord = data.lastZhuanyinWord;
				var fileName = null;
				if (index == 1) {
					fileName = encodeURIComponent($scope.task.taskNo + "转印说明附件一");
				} else if (index == 2) {
					fileName = encodeURIComponent($scope.task.taskNo + "转印说明附件二");
				}
				$http.post('attachment/openword/' + lastZhuanyinWord
						+ "?fileName=" + fileName + "&userId=" + $scope.curUser.id + "&taskUserId=" + $scope.task.curDealer
						+ "&paperId=" + $scope.task.pagerConstruct.id + "&attType=ZHUANYIN").success(function(data){
					var code = data.code;
					if(code == "0"){
						var attachmentId = data.attachmentId;
						var tempPath = data.tempPath;
						var title = data.title;
						tempPath = encodeURIComponent(tempPath.replace(/\\/g, "\\\\"));
						var hostUrl = $scope.rootPath + "/resources/app/word/" + (readonly || $scope.task.status == "ARCHIVED"?"tempView":"tempEdit") + ".jsp?attachmentId=" + lastZhuanyinWord
						+ "&fileName=" + fileName + "&userId=" + $scope.curUser.id + "&taskUserId=" + $scope.task.curDealer
						+ "&paperId=" + $scope.task.pagerConstruct.id + "&attType=ZHUANYIN" + "&title=" + title + "&tempPath=" + tempPath;
						window.open(hostUrl);
					}else{
						toaster.pop('error', '非法访问!');
					}
				});
			}
			else{
				toaster.pop('error', data.msg);
			}
		});
	}
	
	/** 查看原始试卷与标答 **/
	$scope.historyPaperWord = function(){
		var attLength = $scope.task.pagerConstruct.paperWordHistories.length;
		if($scope.openWordStatus == '2'){
			var downloadTime = $filter('date')(new Date(), 'yyyy-MM-dd HH:mm:ss');
			var fileName = encodeURIComponent($scope.task.taskNo + "试卷_" + downloadTime);
			
			$http.post('attachment/viewword/' + $scope.task.pagerConstruct.paperWordHistories[attLength - 1].attId
					+ "?fileName=" + fileName + "&userId=" + $scope.curUser.id).success(function(data){
				var code = data.code;
				if(code == "0"){
					var tempPath = data.tempPath;
					var title = data.title;
					tempPath = encodeURIComponent(tempPath.replace(/\\/g, "\\\\"));
					var hostUrl = $scope.rootPath + "/resources/app/word/tempView.jsp?&title=" + title + "&tempPath=" + tempPath;
					window.open(hostUrl);
				}else{
					toaster.pop('error', '非法访问!');
				}
			});
//			var hostUrl = $scope.rootPath + "/attachment/viewword/" + $scope.task.pagerConstruct.paperWordHistories[attLength - 1].attId
//			+ "?fileName=" + fileName + "&userId=" + $scope.curUser.id;
//			var url = "PageOffice://|" + hostUrl + "|width=1000px;height=630px;||";
//			window.location.href = url;
		}else if($scope.openWordStatus == '1'){
			window.open("attachment/download/" + $scope.task.pagerConstruct.paperWordHistories[attLength - 1].attId);
		}
	};
	$scope.historyAnswerWord = function(){
		var attLength = $scope.task.pagerConstruct.answerWordHistories.length;
		if($scope.openWordStatus == '2'){
			var downloadTime = $filter('date')(new Date(), 'yyyy-MM-dd HH:mm:ss');
			var fileName = encodeURIComponent($scope.task.taskNo + "答案_" + downloadTime);
			
			$http.post('attachment/viewword/' + $scope.task.pagerConstruct.answerWordHistories[attLength - 1].attId
					+ "?fileName=" + fileName + "&userId=" + $scope.curUser.id).success(function(data){
				var code = data.code;
				if(code == "0"){
					var tempPath = data.tempPath;
					var title = data.title;
					tempPath = encodeURIComponent(tempPath.replace(/\\/g, "\\\\"));
					var hostUrl = $scope.rootPath + "/resources/app/word/tempView.jsp?&title=" + title + "&tempPath=" + tempPath;
					window.open(hostUrl);
				}else{
					toaster.pop('error', '非法访问!');
				}
			});
//			var hostUrl = $scope.rootPath + "/attachment/viewword/" + $scope.task.pagerConstruct.answerWordHistories[attLength - 1].attId
//			+ "?fileName=" + fileName  + "&userId=" + $scope.curUser.id;
//			var url = "PageOffice://|" + hostUrl + "|width=1000px;height=630px;||";
//			window.location.href = url;
		}else if($scope.openWordStatus == '1'){
			window.open("attachment/download/" + $scope.task.pagerConstruct.answerWordHistories[attLength - 1].attId);
		}
	};
	$scope.historyWangpingWord = function(){
		var attLength = $scope.task.pagerConstruct.wangpingWordHistories.length;
		if($scope.openWordStatus == '2'){
			var downloadTime = $filter('date')(new Date(), 'yyyy-MM-dd HH:mm:ss');
			var fileName = encodeURIComponent($scope.task.taskNo + "网评卷_" + downloadTime);
			
			$http.post('attachment/viewword/' + $scope.task.pagerConstruct.wangpingWordHistories[attLength - 1].attId
					+ "?fileName=" + fileName + "&userId=" + $scope.curUser.id).success(function(data){
				var code = data.code;
				if(code == "0"){
					var tempPath = data.tempPath;
					var title = data.title;
					tempPath = encodeURIComponent(tempPath.replace(/\\/g, "\\\\"));
					var hostUrl = $scope.rootPath + "/resources/app/word/tempView.jsp?&title=" + title + "&tempPath=" + tempPath;
					window.open(hostUrl);
				}else{
					toaster.pop('error', '非法访问!');
				}
			});
//			var hostUrl = $scope.rootPath + "/attachment/viewword/" + $scope.task.pagerConstruct.wangpingWordHistories[attLength - 1].attId
//			+ "?fileName=" + fileName  + "&userId=" + $scope.curUser.id;
//			var url = "PageOffice://|" + hostUrl + "|width=1000px;height=630px;||";
//			window.location.href = url;
		}else if($scope.openWordStatus == '1'){
			window.open("attachment/download/" + $scope.task.pagerConstruct.wangpingWordHistories[attLength - 1].attId);
		}
	};
	$scope.historyTikaWord = function(){
		window.open("attachment/download/" + $scope.task.pagerConstruct.tikaWordHistories[0].attId);
	};
	
	/** 上传试卷与标答 **/
	$scope.uploadParams = {
			accept: '.docx,.doc,.cdr',
			template: null,
			fileType: null,
			title: ''
	};
	var uploadModal = $modal({title:'上传文档',scope: $scope, templateUrl: 'resources/app/common/upload.html', show: false});
	
	$scope.showUploadModal = function(fileType) {
		$scope.uploadParams.fileType = fileType;
		if(fileType == 'HJ'){
			$scope.uploadParams.title = '上传试卷';
		}else if(fileType == 'DA'){
			$scope.uploadParams.title = '上传答案';
		}else if(fileType == 'WPJ'){
			$scope.uploadParams.title = '上传网评卷';
		}else if(fileType == 'ZK'){
			$scope.uploadParams.title = '上传专卡';
		}
		uploadModal.$promise.then(uploadModal.show);
	};
	
	var uploader = $scope.uploader = new FileUploader({
        url: 'attachment/upload'
    });
	
	$scope.upload = function() {
		$scope.loading = $q.defer().promise;
		uploader.queue[0].upload();
    };
    
    $scope.model = {};
    uploader.onSuccessItem = function(fileItem, response, status, headers) {
    	if(response.att){
    		var params = "taskId=" + $scope.task.id 
							+ "&paperId=" + $scope.task.pagerConstruct.id 
							+ "&attId=" + response.att.id 
							+ "&wordType=" + $scope.uploadParams.fileType;
    		
    		$http.post('taskCenter/submitZkWord?' + params).success(function(res){
    			if(res.flag=='failed'){
    				toaster.pop('error', "上传失败，请联系管理员。");
    	           return false;
    			}else{
    				toaster.pop('success', "上传成功。");
    				uploadModal.hide();
    				$scope.load();
    			}
    		});
    	}else{
    		alert(response.msg);
    	}
    };
    
    $scope.files = $scope.uploader.queue;
    
    $scope.uploader.onCompleteAll = function() {
		$scope.loading = null;
		$scope.uploader.clearQueue();
	}
    
    /** 归档 **/
    /** 审核结果 **/
	var workflowArchiveModal = $modal({title:'归档',scope: $scope, templateUrl: 'resources/app/batch/paperTask.workflow.archive.html', show: false});
	$scope.showWorkflowArchiveModal = function() {
		workflowArchiveModal.$promise.then(workflowArchiveModal.show);
	};
	$scope.workflowArchive = function(){
		var params = "taskId=" + $scope.task.id 
		+ "&remark=" + $scope.workflow.remark;
		$http.post('taskCenter/saveArchiveResult?' + params).success(function(data){
			if(data.flag=="success"){
				toaster.pop('success','更新成功！');
				$scope.workflow.remark = null;
				workflowArchiveModal.hide();
				$scope.load();
			}
			else{
				toaster.pop('error', data.msg);
			}
		});
	};
	
	//查看试卷
	$scope.showTaskDetail = function(){
		var taskNo = $scope.task.taskNo;
		$http.post('business/queryTaskByTaskNo/' + taskNo + "?batchType=RU_WEI_MING_TI").success(function(data){
			var result = data.rows;
			if(result){
				if(result.length == 1){
					//$state.go('task.paperTask.detail', {taskId: result[0].id});
					var url = $state.href('task.paperTask.detail', {taskId: result[0].id});
					window.open(url,'paperTask_detail_' + result[0].id);
				}else{
					toaster.pop('error', "该试卷不存在入闱命题任务");
				}
			}
		}); 
	}
	
	$scope.showBatchDetail = function(){
		var taskNo = $scope.task.taskNo;
		$http.post('business/queryTaskByTaskNo/' + taskNo + "?batchType=RU_WEI_MING_TI").success(function(data){
			var result = data.rows;
			if(result){
				if(result.length == 1){
					//$state.go('batch.info.paperTask.detail', {taskId: result[0].id});
					//var url = $state.href('batch.info.paperTask.detail', {taskId: result[0].id});
					var url = "main#/batch/info/" + result[0].batchId + "/paperTask/" + result[0].id + "/detail";
					window.open(url,'paperTask_detail_' + result[0].id);
				}else{
					toaster.pop('error', "该试卷不存在入闱命题任务");
				}
			}
		}); 
	}

})


//及格分数预估表
.controller('PaperTaskDifficultyEstimateCtrl',function($scope,$http,$state,$location,$modal,toaster,$stateParams,$filter){
	$scope.estimateValueRange = {
		A: {minValue: 0.7, maxValue: 1},
		B: {minValue: 0.5, maxValue: 0.7},
		C: {minValue: 0.3, maxValue: 0.5},
		D: {minValue: 0, maxValue: 0.3},
	};
	
	$scope.load = function(){
		$http.post('taskCenter/getPaperTask/' + $stateParams.taskId).success(function(data){
			$scope.task = data;
			$scope.loading = $http.post('zujuan/getDifficultyEstimate/' + $scope.task.pagerConstruct.id).success(function(data){
				$scope.estimateDatas = data;
				$scope.changeValue();
			}).error(function(data, code){alert(code);});
			
			$http.post('user/queryCurUser').success(function(data){
				$scope.curUser = data;
				if($scope.curUser.id == $scope.task.propositionTeacherBean.id 
						&& $scope.task.status != 'ARCHIVED'){
					$scope.editable = true;
				}
			});
			
		}).error(function(data, code){alert(code);});
	}
	
	$scope.load();
	
	$scope.initTableData = function(){
		$http.post('zujuan/createDifficultyEstimate/' + $scope.task.pagerConstruct.id).success(function(data){
			if(data.flag == 'success'){
				$scope.load();
			}else{
				toaster.pop('error', '创建难度预估表失败，请联系管理员！');
			}
		})
		.error(function(data, code){alert(code);});
	}
	
	$scope.changeValue  = function(){
		$scope.totalAverageScore = 0;
		angular.forEach($scope.estimateDatas, function(data){
			if(data.estimateDifficultyValue != null){
				$scope.totalAverageScore += data.questionScore * data.estimateDifficultyValue;
			}
		})
		
		$scope.totalAverageScore = $scope.totalAverageScore.toFixed(2);
	}
	
	$scope.deleteTableData = function(){
		if(confirm('确认要删除及格分数预估表吗？')){
			$http.post('zujuan/deleteDifficultyEstimate/' + $scope.task.pagerConstruct.id)
				.success(function(data){
					if(data.flag=='failed'){
						toaster.pop('error', "操作失败！");
					}else{
						toaster.pop('success', "操作成功！");
						$scope.load();
					}
				});
		}
	}
	
	$scope.submit = function(){
		if($scope.form.$invalid){
			toaster.pop('error', "校验失败，请检查表单中红框部分的内容。")
			$scope.submitted = true;
			return;
		}
		
		if($scope.totalAverageScore > 65 || $scope.totalAverageScore < 55){
			toaster.pop('error', "试卷及格分数超出55-65分的范围。")
			return;
		}
		//console.log($scope.form.$invalid);
		$http.post('zujuan/setEstimateDifficulty', $scope.estimateDatas).success(function(data){
			if(data.flag=="success"){
				toaster.pop('success', '保存成功！');
			}else{
				toaster.pop('error', '保存失败！');
			}
		})
	};
	
})

//批次下所有的评价
.controller('PaperTaskBatchTeacherAssessmentsCtrl',function($scope,$http,$state,$location,$modal,toaster,$stateParams,$filter,assessmentItems){
	$scope.assessmentItems = assessmentItems.array;
	$scope.load = function(){
		$scope.loading = 
			$http.post('teacherAssessment/getAssessmentsByBatchId/' + $stateParams.id)
				.success(function(data){
					if(data.flag == 'success'){
						$scope.assessments = data.assessments;
						if($scope.assessments){
							angular.forEach($scope.assessments, function(assessment){
								var totalScore = 0;
								angular.forEach(assessment.details, function(data){
									if(data.score != null){
										totalScore += data.score;
									}
								})
								assessment.totalScore = totalScore;
							})
							
							if($scope.assessments.length == 0){
								toaster.pop('warning', '尚无评价信息！');
							}
						}
					}else{
						toaster.pop('error', '获取评价表失败！');
					}
				});
	}
	$scope.load();
})

//教师评价表
.controller('PaperTaskTeacherAssessmentCtrl',function($scope,$http,$state,$location,$modal,toaster,$stateParams,$filter,assessmentItems){
	$scope.assessmentItems = assessmentItems.array;
	
	$scope.load = function(){
		$scope.loading = 
			$http.post('teacherAssessment/getAssessmentByTaskAndUserId/' + $stateParams.taskId + '/' + $stateParams.userId)
				.success(function(data){
					$scope.task = data.task;
					$scope.assessment = data.assessment;
					$scope.curUser = data.curUser;
					$scope.changeValue();
					
					//若当前用户为学科秘书1，并且任务未归档，则可以编辑教师评价表
					if($scope.curUser.id == $scope.task.primarySecretaryBean.id 
							&& $scope.task.status != 'ARCHIVED'){
						$scope.editable = true;
					}
					
					if($scope.assessment == null && $scope.task != null){
						$scope.assessment = {
								teacherId: $scope.task.propositionTeacherBean.id,
								taskId: $scope.task.id,
								createById: $scope.curUser.id
						}
						
						$scope.assessment.details = []; 
						//生成26个空的评价信息
						for(var i=1; i<=26; i++){
							var detail = {assessmentSortNo: i
									//, score: $scope.assessmentItems[i-1].score //test
									};
							if($scope.editable){
								detail.score = $scope.assessmentItems[i-1].score;
							}
							$scope.assessment.details.push(detail);
						}
						if($scope.editable){
							toaster.pop('info', '请填写教师评价表！');
						}
					}
					$scope.changeValue();
				}).error(function(data, code){alert(code);});
		
	}
	
	$scope.load();
	
	$scope.changeValue  = function(){
		$scope.totalScore = 0;
		if($scope.assessment){
			angular.forEach($scope.assessment.details, function(data){
				if(data.score != null){
					$scope.totalScore += data.score;
				}
			})
		}
	}
	
	$scope.submit = function(){
		if($scope.form.$invalid){
			toaster.pop('error', "校验失败，请检查表单中红框部分的内容。")
			$scope.submitted = true;
			return;
		}
		
		$http.post('teacherAssessment/setScore', $scope.assessment).success(function(data){
			if(data.flag=="success"){
				toaster.pop('success', '保存成功！');
			}else{
				toaster.pop('error', '保存失败！');
			}
		})
	};
	
})

.controller('TodoPaperTaskListCtrl',function($scope,$http,$state,$cookieStore,$window,$location,$modal,toaster,$stateParams,paperTaskStatus){
	$scope.search = {};
	$scope.search1 = {};
	$scope.paperTaskStatus = paperTaskStatus.array;
	
	$scope.load = function(){
		$http.post('taskCenter/queryRelatedPaperTasks').success(function(data){
			$scope.array = data.rows;
			//console.log($scope.array);
			if(data.total > 0){
				$http.post('business/queryBatchById/' + $scope.array[0].batchId).success(function(data){
					$scope.batch = data;
				});
			}
			
			$http.post('user/queryCurUser').success(function(data){
				$scope.curUser = data;
				//设置默认查询条件为待处理
				$scope.search.curDealer = $scope.curUser.id;
				$scope.search.status = '!ARCHIVED';
				$scope.matchType = true;
				
				$scope.search1.curDealer = $scope.curUser.id;
				$scope.search1.status = '!ARCHIVED_REVIEW';
				
				var todoTaskCount = 0;
				var finishedTaskCount = 0;
				angular.forEach($scope.array, function(task){
					if(task.curDealer == $scope.search.curDealer && task.status != 'ARCHIVED' && task.status != 'ARCHIVED_REVIEW'){
						todoTaskCount++;
					}
					
					if(task.status == 'ARCHIVED' || task.status == 'ARCHIVED_REVIEW'){
						finishedTaskCount++;
					}
				})
				
				if(finishedTaskCount == $scope.array.length && $scope.array.length > 0){
					toaster.pop('success', '恭喜您，您的命题工作已完成，可以出闱了。');
				}else if(todoTaskCount == 0){
					toaster.pop('warning', '没有待处理的任务！');
				}
			});
		});

	};
	$scope.load();
	
	$scope.showTaskDetail = function(row){
		var batchType = row.batchType;
		if(batchType == 'RU_WEI_MING_TI'){
			$state.go('task.paperTask.detail', {taskId: row.id});
		}else if(batchType == 'SHI_JUAN_FU_SHEN'){
			$state.go('task.paperTask.reviewDetail', {taskId: row.id});
		}
	}
	
	$scope.viewPaper = function(row){
		if(row.paperId > 0){
			window.open("zujuan/manualAdd?taskId=" + row.id,
					"paper_win_" + row.taskNo);
		}else{
			toaster.pop('warning', '命题教师1（' + row.propositionTeacherBean.name + '）尚未组卷！');
		}
	}
	
	$scope.viewTeacherAssessment = function(row){
		if(row.teacherAssessmentId > 0){
			var url = $state.href('task.paperTask.teacherAssessment', {taskId: row.id, userId: row.propositionTeacherBean.id});
			window.open(url,'_blank');
		}else{
			toaster.pop('warning', '学科秘书1（' + row.primarySecretaryBean.name + '）尚未创建评价表！');
		}
	}
	
	$scope.viewDifficultyEstimate = function(row){
		if(row.difficultyEstimateTableId > 0){
			var url = $state.href('task.paperTask.difficultyEstimate', {taskId: row.id, paperId: row.paperId});
			window.open(url,'_blank');
		}else{
			toaster.pop('warning', '命题教师1（' + row.propositionTeacherBean.name + '）尚未创建及格分数预估表！');
		}
	}
	
	$scope.filterBy = function(keyValues){
		if(keyValues.constructor == Array){
			$scope.search = keyValues[0];
			$scope.search1 = keyValues[1];
		}else{
			$scope.search = keyValues;
			$scope.search1 = {'status' : '!ARCHIVED_REVIEW'};
		}
		$scope.matchType = true;
	}
	
	$scope.filterByPaperId = function(){
		if($scope.nonPaper){
			$scope.search = { paperId: null, batchType : '!SHI_JUAN_FU_SHEN'};
			$scope.search1 = {};
		}else{
			$scope.search = {};
			$scope.search1 = {};
		}
	}
	
	$scope.filterByAssessmentId = function(){
		if($scope.nonAssessment){
			$scope.search = { teacherAssessmentId: null , batchType : '!SHI_JUAN_FU_SHEN'};
			$scope.search1 = {};
		}else{
			$scope.search = {};
			$scope.search1 = {};
		}
	}
	
	$scope.filterByDifficultyEstimateTableId = function(){
		if($scope.nonDifficultyEstimate){
			$scope.search = { difficultyEstimateTableId: null , batchType : '!SHI_JUAN_FU_SHEN'};
			$scope.search1 = {};
		}else{
			$scope.search = {};
			$scope.search1 = {};
		}
	}
})

/** 
 * 题卡录入批次 $cookieStore, $scope,$http,$state,$location,$modal,FileUploader, $q,toaster,$stateParams,$filter
 *  **/
.controller('InputTaskListCtrl',function($scope,$http,$state,$location,$modal,toaster,$stateParams,FileUploader, $q){
	$scope.load = function(){
		$http.post('business/allInputQuesTasks/' + $stateParams.id).success(function(data){
			$scope.array = data.rows;
		})
		.error(function(data, code){
			alert(code);
		});
	};
	$scope.load();
	
	$scope.delete = function(row){
		var param = {'taskIds':[row.id]};
		if(confirm('确认要删除课程（' + row.course.code + '-' + row.course.name + ')吗？')){
			$http.post('business/delInputQuesTasks/'+row.id).success(function(res){
				if(res.flag=='failed'){
					toaster.pop('error', "操作失败！");
				}else{
					toaster.pop('success', "操作成功！");
					$scope.load();
				}
			});
		}
	};
	
	$scope.expQuestions = function(){
		$http.post('business/expInputTaskQuestions/' + $stateParams.id).success(function(data){
			window.open("attachment/download/" + data.att.id);
		})
		.error(function(data, code){
			alert(code);
		});
	};
	
	/** 上传试卷与标答 **/
	$scope.uploadParams = {
			accept: '.qrzktk',
			template: null,
			fileType: 'qrzktk',
			title: ''
	};
	var uploadModal = $modal({title:'上传题卡文件',scope: $scope, templateUrl: 'resources/app/common/upload.html', show: false});
	
	$scope.impQuestions = function() {
		$scope.uploadParams.title = '上传题卡文件(文件格式：.qrzktk)';
		uploadModal.$promise.then(uploadModal.show);
	};
	
	var uploader = $scope.uploader = new FileUploader({
        url: 'attachment/upload'
    });
	
	$scope.upload = function() {
		$scope.loading = $q.defer().promise;
		uploader.queue[0].upload();
    };
    
    uploader.onSuccessItem = function(fileItem, response, status, headers) {
    	$scope.loadingMsg = '正在解压数据文件，请稍等...！';
    	$scope.loading = $http.post('business/impInputTaskQuestions/' + response.att.id)
		.success(function(data){
			if(data.flag=='failed'){
				toaster.pop('error', "上传失败，请联系管理员。");
				return false;
			}else{
				if(data.ignoreNum - 0 > 0){
					toaster.pop('success', "上传成功，新增试题：" + data.successNum + "道；重复试题（已自动忽略）：" + data.ignoreNum + "道。");
				}else if(data.successNum - 0 > 0){
					toaster.pop('success', "上传成功，新增试题：" + data.successNum + "道。");
				}else{
					toaster.pop('error', "上传的文件中未发现题卡数据！");
				}
				uploadModal.hide();
				$scope.load();
			}
		})
		.error(function(data,code){
			alert(code);
		});
    };
    
    $scope.files = $scope.uploader.queue;
    
    $scope.uploader.onCompleteAll = function() {
		$scope.loading = null;
		$scope.uploader.clearQueue();
	}
})

/** 
 * 题库建设批次
 *  **/
.controller('TkjsTaskListCtrl',function($scope,$http,$state,$location,$modal,toaster,$stateParams){
	$scope.load = function(){
		$http.post('business/allTkjsTasks/' + $stateParams.id).success(function(data){
			$scope.array = data.rows;
		})
		.error(function(data, code){
			alert(code);
		});
	};
	$scope.load();
	
	$scope.delete = function(row){
		var param = {'taskIds':[row.id]};
		if(confirm('确认要删除课程（' + row.course.code + '-' + row.course.name + ')的题库建设任务吗？')){
			$http.post('business/delTkjsTasks/'+row.id).success(function(res){
				if(res.flag=='failed'){
					toaster.pop('error', "操作失败！");
				}else{
					toaster.pop('success', "操作成功！");
					$scope.load();
				}
			});
		}
	}
})

/** 
 * 试卷复审批次
 *  **/
.controller('ReviewTaskListCtrl',function($cookieStore, $scope,$http,$state,$location,$modal,FileUploader, $q,toaster,$stateParams,$filter){
	
	/** 上传试卷与标答 **/
	$scope.uploadParams = {
			accept: '.zip',
			template: null,
			fileType: 'zip',
			title: ''
	};
	var uploadModal = $modal({title:'上传附件',scope: $scope, templateUrl: 'resources/app/common/upload.html', show: false});
	
	$scope.showUploadModal = function() {
		$scope.uploadParams.title = '上传附件';
		uploadModal.$promise.then(uploadModal.show);
	};
	
	var uploader = $scope.uploader = new FileUploader({
        url: 'attachment/uploadReviewAtt/' + $stateParams.id
    });
	
	$scope.upload = function() {
		$scope.loading = $q.defer().promise;
		uploader.queue[0].upload();
    };
    
    $scope.model = {};
    uploader.onSuccessItem = function(fileItem, response, status, headers) {
    	if(response.flag == 'error'){
    		toaster.pop('error', response.msg);
    	}else if(response.flag == 'failed'){
    		toaster.pop('error', response.msg);
    	}else if(response.flag == 'success'){
    		if(response.resultList){
        		var params = {param : response.resultList};
        		
        		$http.post('taskCenter/submitReviewAtt', JSON.stringify(response.resultList)).success(function(res){
        			if(res.flag=='failed'){
        				toaster.pop('error', "上传失败，请联系管理员。");
        				return false;
        			}else{
        				toaster.pop('success', "上传成功。");
        				uploadModal.hide();
        				$scope.load();
        			}
        		});
        	}else{
        		alert(response.msg);
        	}
    	}
    };
    
    $scope.files = $scope.uploader.queue;
    
    $scope.uploader.onCompleteAll = function() {
		$scope.loading = null;
		$scope.uploader.clearQueue();
	}
	
	$scope.load = function(){
		var param = {'batchId':$stateParams.id, 'rows':9999};
		$http.post('business/allReviewTasks', param).success(function(data){
			$scope.array = data.rows;
		})
		.error(function(data, code){
			alert(code);
		});
	};
	$scope.load();
	
	$scope.showTaskDetail = function(row){
		if(row.curDealer != '' && row.curDealer != null){
			$state.go('batch.info.reviewTask.reviewDetail', {taskId: row.id});
		}else{
			toaster.pop('error', '相关人员未配置！');
			return false;
		}
	}
	
	/** 添加复审任务 **/
    var addReviewTaskModal = $modal({title:'添加复审任务',scope: $scope, templateUrl: 'resources/app/batch/reviewTask.add.html', show: false});
	
	$scope.showAddReviewTaskModal = function(row) {
		if(row){
			$scope.editReviewTask = row;
		}else{
			$scope.editReviewTask = null;
		}
		addReviewTaskModal.$promise.then(addReviewTaskModal.show);
	};
	
	$scope.hideAddReviewTaskModal = function() {
		addReviewTaskModal.hide();
		$scope.load();
	};
	
	//删除复审任务
	$scope.deleteTask = function(row){
		if(confirm('确认删除该任务吗？')){
			var taskId = row.id;
			var curDealer = row.curDealer;
			$http.post('business/deleteReviewTask?id=' + taskId)
			.success(function(data){
				if(data.flag == 'failed'){
					toaster.pop('error', data.msg);
				}
				else{
					toaster.pop('success', '操作成功！');
					$scope.load();
				}
			})
			.error(function(data,code){
				alert(code);
			});
		}
	};
	
	//导出任务
	$scope.exportAllFiles = function() {
		$scope.isBusinessManager = true;
		$http.post('business/exportReviewFiles/' + $stateParams.id).success(function(data){
			window.open("attachment/download/" + data.att.id);
		})
		.error(function(data, code){
			alert(code);
		});
	};
	
	//启用试卷
	var enableModal = $modal({title:'添加复审任务',scope: $scope, templateUrl: 'resources/app/batch/reviewTask.enable.html', show: false});
	$scope.showEnableModal = function(row) {
		if(row){
			$scope.paper = row;
		}else{
			$scope.paper = null;
		}
		enableModal.$promise.then(enableModal.show);
	};
	
	$scope.enableSubmit = function(){
		var date = $scope.model.enableDateYear + "-" + $scope.model.enableDateMonth;
		var paperCode = $scope.paper.pagerConstruct.name;
		$http({
        method  : 'POST',
        url     : 'zujuan/enablePaper',
        data    : 'paperCode='+paperCode+'&date='+date,
        headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
    })
		.success(function(res){
			enableModal.hide();
			toaster.pop('success', '操作成功！');
			$state.reload();
		})
	}
})

/** 手工添加复审任务单 **/
.controller('ReviewTaskAddCtrl',function($scope,$http,$state,$location,$modal,toaster,$stateParams,userType){
	$scope.pageModel = {};
	$scope.pageModel.pageSize = 5;
	$scope.search = {};
	$scope.userSearch = {};
	$scope.reviewTaskModel = {
			taskNo: {},
			teacher: {},
			secretary: {},
			inputer: {},
			operStep: 1
	};
	
	$scope.load = function(){
		if($scope.editReviewTask){
			var reviewTask = $scope.editReviewTask;
			$scope.reviewTaskModel = {
					taskNo: reviewTask.taskNo,
					teacher: reviewTask.auditTeacherBean,
					secretary: reviewTask.primarySecretaryBean,
					inputer: reviewTask.typesetterBean,
					operStep: 2,
					reviewTaskId: reviewTask.id
			};
		}
		_goPage(1);
	}
	$scope.load();
	
	$scope.selectUser = function(row){
		switch($scope.reviewTaskModel.operStep){
		case 2: $scope.reviewTaskModel.teacher = row;break;
		case 3: $scope.reviewTaskModel.secretary = row;break;
		case 4: $scope.reviewTaskModel.inputer = row;break;
		}
		if($scope.reviewTaskModel.operStep != 4){
			$scope.reviewTaskModel.operStep++;
			delete $scope.search.keyword;
			_goPage(1);
		}
	}
	
	$scope.goStep = function(step){
		$scope.reviewTaskModel.operStep = step;
		delete $scope.search.keyword;
		_goPage(1);
	}
	
	$scope.saveReviewTask = function(){
		if(!$scope.reviewTaskModel.taskNo || $scope.reviewTaskModel.taskNo.length != 14){
			toaster.pop('error', '未输入试卷名称或者试卷名称不符合规范！');
		}else if(!$scope.reviewTaskModel.teacher.id){
			toaster.pop('error', '请选择命题教师！');
		}else if(!$scope.reviewTaskModel.secretary.id){
			toaster.pop('error', '请选择学科秘书！');
		}else if(!$scope.reviewTaskModel.inputer.id){
			toaster.pop('error', '请选择排版员！');
		}else{
			//修改命卷任务相关人员
			if($scope.reviewTaskModel.reviewTaskId){
				var params = {
						id:$scope.reviewTaskModel.reviewTaskId,
						auditTeacher: $scope.reviewTaskModel.teacher.id,
						primarySecretary: $scope.reviewTaskModel.secretary.id,
						typesetter: $scope.reviewTaskModel.inputer.id,
				};
				$http.post('business/updateReviewTask', params).success(function(data){
					if(data.flag == 'failed'){
						toaster.pop('error', data.msg);
					}else{
						toaster.pop('success', '更新成功！');
						$scope.hideAddReviewTaskModal();
					}
				});
			}else{
				$http.post('business/queryTaskByTaskNo/' + $scope.reviewTaskModel.taskNo + "?batchId=" + $stateParams.id
						 + "&batchType=SHI_JUAN_FU_SHEN").success(function(data){
					var result = data.rows;
					if(result){
						if(result.length >= 1){
							toaster.pop('error', "任务名称已存在!");
						}else{
							//新增命卷任务
							var params = {
									taskNo: $scope.reviewTaskModel.taskNo,
									
										teacher: {id: $scope.reviewTaskModel.teacher.id
											, loginName: $scope.reviewTaskModel.teacher.loginName},
											
											secretary: {id: $scope.reviewTaskModel.secretary.id
													, loginName: $scope.reviewTaskModel.secretary.loginName},
													
													inputer: {id: $scope.reviewTaskModel.inputer.id
															, loginName: $scope.reviewTaskModel.inputer.loginName}
							}
							
							$http.post('business/addReviewTask/' + $stateParams.id, params).success(function(data){
								if(data.flag == 'failed'){
									toaster.pop('error', data.msg);
								}else{
									toaster.pop('success', '保存成功！');
									$scope.hideAddReviewTaskModal();
								}
							});
						}
					}
				 });
			}
		}
	}
	
	$scope.goPage = function(pageNum){
		_goPage(pageNum);
	}
	
	function _goPage(pageNum){
		if(pageNum < 1 || (pageNum > $scope.pageModel.totalPage && $scope.pageModel.totalPage > 0)){
			return;
		}
		
		$scope.pageModel.curPage = pageNum;
		
		var flag = true;
		if($scope.reviewTaskModel.operStep == 1){
			var taskno = $scope.search.taskNo;
			if(taskno == null || taskno == 'undefined'){
				$scope.reviewTaskModel.taskNo = '';
			}else{
				$scope.reviewTaskModel.taskNo = taskno;
			}
			flag = false;
		}else{
			switch($scope.reviewTaskModel.operStep){
				case 2: $scope.search.userType = userType.teacher;break;
				case 3: $scope.search.userType = userType.secretary;break;
				case 4: $scope.search.userType = userType.inputer;break;
			}
			var url = 'user/queryUsers';
			var params = {'page': pageNum
					, 'rows' : $scope.pageModel.pageSize
					, 'keyword' : $scope.search.keyword
					, 'userType': $scope.search.userType};
		}
		
		if(flag == true){
			$http.post(url, params).success(function(data){
				$scope.pageModel.array = data.rows;
				$scope.pageModel.total = data.total;
				$scope.pageModel.totalPage = Math.ceil(data.total / $scope.pageModel.pageSize);
			})
			.error(function(data, code){alert(code);});
		}
	}
})

.controller('InputBatchAddCourseCtrl',function($scope,$http,$state,$location,$modal,toaster,$stateParams){
	$scope.pageModel = {};
	$scope.pageModel.pageSize = 6;
	$scope.search = {};
	
	$scope.load = function(){
		$http.post('business/allInputQuesTasks/' + $stateParams.id).success(function(data){
			$scope.auditTasks = data.rows;
			_goPage(1);
		})
	};
	$scope.load();
	
	$scope.goPage = function(pageNum){
		_goPage(pageNum);
	}
	
	function _goPage(pageNum){
		if(pageNum < 1 || (pageNum > $scope.pageModel.totalPage && $scope.pageModel.totalPage > 0)){
			return;
		}
		
		$scope.pageModel.curPage = pageNum;
		
		var url = 'course/queryCourses';
		var params = {'page': pageNum
						, 'rows' : $scope.pageModel.pageSize
						, 'keyword' : $scope.search.keyword};
		$http.post(url, params).success(function(data){
			$scope.pageModel.array = data.rows;
			$scope.pageModel.total = data.total;
			$scope.pageModel.totalPage = Math.ceil(data.total / $scope.pageModel.pageSize);
			
			for(var i = 0; i < $scope.pageModel.array.length; i++){
				var course = $scope.pageModel.array[i];
				for(var j=0; j<$scope.auditTasks.length; j++){
					var inCourse = $scope.auditTasks[j];
					if(course.code == inCourse.courseCode){
						course.inBatch = true;
						break;
					}
				}
			}
		})
		.error(function(data, code){alert(code);});
	}
	
	$scope.addCourse = function(row){
		var param = {'courseId':row.id,'batchId':$stateParams.id};
		
		$http.post('business/addInputQuesTask',param).success(function(res){
			if(res.flag=='failed'){
				toaster.pop('error', "操作失败！");
	           return false;
			}else{
				row.inBatch = true;
				toaster.pop('success', "操作成功！");
				$scope.auditTasks[$scope.auditTasks.length] = {'courseCode':row.code};
			}
		});
	}
})

.controller('InputTaskRelatedInputersCtrl', function($scope,$http,$state,$location,$modal,toaster,$stateParams){
	$scope.pageModel = {};
	$scope.pageModel.pageSize = 6;
	$scope.search = {};
	
	function _goPage(pageNum){
		if(pageNum < 1 || (pageNum > $scope.pageModel.totalPage && $scope.pageModel.totalPage > 0)){
			return;
		}
		
		$scope.pageModel.curPage = pageNum;
		
		var url = 'user/queryUsers';
		var params = {'page': pageNum
						, 'rows': $scope.pageModel.pageSize
						, 'keyword': $scope.search.keyword
						, 'userType' : 12
						,'isEnabled': 1};
		$http.post(url, params).success(function(data){
			$scope.pageModel.array = data.rows;
			$scope.pageModel.total = data.total;
			$scope.pageModel.totalPage = Math.ceil(data.total / $scope.pageModel.pageSize);
		})
		.error(function(data, code){alert(code);});
	}
	
	$scope.goPage = function(pageNum){
		_goPage(pageNum);
	}
	
	$scope.load = function(){
		_goPage(1);
		
		$http.post('business/allInputQuesTasks/' + $stateParams.id).success(function(data){
			$scope.tasks = data.rows;
			if(data.rows.length > 0){
				if($scope.curTask == null){
					$scope.curTask = data.rows[0];
				}
			}
		})
		.error(function(data, code){
			alert(code);
		});
	};
	$scope.load();
	
	$scope.selectTask = function(row){
		$scope.curTask = row;
	}
	
	$scope.addRelation = function(row){
		var exists = false;
		for(var i=0; i < $scope.curTask.inputerList.length; i++){
			var item = $scope.curTask.inputerList[i];
			if(item.id == row.id){
				exists = true;
			}
		}
		if(!exists){
			$scope.curTask.inputerList.push(row);
			$scope.submit();
		}else{
			toaster.pop('warning', '录入员已关联！');
		}
	}
	
	$scope.deleteRelation = function(row){
		var i=0; 
		for(;i < $scope.curTask.inputerList.length; i++){
			var item = $scope.curTask.inputerList[i];
			if(item.id == row.id){
				break;
			}
		}
		$scope.curTask.inputerList.splice(i,1);
		$scope.submit();
	}
	
	$scope.submit = function(){
		var links = [];
		for(var i=0;i < $scope.curTask.inputerList.length; i++){
			var item = $scope.curTask.inputerList[i];
			links.push(item.id);
		}
		
		$http.post('business/saveLinkInputers/' + $scope.curTask.id, links).success(function(res){
			if(res.flag=='failed'){
				toaster.pop('error', "操作失败！");
	           return false;
			}else{
				toaster.pop('success', "操作成功！");
				$scope.load();
			}
		});
	}
})

.controller('TkjsBatchAddCourseCtrl',function($scope,$http,$state,$location,$modal,toaster,$stateParams){
	$scope.pageModel = {};
	$scope.pageModel.pageSize = 6;
	$scope.search = {};
	
	$scope.load = function(){
		$http.post('business/allTkjsTasks/' + $stateParams.id).success(function(data){
			$scope.auditTasks = data.rows;
			_goPage(1);
		})
	};
	$scope.load();
	
	$scope.goPage = function(pageNum){
		_goPage(pageNum);
	}
	
	function _goPage(pageNum){
		if(pageNum < 1 || (pageNum > $scope.pageModel.totalPage && $scope.pageModel.totalPage > 0)){
			return;
		}
		
		$scope.pageModel.curPage = pageNum;
		
		var url = 'course/queryCourses';
		var params = {'page': pageNum
						, 'rows' : $scope.pageModel.pageSize
						, 'keyword' : $scope.search.keyword};
		$http.post(url, params).success(function(data){
			$scope.pageModel.array = data.rows;
			$scope.pageModel.total = data.total;
			$scope.pageModel.totalPage = Math.ceil(data.total / $scope.pageModel.pageSize);
			
			for(var i = 0; i < $scope.pageModel.array.length; i++){
				var course = $scope.pageModel.array[i];
				for(var j=0; j<$scope.auditTasks.length; j++){
					var inCourse = $scope.auditTasks[j];
					if(course.code == inCourse.courseCode){
						course.inBatch = true;
						break;
					}
				}
			}
		})
		.error(function(data, code){alert(code);});
	}
	
	$scope.addCourse = function(row){
		var param = {'courseId':row.id,'batchId':$stateParams.id};
		
		$http.post('business/addTkjsTask',param).success(function(res){
			if(res.flag=='failed'){
				toaster.pop('error', "操作失败！");
	           return false;
			}else{
				row.inBatch = true;
				toaster.pop('success', "操作成功！");
				$scope.auditTasks[$scope.auditTasks.length] = {'courseCode':row.code};
			}
		});
	}
})

.controller('TkjsTaskRelatedTeachersCtrl', function($scope,$http,$state,$location,$modal,toaster,$stateParams){
	$scope.pageModel = {};
	$scope.pageModel.pageSize = 6;
	$scope.search = {};
	
	function _goPage(pageNum){
		if(pageNum < 1 || (pageNum > $scope.pageModel.totalPage && $scope.pageModel.totalPage > 0)){
			return;
		}
		
		$scope.pageModel.curPage = pageNum;
		
		var url = 'user/queryUsers';
		var params = {'page': pageNum
						, 'rows': $scope.pageModel.pageSize
						, 'keyword': $scope.search.keyword
						, 'userType' : 10
						,'isEnabled': 1};
		$http.post(url, params).success(function(data){
			$scope.pageModel.array = data.rows;
			$scope.pageModel.total = data.total;
			$scope.pageModel.totalPage = Math.ceil(data.total / $scope.pageModel.pageSize);
		})
		.error(function(data, code){alert(code);});
	}
	
	$scope.goPage = function(pageNum){
		_goPage(pageNum);
	}
	
	$scope.load = function(){
		_goPage(1);
		
		$http.post('business/allTkjsTasks/' + $stateParams.id).success(function(data){
			$scope.tasks = data.rows;
			if(data.rows.length > 0){
				if($scope.curTask == null){
					$scope.curTask = data.rows[0];
				}
			}
		})
		.error(function(data, code){
			alert(code);
		});
	};
	$scope.load();
	
	$scope.selectTask = function(row){
		$scope.curTask = row;
	}
	
	$scope.addRelation = function(row){
		var exists = false;
		for(var i=0; i < $scope.curTask.teacherList.length; i++){
			var item = $scope.curTask.teacherList[i];
			if(item.id == row.id){
				exists = true;
			}
		}
		if(!exists){
			$scope.curTask.teacherList.push(row);
			$scope.submit();
		}else{
			toaster.pop('warning', '命题教师已关联！');
		}
	}
	
	$scope.deleteRelation = function(row){
		var i=0; 
		for(;i < $scope.curTask.teacherList.length; i++){
			var item = $scope.curTask.teacherList[i];
			if(item.id == row.id){
				break;
			}
		}
		$scope.curTask.teacherList.splice(i,1);
		$scope.submit();
	}
	
	$scope.submit = function(){
		var links = [];
		for(var i=0;i < $scope.curTask.teacherList.length; i++){
			var item = $scope.curTask.teacherList[i];
			links.push(item.id);
		}
		
		$http.post('business/saveLinkTeachers/' + $scope.curTask.id, links).success(function(res){
			if(res.flag=='failed'){
				toaster.pop('error', "操作失败！");
	           return false;
			}else{
				toaster.pop('success', "操作成功！");
				$scope.load();
			}
		});
	}
})
.controller('StartedPapersListCtrl',function($cookieStore,$scope,$http,appConst,$state,FileUploader,toaster,$modal,$stateParams,$filter){
	
	$scope.pageModel = {};
	$scope.pageModel.pageSize = 10;
	$scope.search = {};

	$scope.load = function(){
		_goPage(1);
	};
	
	$scope.load();
	
	$scope.goPage = function(pageNum){
		_goPage(pageNum);
	};
	
	function _goPage(pageNum){
		if(pageNum < 1 || (pageNum > $scope.pageModel.totalPage && $scope.pageModel.totalPage > 0)){
			return;
		}
		
		$scope.pageModel.curPage = pageNum;

		var url = 'business/queryStartedPapers';
		var params = {'page': pageNum
				, 'rows': $scope.pageModel.pageSize
				, 'keyword': $scope.search.keyword};
		$http.post(url, params).success(function(data){
			$scope.pageModel.array = data.rows;
			$scope.pageModel.total = data.total;
			$scope.pageModel.totalPage = Math.ceil(data.total / $scope.pageModel.pageSize);
		})
		.error(function(data, code){alert(code);});
	}
	
	$scope.load();
	
	
	/** 导入试卷启用数据 **/
	var toImpModal = $modal({title:'导入试卷启用数据',scope: $scope, templateUrl: 'resources/app/batch/startedPapers.imp.html', show: false});
	
	$scope.toImpStartPapers = function(){
		toImpModal.$promise.then(toImpModal.show);
	}
	
	var uploader = $scope.uploader = new FileUploader({
        url: 'attachment/upload'
    });
	$scope.upload = function() {
		//$scope.loading = $q.defer().promise;
		$scope.loadingMsg = '正在上传试卷启用数据文件，请稍等...！';
		uploader.queue[0].upload();
    };
    $scope.model = {};
    $scope.submitStartPapers = function(fileItem, response, status, headers) {
		$scope.loadingMsg = '正在加载试卷启用数据文件，请稍等...！';
		var date = $scope.model.enableDateYear + "-" + $scope.model.enableDateMonth;
    	$scope.loading = $http.post('business/impStartedPapers/' + $scope.model.att.id + "?startTime=" + date)
		.success(function(data){
			if(data.flag == 'failed'){
				toaster.pop('error', data.msg);
			}
			else{
				toaster.pop('success', data.log);
				toImpModal.hide();
				$state.reload();
			}
		})
		.error(function(data,code){
			alert(code);
		});
    };
    
    uploader.onSuccessItem = function(fileItem, response, status, headers) {
    	$scope.model.att = response.att;
    	toaster.pop('success', "上传成功，请点击提交按钮。");
    };
    
    $scope.files = $scope.uploader.queue;
    $scope.uploader.onCompleteAll = function() {
		//$scope.loading = null;
		$scope.uploader.clearQueue();
	};
    
})