'use strict';
angular.module('qrzk')

/** 启用卷管理 **/
.controller('UseBatchSummaryCtrl',function($cookieStore,$scope,$http,appConst,$stateParams,$window,toaster){
	$scope.load = function(){
		var url = 'examPaper/getBatchPapers/'+$stateParams.id;
		$http({
	        'url' : url,
	        'method' : 'POST',
	        'headers': appConst.formHeaders,
	        'data' : 'page=1&rows=9999'
	    }).success(function(data){
	    	$scope.papers = data.rows;
	    	
	    	var uploadedPaperCount = 0;
	    	var uploadedAnswerCount = 0;
	    	var uploadedAnswerSheetCount = 0;
	    	var isOutBoundScannedCount = 0;
	    	var isStorageScannedCount = 0;
	    	
	    	for(var i=0; i<$scope.papers.length; i++){
	    		var paper = $scope.papers[i];
	    		
	    		if(paper.paperPath != null)
	    			uploadedPaperCount ++;
	    		if(paper.standardAnswerPath != null)
	    			uploadedAnswerCount ++;
	    		if(paper.answerSheetPath != null)
	    			uploadedAnswerSheetCount ++;
	    		if(paper.isOutBoundScanned == 1)
	    			isOutBoundScannedCount ++;
	    		if(paper.isStorageScanned == 1)
	    			isStorageScannedCount ++;	    		
	    	}
	    	
	    	$scope.batchSummary = "该批次下：已上传  "+uploadedPaperCount+" 套试卷、"
	    	+ uploadedAnswerCount +" 套答案、"
	    	+ uploadedAnswerSheetCount+" 套专卡。已有"
	    	+ isOutBoundScannedCount +" 套试卷出库扫描 "
	    	+ isStorageScannedCount+" 套试卷回库扫描。"
	    });
	};
	$scope.load();
})

