'use strict';
angular.module('qrzk')
.filter('sumByField',function(){
	return function(data,key){
		if (typeof(data) === 'undefined' || typeof(key) === 'undefined') {
            return 0;
        }

        var sum = 0;
        for (var i = data.length - 1; i >= 0; i--) {
            sum += parseInt(data[i][key]);
        }

        return sum;
	};
})
/** 省份信息管理 **/
.controller('ProvinceCtrl',function($scope,$http,Province,appConst,toaster,PaperType){
	
	$scope.groups = PaperType.query();
	$scope.provs = [];
	$scope.load = function(){
		$scope.loading = Province.query().$promise.then(function(data){
			$scope.provs = data;
		});
	};
	$scope.load();
	
	$scope.saveProv = function(data,index){
		angular.extend($scope.provs[index],data);
		var name = $scope.provs[index].name;
		$scope.loading = $scope.provs[index].$save(function(res){
			if(res.result){
				toaster.pop('success',name,'保存成功！');
				$scope.load();
			}
		});
		
	};
})
/** 供卷 **/
.controller('BatchInfoSupplyCtrl',function(Batch,$window,$scope,$http,
		$state,$stateParams,appConst,$q){
	$scope.courses = [];
	var batchId = $stateParams.id;
	var batch = $scope.batch = Batch.get({id:$stateParams.id});
	$scope.trackType = 'paperPrint';
	
	$scope.load = function(){
		var url = 'supply/course/batch/'+batchId;
		$scope.promise = $http.get(url).success(function(data){
	    	$scope.courses = data;
	    });
	};
	
	$http.get('printtasks?batchId='+batchId)
	.success(function(provs){
		$scope.provs = provs;
		$scope.load();
		
	});
	
	$scope.showTotal = function(code){
		var list = _.filter($scope.courses,function(item){
			var provs = item.supplyProvInfo;
			var prov = _.findWhere(provs,{provCode:code});
			if(prov)return true;
		});
		return list.length;
	}
	
	
	$scope.refresh = function(){
		$state.reload();
	}
	
	$scope.expStartedPapers = function(){
		window.open('supply/course/expStartedPapers/'+batchId);
	}
})
//供卷管理
.controller('BatchInfoSupplyMgtCtrl',function(Batch,$window,$scope,$rootScope,
		$http,$state,$stateParams,appConst,FileUploader,$q,toaster){
	var batchId = $stateParams.id;
	var batch = $scope.batch = Batch.get({id:batchId});
	$scope.courses = [];
	$scope.load = function(){
		var url = 'supply/course/batch/'+batchId;
		$scope.loading = $http.get(url).success(function(data){
	    	$scope.courses = data;
	    	if(data.length >0){
	    		if($rootScope.selectedIndex){
		    		$scope.selected = data[$rootScope.selectedIndex];
	    		}
	    		else{
	    			$scope.selected = data[0];
	    		}
	    		$scope.supplyProvInfo = $scope.selected.supplyProvInfo;
	    	}
	    });
	};
	
	$http.get('province')
	.success(function(data){
		$scope.provs = data;
		$scope.load();
		
	});
	
	//选择课程
	$scope.selected = null;
	$scope.supplyProvInfo = [];
	var selectedIndex = 0;
	$scope.selectCourse = function(index){
		$scope.selected = $scope.courses[index];
		selectedIndex = index;
		
		$scope.supplyProvInfo = $scope.courses[index].supplyProvInfo;
	};
	
	//删除
	$scope.remove = function(id){
		var r = $window.confirm('删除供卷课程会同时删除关联的供卷身份，是否确定？');
		if(r){
			$http.delete('supply/course/'+id)
			.success(function(data){
				if(data.result){
					toaster.pop('success','删除成功！');
					$rootScope.selectedIndex = null;
					$state.reload();
				}
			});
		}
	}
	
	//进入修改
	$scope.edit = function(id){
		$rootScope.selectedIndex = selectedIndex;
		$state.go('batch.info.supplyform',{op:'edit',supplyCourseId:id});
	};
	
	$scope.uploader = new FileUploader({
		url: 'supply/course/upload/'+batchId
	});
	
	$scope.files = $scope.uploader.queue;
	$scope.upload = function(){
		var r = $window.confirm('上传供卷课程设置会删除现有数据，是否确定？');
		if(r){
			$scope.loading = $q.defer().promise;
			var files = $scope.uploader.queue;
			files[0].upload();
		}
	};
	
	$scope.uploader.onSuccessItem = function(fileItem, response, status, headers) {
		if(response.flag == 'success'){
			toaster.pop('success','导入成功！');
		}else{
			toaster.pop('error', response.msg);
		}
    };
	
	$scope.uploader.onCompleteAll = function() {
		$scope.load();
		$scope.loading = null;
		$scope.uploader.clearQueue();
	};
})
/** 供卷表单 **/
.controller('BatchInfoSupplyFormCtrl',function(Batch,$scope,Province,
		$window,$http,$state,$stateParams,appConst,toaster){
	var batchId = $stateParams.id;
	var currentBatch = Batch.get({id:batchId});
	$scope.op = $stateParams.op;
	$scope.title = $stateParams.op == 'add'?'添加':'修改';
	$scope.courses = [];
	$scope.provs = [];
	$scope.selected;//选择的课程
	$scope.supplyCourseId;//修改时保存供卷课程id
	
	$http.get('course')
	.success(function(data){
		$scope.courses = data;
	});
	$http.get('province')
	.success(function(provs){
		$scope.provs = provs;
		
		//如果是修改，从服务器端获取供卷课程数据
		if($stateParams.op == 'edit'){
			var scId = $stateParams.supplyCourseId;
			$http.get('supply/course/'+scId)
			.success(function(data){
				$scope.selected = data;
				$scope.editCourse = data;
				
				var provInfos = data.supplyProvInfo;
				for(var i = 0 ; i < $scope.provs.length; i++){
					angular.forEach(provInfos,function(info){
						if($scope.provs[i].code == info.provCode){
							$scope.provs[i].supplyProvId = info.id;
							$scope.provs[i].enabled = true;
							$scope.provs[i].paperType = info.paperType;
							$scope.provs[i].paperFormat = info.paperFormat;
							$scope.provs[i].batchId = info.batchId;
							$scope.provs[i].courseCode = info.courseCode;
							$scope.provs[i].courseName = info.courseName;
						}
					});
					
					if(!$scope.provs[i].enabled || $scope.provs[i].enabled == false){
						$scope.provs[i].batchId = batchId;
						$scope.provs[i].courseCode = $scope.editCourse.courseCode;
						$scope.provs[i].courseName = $scope.editCourse.courseName;
					}
				}
				
			});
		}
	});
	
	
	//保存
	$scope.save = function(){
		
		var selected = $scope.selected;
		var provs = _.where($scope.provs,{enabled:true});
		var mergeCnt = _.where(provs,{paperFormat:'MERGE'}).length;
		var sepCnt = _.where(provs,{paperFormat:'SEPERATE'}).length;
		var supplyCourse;
		if($stateParams.op == 'edit'){
			supplyCourse = angular.extend({},$scope.editCourse);
			supplyCourse.supplyProvInfo = [];
		}
		else{
			supplyCourse = {
				batchId:currentBatch.id,
				batchCode:currentBatch.code,
				supplyProvInfo:[]
			};
		}
		supplyCourse.examTime = currentBatch.remark;
		supplyCourse.courseCode = selected.courseCode;
		supplyCourse.courseName = selected.courseName;
		supplyCourse.mergeCount = mergeCnt;
		supplyCourse.sepCount = sepCnt;
		supplyCourse.total = mergeCnt+sepCnt;
		angular.forEach(provs,function(item){
			var provInfo = {
				batchId:item.batchId,
				courseCode:item.courseCode,
				courseName:item.courseName,
				provCode:item.code,
				provName:item.name,
				paperType:item.paperType,
				paperFormat:item.paperFormat				
			};
			if($stateParams.op == 'edit'){
				provInfo.id = item.supplyProvId;
				provInfo.supplyCourseId = supplyCourse.id;
			}
			supplyCourse.supplyProvInfo.push(provInfo);
		});
		$scope.myPromise = $http.post('supply/course',supplyCourse)
		.success(function(data){
			if(data.result){
				toaster.pop('success','提交成功！');
				$window.history.back();
			}
		})
		.error(function(){
			toaster.pop('error','操作失败，供卷课程重复！');
		});
	};
})
/** 启用试卷 **/
.controller('BatchInfoSupplyPaperCtrl',function(Batch,$stateParams,$scope,
		$window,$http,$filter,toaster){
	var batchId = $stateParams.id;
	//var currentBatch = Batch.get({id:batchId});
	//加载已添加的供卷课程
	$scope.courses = [];
	$scope.selected;
	$scope.flag = false;//只显示未关联的课程
	
	var courses;
	$scope.loading = $http.get('supply/course/batch/'+batchId)
	.success(function(data){
		$scope.courses = courses = data;
		if(data.length > 0){
			$scope.selected = data[0];
		}
	})
	
	//选择课程
	var selectedIndex = 0;
	$scope.selectCourse = function(index){
		$scope.selected = courses[index];
		selectedIndex = index;
		$scope.loadPapers();
	}
	
	//根据所选课程加载试卷
	$scope.papers = [];
	$scope.loadPapers = function(){
		var courseCode = $scope.selected.courseCode;
		$scope.loading = $http.get('supply/course/paper/' + $stateParams.id + '/' +courseCode)
		.success(function(data){
			$scope.papers = data;
		});
	}
	
	//关联试卷
	$scope.assignPaper = function(paper){
		var url = 'supply/course/'+$scope.selected.id+'/paper/'+paper.id;
		$scope.loading = $http.put(url)
		.success(function(data){
			if(data.result){
				selectedIndex++;
				var title = $scope.selected.courseCode+' '+$scope.selected.courseName;
				toaster.pop('success',title,"启用试卷成功！");
				$scope.selected.paperId = paper.id;
				if(selectedIndex == $scope.courses.length){
					$scope.selected = $scope.courses[0];
					selectedIndex = 0;
				}
				else{
					$scope.selected = $scope.courses[selectedIndex];
				}
				$scope.loadPapers();
			}
		});
	}
})
//打印安排
.controller('BatchInfoSupplyPrintTaskCtrl',function(Batch,$stateParams,$scope,$window,$http,$aside,toaster){
	var batchId = $stateParams.id;
	//var currentBatch = Batch.get({id:batchId});
	$scope.availProvs = [];
	$scope.tasks = [];
	
	
	$scope.load = function(){
		//判断是否还有未启用试卷的课程或毛坯试卷
		$http.get('printtasks/avail?batchId='+batchId)
		.success(function(data){
			$scope.printStatus = data;
		});
		
		//获取未分配的省份数量
		$http.get('printtasks?flag=true&batchId='+batchId)
		.success(function(data){
			$scope.availProvsCount = data.length;
		});
	}
	
	$scope.load();
	
	
	function _loadTasks(){
		$scope.loading = $http.get('printtasks/users?batchId='+batchId)
		.success(function(data){
			$scope.tasks = data;
		})
	}
	_loadTasks();
	
	//计算试卷份数
	$scope.sum = function(data){
		var sum = 0;
		angular.forEach(data,function(item){
			sum += item.paperCount;
		})
		return sum;
	}
	
	var aside = $aside({
		 scope: $scope, 
		 show:false,
		 templateUrl: 'resources/app/batch/dialog.html'
	});
	
	var activeUser = null;
	$scope.show = function(user){
		activeUser = user;
		$http.get('printtasks?flag=true&batchId='+batchId)
		.success(function(data){
			$scope.availProvs = data;
			aside.show();
		});
	}
		  
	$scope.hide = function(){
		aside.hide();
	}
	
	$scope.autoAssign = function(){
		var r = $window.confirm('执行自动分配会先清除所有已分配的任务，是否执行？');
		if(r){
			$scope.loading = $http.get('supply/course/print/assign?batchId='+batchId)
			.success(function(data){
				if(data.result){
					toaster.pop('success', '分配任务成功。');
					_loadTasks();
					$scope.availProvsCount = 0;
				}else{
					toaster.pop('error', data.msg);
				}
			});
		}
	}
	
	$scope.add = function(){
		var arr = [];
		angular.forEach($scope.availProvs,function(item){
			if(item.selected){
				var p = 'idArr='+item.id;
				arr.push(p);
			}
		});
		var params = arr.join('&')+'&userId='+activeUser.id;
		$http.put('printtasks/users?'+params)
		.success(function(data){
			if(data.result){
				angular.forEach($scope.availProvs,function(item){
					if(item.selected){
						activeUser.tasks.push(item);
						$scope.availProvsCount--;
					}
				});
				aside.hide();
			}
		});
	}
	
	//删除省份打印任务
	$scope.removeTask = function(row,index){
		var taskId = row.tasks[index].id;
		var params = 'idArr='+taskId;
		row.tasks.splice(index,1);
		$http.put('printtasks/users?'+params)
		.success(function(data){
			if(data.result){
				$scope.availProvsCount++;
			}
		});
	}
	
})
//参数设置
.controller('BatchInfoSupplyConfigCtrl',function($stateParams,$scope,$http,toaster){
	var batchId = $stateParams.id;
	$scope.config = null;
	$http.get('supplyconfig?batchId='+batchId)
	.success(function(data){
		$scope.config = data;
	})
	$scope.submit = function(){
		$scope.loading = $http.put('supplyconfig',$scope.config)
		.success(function(data){
			if(data.result){
				toaster.pop('success','设置成功');
			}
		});
	}
})
//供卷打印
.controller('BatchInfoSupplyPrintCtrl',function($stateParams,$scope,$http,toaster){
	var batchId = $scope.batchId = $stateParams.id;
	$scope.flag = 'all';
	$scope.provCode = '11';
	$scope.provs = [];
	
	$http.get('print/supply/provinces/'+batchId	)
	.success(function(data){
		for(var i=0;i<data.length;i++){
			$scope.provs.push({provCode:data[i][0],provName:data[i][1]});
		}
	});
	
	$scope.courses = [];
	$http.get('print/supply/courses/'+batchId)
	.success(function(data){
		$scope.courses = data;
	});
})