.controller('UseBatchPaperCtrl',function($cookieStore,$scope,$http,appConst,$stateParams,$window,toaster){
	$scope.pageModel = {};
	$scope.pageModel.pageSize = 10;
	$scope.search = {};
	
	$scope.load = function(){
		$http.post('examSetting/validateCodeBook').success(function(data){
			$scope.downloadPapers = data.canBackup;
		});
		
		_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.isCheckAll = false;
		$scope.pageModel.curPage = pageNum;
		
		var params = {'page': pageNum
				, 'rows': $scope.pageModel.pageSize
				, 'keyword': $scope.search.keyword
				, 'batchId': $stateParams.id};
		
		$http.post('examPaper/queryBatchPapers' , 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.removePaperFromBatch = function(row, batchId){
		var params={
        		"batchId" : batchId,
        		"paperId" : row.id
        	};
		var r = $window.confirm('确定要移出试卷(试卷代码：' + row.code + ')吗？');
		if(r){
			$http.post('examPaper/removePaperFromBatch', params).success(function(data){
				if(data.result){
					toaster.pop('success', row.code + ' 移出成功！');
					$scope.load();
				}
			});
		}
	};
	
	$scope.removeSelectedPapers = function(){
		var selectedPaperIds = [];
		var selectUsedPapers = false;
		angular.forEach($scope.pageModel.array, function(item){
			if(item.isChecked){
				selectedPaperIds.push(item.id);
				if(item.status == 'USED'){
					selectUsedPapers = true;
				}
			}
		});
		
		if(selectUsedPapers){
			toaster.pop('warning', '不能移出启用状态的试卷！');
		}else if(selectedPaperIds.length > 0){
			var url = 'examPaper/removePapersFromBatch?';
			var params = "paperBatchId=" + $stateParams.id 
			+ "&relatedPaperIds=" + selectedPaperIds;
			
			$http.post(url + params).success(function(data){
				toaster.pop('success', '移出成功！');
				_goPage(1);
			}).error(function(data, code){alert(code);});
		}else{
			toaster.pop('warning', '请选择一行或多行记录！');
		}
	}
	
	$scope.checkAll = function(){
		angular.forEach($scope.pageModel.array, function(item){
			item.isChecked = $scope.isCheckAll;
		});
	}
	
	$scope.confirmUsed = function(){
		//检查是否有选中的行，如果有选中的行，则只处理选中行
		var checkedPaperIds = [];
		var hasNonOutScanPapers = false;
		angular.forEach($scope.pageModel.array, function(item){
			if(item.isChecked){
				checkedPaperIds.push(item.id);
				if(item.isOutBoundScanned != 1){
					hasNonOutScanPapers = true;
				}
			}
		});
		
		if(checkedPaperIds.length > 0){
			if(hasNonOutScanPapers){
				toaster.pop('warning', '选中的试卷中包括未出库扫描的试卷，无法启用！');
			}else if($window.confirm('您确认要将选中的试卷设置为启用状态吗？')){
				$http.post('examPaper/confirmUsedPapers', {array: checkedPaperIds}).success(function(data){
					if(data.type == 'success'){
						toaster.pop('success', '操作成功！');
						$scope.load();
					}else{
						toaster.pop('error', data.msg);
					}
				});
			}
		}else if($window.confirm('您确认要将所有试卷设置为启用状态吗？')){
			$http.post('examPaper/confirmUsedPapersAll', {batchId: $stateParams.id}).success(function(data){
				if(data.type == 'success'){
						toaster.pop('success', '操作成功！');
						$scope.load();
					}else{
						toaster.pop('error', data.msg);
					}
			});
		}
	}
})
.controller('UseBatchPaperExtractCtrl',function($cookieStore,$scope,$http,$modal,appConst,$stateParams,$window,FileUploader, $q, toaster){
	$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.isCheckAll = false;
		$scope.pageModel.curPage = pageNum;
		
		
		var params = {'page': pageNum
				, 'rows': $scope.pageModel.pageSize
				, 'keyword': $scope.search.keyword
				, 'batchId': $stateParams.id};
		
		if($scope.search.noRelatedPaper){
			params.relatedPaperNum = 0;
		}

		$http.post('dbfPaperInfo/queryDbfPaperInfo/' + $stateParams.id, 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);});
	}
	
	/** 导入课程教材信息 **/
	var uploadModal = $modal({title:'上传文档',scope: $scope, templateUrl: 'resources/app/common/upload.html', show: false});
	$scope.showImportCourseBookWin = function() {
		$scope.uploadParams = {
				accept: '.dbf',
				template: '启用批次课程教材信息上传模板.dbf',
				fileType: null,
				title: '上传课程与教材信息',
				uploadType: 'DBF'
		};
		
		uploadModal.$promise.then(uploadModal.show);
	};
	
	$scope.uploader = new FileUploader({
        url: 'dbfPaperInfo/DBFUpload/' + $stateParams.id
    });
	
	$scope.upload = function() {
		$scope.loading = $q.defer().promise;
		$scope.uploader.queue[0].upload();
    };
    
    $scope.uploader.onSuccessItem = function(fileItem, response, status, headers) {
    	if(response == 'success'){
    		toaster.pop('success', '导入成功！');
    		uploadModal.hide();
    		$scope.load();
    	}else{
    		toaster.pop('fail', '导入失败！');
    	}
    };
    
    $scope.files = $scope.uploader.queue;
    
    $scope.uploader.onCompleteAll = function() {
		$scope.loading = null;
		$scope.uploader.clearQueue();
	};
	
    $scope.checkAll = function(){
		angular.forEach($scope.pageModel.array, function(item){
			item.isChecked = $scope.isCheckAll;
		});
	}
    
    /** 删除选中的课程教材信息 **/
    $scope.removeSelectedCourses = function(){
		var selectedIds = [];
		var hasRelatedPaper = false;
		angular.forEach($scope.pageModel.array, function(item){
			if(item.isChecked){
				selectedIds.push(item.id);
				if(item.relatedPaperNum > 0){
					hasRelatedPaper = true;
				}
			}
		});
		
		if(hasRelatedPaper){
			toaster.pop('warning', '选中的课程已关联试卷，请先移出关联试卷！');			
		}else if(selectedIds.length > 0){
			var url = 'dbfPaperInfo/removeDbfPaperInfoFromBatch?';
			var params = "paperBatchId=" + $stateParams.id 
			+ "&dbfPaperInfoIds=" + selectedIds
			+ "&isRemoveRelatedPapers=false";
			
			$http.post(url + params).success(function(data){
				toaster.pop('success', '移出成功！');
				_goPage(1);
			}).error(function(data, code){alert(code);});
		}else{
			toaster.pop('warning', '请选择一行或多行记录！');
		}
	}
    
    /** 抽卷 **/
    $scope.extractPapers = function(){
    	$scope.loading = $http.post('dbfPaperInfo/autoMatchPapers/' + $stateParams.id).success(function(data){
    		console.log(data);
    		if(data.success){
    			toaster.pop('success', '匹配成功！');
    			$scope.load();
    		}else{
    			for(var i=0; i < data.messages.length; i++){
    				toaster.pop('error', data.messages[i]);
    			}
    		}
    	}).error(function(data, code){alert(code);});
    }
    
    /** 导入共卷课程 **/
    var gjuploadModal = $modal({title:'上传文档',scope: $scope, templateUrl: 'resources/app/batch/info.use.gjupload.html', show: false});
	$scope.showImportGJCourseWin = function() {
		gjuploadModal.$promise.then(gjuploadModal.show);
	};
	
	$scope.gjUploader = new FileUploader({
        url: 'examPaper/uploadGJCourses/' + $stateParams.id
    });
    
    $scope.gjupload = function(){
    	$scope.loading = $q.defer().promise;
    	$scope.gjUploader.queue[0].upload();
    };
    
    $scope.gjUploader.onSuccessItem = function(fileItem, response, status, headers) {
    	if(response.result){
    		toaster.pop('success', '导入成功！');
    	}else{
    		toaster.pop('fail', response.message);
    	}
    	gjuploadModal.hide();
    };
    
    $scope.gjfiles = $scope.gjUploader.queue;
    
    $scope.gjUploader.onCompleteAll = function() {
		$scope.loading = null;
		$scope.gjUploader.clearQueue();
	};
    
    /**查看共卷课程信息**/
    var gjCoursesModal = $modal({title:'共卷课程',scope: $scope, templateUrl: 'resources/app/batch/info.use.gj.html', show: false});
	$scope.showGJCourseWin = function() {
		$http.get('examPaper/getGJCourses/' + $stateParams.id).success(function(result){
			$scope.gjCourses = result.rows;
			gjCoursesModal.$promise.then(gjCoursesModal.show);
		});
	};
	
})

/** 关联启用试卷 **/
.controller('UseBatchAddPaperCtrl',function($cookieStore,$scope,$http,appConst,$stateParams,$window,toaster){
	$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.isCheckAll = false;
		$scope.pageModel.curPage = pageNum;
		
		var params = {'page': pageNum
				, 'rows': $scope.pageModel.pageSize
				, 'keyword': $scope.search.keyword
				, 'batchId': $stateParams.id};
		
		$http.post('examPaper/queryFormalPaperForUse' , 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.relatedPaper = function(row, batchId){
		var url = 'examPaper/addPapersToBatch';
		var params={
        		"batchId" : batchId,
        		"paperId" : row.id
        	};
		$http.post('examPaper/addPaperToBatch', params).success(function(data){
			row.isRelated = true;
			toaster.pop('success', row.code + ' 添加成功！');
	    });
	}
	
	$scope.relateSelectedPapers = function(){
		var selectedPaperIds = [];
		angular.forEach($scope.pageModel.array, function(item){
			if(item.isChecked){
				selectedPaperIds.push(item.id);
			}
		});
		var url = 'examPaper/addPapersToBatch?';
		var params = "batchId=" + $stateParams.id 
					+ "&paperIds=" + selectedPaperIds;
		
		$http.post(url + params).success(function(data){
			toaster.pop('success', '添加成功！');
			_goPage(1);
		}).error(function(data, code){alert(code);});
	}
	
	$scope.checkAll = function(){
		angular.forEach($scope.pageModel.array, function(item){
			item.isChecked = $scope.isCheckAll;
		});
	}
})

/** 启用批次-出库扫描 **/
.controller('UseOutScanCtrl',function($cookieStore,$scope,$http,appConst,$state,$stateParams){
	$scope.model = {};
	$scope.scanHistories = [];
	$scope.submit = function(){
		$scope.model.batchId = $stateParams.id;
		$http.post('examPaper/outbound', $scope.model)
		.success(function(data){
			$scope.paper=data.paper;
			$scope.scanHistories.unshift({'code':$scope.model.code, 'result': data.result, 'msg': data.msg});
			$scope.model.code='';
			if(data.result){
				$scope.soundSrc = 'resources/sound/scansuccess.wav';
			}else{
				$scope.soundSrc = 'resources/sound/scanfail.wav';
			}
			var audio = new Audio();
			audio.src=$scope.soundSrc;
			audio.play();
		})
		.error(function(data,code){
			alert(code);
		});
		
	};
})

/** 启用批次-回库扫描 **/
.controller('UseInScanCtrl',function($cookieStore,$scope,$http,appConst,$state,$stateParams){
	$scope.model = {};
	$scope.scanHistories = [];
	$scope.submit = function(){
		$scope.model.batchId = $stateParams.id;
		$http.post('examPaper/useInScan', $scope.model)
		.success(function(data){
			$scope.paper=data.paper;
			$scope.scanHistories.unshift({'code':$scope.model.code, 'result': data.result, 'msg': data.msg});
			$scope.model.code='';
			if(data.result){
				$scope.soundSrc = 'resources/sound/scansuccess.wav';
			}else{
				$scope.soundSrc = 'resources/sound/scanfail.wav';
			}
			var audio = new Audio();
			audio.src=$scope.soundSrc;
			audio.play();
		})
		.error(function(data,code){
			alert(code);
		});
		
	};
})

/** 启用批次库存统计 **/
.controller('UseBatchStockCtrl',function($cookieStore,$scope,$http,appConst,$stateParams,$window,toaster){
	$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 params = {'page': pageNum
				, 'rows': $scope.pageModel.pageSize
				, 'keyword': $scope.search.keyword
				, 'batchId': $stateParams.id};
		
		$http.post('dbfPaperInfo/queryUseBatchStock' , 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.downloadToExcel = function(){
		$window.open("dbfPaperInfo/downloadUseBatchStockToExcel/" + $stateParams.id);
	}
})