//查看供卷打印日志
.controller('SupplyPrintLogCtrl',function($stateParams,$scope,$http,toaster){
	var batchId = $scope.batchId = $stateParams.id;
	
	$http.get('printlogs/queryPrintDates/'+batchId	)
	.success(function(data){
		$scope.printDates = data;

		if($scope.printDates.length > 0){
			$scope.printDate = $scope.printDates[0];
			var url = "printlogs/queryByBatchIdAndPrintDate/" + batchId + "/" + $scope.printDates[0];
			$http.get(url).success(function(data){
				$scope.array = data;
			});
		}
	});
	
	$scope.changePrintDate = function(){
		var url = "printlogs/queryByBatchIdAndPrintDate/" + batchId + "/" + $scope.printDate;
		$http.get(url).success(function(data){
			$scope.array = data;
		});
	}
})

//检查任务安排
.controller('BatchInfoSupplyScanTaskCtrl',function(Batch,$stateParams,$scope,$window,$http,$aside,toaster){
	var batchId = $stateParams.id;
	$scope.batchId = batchId;
	$scope.availProvs = [];
	$scope.tasks = [];
	
	$scope.load = function(){
		//判断是否已分配打印任务，分配打印任务后才能创建检查任务
		$http.get('scantasks/avail?batchId='+batchId)
		.success(function(data){
			$scope.printStatus = data;
		});
		
		$http.get('scantasks/queryAvailProvs/'+batchId)
		.success(function(data){
			$scope.availProvsCount = data.length;
		});
	}
	
	$scope.load();
	
	
	function _loadTasks(){
		$scope.loading = $http.get('scantasks/users?batchId='+batchId)
		.success(function(data){
			$scope.tasks = data;
		})
	}
	_loadTasks();
	
	//计算课程数
	$scope.sum = function(data){
		var sum = 0;
		angular.forEach(data,function(item){
			sum += item.paperCount;
		})
		return sum/2;
	}
	
	$scope.exportData = function(data){
		$scope.loadingMsg = '正在生成导出数据文件，请稍等...！';
		
		$scope.loading = $http.post('scantasks/exportData/' + batchId)
			.success(function(data){
				if(data.flag == 'failed'){
					alert('error', data.msg);
				}
				else{
					$("#downloadForm").attr("action","attachment/download/" + data.att.id);
    				$("#downloadForm").submit();
					toaster.pop('success', '操作成功！');
				}
			})
			.error(function(data,code){alert(code);});
	};
	
	var aside = $aside({
		 scope: $scope, 
		 show:false,
		 templateUrl: 'resources/app/batch/dialog.html'
	});
	
	var activeUser = null;
	//显示为分配的省份
	$scope.show = function(user){
		activeUser = user;
		$http.get('scantasks/queryAvailProvs/'+batchId)
		.success(function(data){
			$scope.availProvs = data;
			aside.show();
		});
	}
		  
	$scope.hide = function(){
		aside.hide();
	}
	
//	$scope.autoAssign = function(){
//		var r = $window.confirm('执行自动分配会先清除所有已分配的任务，是否执行？');
//		if(r){
//			$scope.loading = $http.get('supply/course/scan/assign?batchId='+batchId)
//			.success(function(data){
//				if(data.result){
//					_loadTasks();
//				}
//			});
//		}
//	}
	
	$scope.add = function(){
		var arr = [];
		angular.forEach($scope.availProvs,function(item){
			if(item.selected){
				var p = 'idArr='+item.id;
				arr.push(p);
			}
		});
		var params = arr.join('&')+'&userId='+activeUser.id;
		$http.put('scantasks/users?'+params)
		.success(function(data){
			if(data.result){
				angular.forEach($scope.availProvs,function(item){
					if(item.selected){
						activeUser.tasks.push(item);
						$scope.availProvsCount--;
					}
				});
				aside.hide();
			}
		});
	}
	
	//删除省份打印任务
	$scope.removeTask = function(row,index){
		var taskId = row.tasks[index].id;
		var params = 'idArr='+taskId;
		row.tasks.splice(index,1);
		$http.put('scantasks/users?'+params)
		.success(function(data){
			if(data.result){
				$scope.availProvsCount++;
			}
		});
	}
	
})

.controller('BatchInfoSupplyScanCtrl',function($stateParams,$scope,$window,$http,$aside,toaster){
	$scope.scanType = $stateParams.scanType;
	$scope.courses = [];
	$scope.provs = [];
	
	$scope.load = function(){
		$http.get('batch/getLatest')
		.success(function(data){
			$scope.batch = data;
			
			if($scope.batch != null){
				var url = 'supply/course/batch/'+$scope.batch.id;
				$scope.promise = $http.get(url).success(function(data){
					$scope.courses = data;
				});
				
				$http.get('scantasks?batchId='+$scope.batch.id)
				.success(function(provs){
					$scope.provs = provs;
				});
			}
		});
	};
	
	$scope.load();
	
	$scope.model = {};
	$scope.submit = function(){
		var obj = angular.toJson($scope.model);
		$scope.model.batchId = $scope.batch.id;
		
		if($scope.model.barcode.length == 8){
			var courseCode = $scope.model.barcode.substring(0, 5);
			var provCode = $scope.model.barcode.substring(5, 7);
			var scanType = $scope.model.barcode.substring(7);
			var taskItemId = 0;
			
			if(scanType == 1)
				scanType = 'paper';
			else if(scanType == 2)
				scanType = 'answer';
			
			if(scanType != $scope.scanType){
				toaster.pop('warning', scanType == 'paper' ? '您扫描的是试卷！' : '您扫描的是答案！');
				_playAudio(false);
				return;				
			}
			//遍历获取是否有此扫描任务
			var xizang = 54;
			var sichuan = 51;
			for(var i=0; i < $scope.provs.length; i++){
				var p = $scope.provs[i];
				if(p.provCode == provCode || (provCode == sichuan && p.provCode == xizang)){
					for(var j=0; j<p.taskItems.length; j++){
						var taskItem = p.taskItems[j];
						if(taskItem.courseCode == courseCode){
							taskItemId = taskItem.id;
							if(scanType == 'paper'){
								taskItem.isPaperScanned = true;
							}else{
								taskItem.isAnswerScanned = true;
							}
							break;
						}
					}
					break;
				}
			}
			
			if(taskItemId != 0 && (scanType == 'paper' || scanType == 'answer')){
				var url = (scanType == 'paper') ? 'scantasks/taskitems/paperScanned/' + taskItemId 
						: 'scantasks/taskitems/answerScanned/' + taskItemId;
				$http.post(url)
				.success(function(data){
					$scope.model.barcode='';
					_playAudio(data.result);
				})
				.error(function(data,code){
					alert(code);
				});
			}else{
				toaster.pop('warning', '找不到扫描任务！');
				_playAudio(false);
			}
			
			
		}else{
			toaster.pop('warning', '条形码必须为8位数字！');
			_playAudio(false);
		}
		
	};
	
	function _playAudio(flag){
		var soundSrc = 'resources/sound/scansuccess.wav';
		if(!flag){
			soundSrc = 'resources/sound/scanfail.wav';
		}
		var audio = new Audio();
		audio.src=soundSrc;
		audio.play();
	}
})

