'use strict';
angular.module('qrzk')
/** 题库统计 **/
.controller('QuestionReportTopCtrl',function($cookieStore,$scope,$http,appConst){

	$scope.load = function(){
		var url = 'user/queryUsers';
		$http.get(url).success(function(data){
			$scope.array = data.rows;
		})
		.error(function(data, code){alert(code);});
	};
	$scope.load();
})

.controller('QuestionAddCtrl',function($cookieStore,$scope,$http,appConst,$state,toaster,$modal,$stateParams){
	$scope.model = {};
	$scope.months=['',1,4,7,10];
	$scope.model.enableTimeYear = '';
	$scope.model.enableTimeMonth = '';
	$scope.bookMap = {};
	$scope.load = function(){
		$http.get('question/getInputTaskCourses').success(function(data){
			$scope.courses = data.courses;
			$scope.status = data.status;
			$scope.codes = data.codes;
			
			$scope.books = [];
			//获取所有课程的教材，并放入一个列表中。
			angular.forEach($scope.courses, function(course){
				var books = data.courseBookMap[course.id];
				angular.forEach(books, function(book){
					book.courseId = course.id;
					$scope.books.push(book);
					$scope.bookMap[book.id] = book;
				});
			});
			
			//默认设置第一个课程
			if($scope.courses && $scope.courses.length > 0){
				$scope.model.courseId = $scope.courses[0].id;
				$scope.changeCourse();
			}
			
			//能力要求，考核要求，预计难度 均默认设置为第一个属性
			var itemType = '';
			angular.forEach($scope.codes, function(code){
				if(code.itemType == 'ABILITY' && code.itemType != itemType){
					itemType = code.itemType;
					$scope.model.abilityCode = code.itemCode;
				}
				
				if(code.itemType == 'ASSESSMENT_DEMAND' && code.itemType != itemType){
					itemType = code.itemType;
					$scope.model.assessmentDemand = code.itemCode;
				}
				
				if(code.itemType == 'QUESTION_DIFFICULTY' && code.itemType != itemType){
					itemType = code.itemType;
					$scope.model.estimateDifficultyCode = code.itemCode;
				}
				
			})
		})
		.error(function(data, code){alert(code);});
	};
	$scope.load();
		
	$scope.changeCourse = function(){
		angular.forEach($scope.books, function(book){
			if(book.courseId == $scope.model.courseId){
				$scope.model.book = book;
			}
		});
		
		$http.post('question/loadQuestionTypeByCourseId/' + $scope.model.courseId).success(function(data){
			$scope.questionTypes = data;
			if($scope.questionTypes && $scope.questionTypes.length > 0){
				$scope.model.typeId = $scope.questionTypes[0].id;
				$scope.changeQuestionType();
			}
		})
		
		$http.post('question/loadTeachersByCourseId/' + $scope.model.courseId).success(function(data){
			$scope.teachers = data;
			//当只有一个命题教师时，设置默认值
			if($scope.teachers.length == 1){
				$scope.model.teacher = $scope.teachers[0];
			}
		})
		
		//为试题自动生成题号
		for(var i=0; i<$scope.courses.length; i++){
			var course = $scope.courses[i];
			if(course.id == $scope.model.courseId){
				//如果当前选中的课程没有题号，则生成题号，避免用户来回切换课程时题号不断增加
				if(!course.questionNo){
					$http.post('question/getNewQuestionNo/' + course.code).success(function(data){
						course.questionNo = data.questionNo;
						$scope.model.questionNo = course.questionNo;
					}).error(function(data, code){alert('error');});
				}else{
					//如果当前选中的课程已经生成题号，则将题号赋予当前试题
					$scope.model.questionNo = course.questionNo;
				}
				break;
			}
		}
	}
	
	$scope.changeQuestionType = function(){
		var selectedQt;
		for(var i=0; i<$scope.questionTypes.length; i++){
			var qt = $scope.questionTypes[i];
			if(qt.id == $scope.model.typeId){
				selectedQt = qt;
				break;
			}
		}
		//修改题型时，若题型有默认分值，则设置试题满分值
		if(qt.defaultScore){
			$scope.model.score = qt.defaultScore;
		}else{
			$scope.model.score = null;
		}
		
		//修改题型对应的选项和答案属性
		switch(qt.correctOptionsNum){
		case 0: //主观题
			$scope.model.options = null;
			$scope.model.answer = '';
			break;
		case 1: //单项选择题
			$scope.model.options = [{'optionNo': 0, 'isCorrectOption': 0}
								,{'optionNo': 1, 'isCorrectOption': 0}
								,{'optionNo': 2, 'isCorrectOption': 0}
								,{'optionNo': 3, 'isCorrectOption': 0}
							];
			delete $scope.model.answer;
			break;
		case 2: //多项选择题
			$scope.model.options = [{'optionNo': 0, 'isCorrectOption': 0}
								,{'optionNo': 1, 'isCorrectOption': 0}
								,{'optionNo': 2, 'isCorrectOption': 0}
								,{'optionNo': 3, 'isCorrectOption': 0}
								,{'optionNo': 4, 'isCorrectOption': 0}
							];
			delete $scope.model.answer;
			break;
		default:
			break;
		}
	}
	
	function _validateForm(){
		var invalid = false;
		
		//校验题干不能为空
		if($scope.model.body == null || $scope.model.body.length == 0){
			toaster.pop('error', '题干不能为空！');
			invalid = true;
		}
		//校验选项内容不为空
		angular.forEach($scope.model.options, function (option) {
			if(option.content == null || option.content.length == 0){
				toaster.pop('error', '选项不能为空！');
				invalid = true;
			}
		});
		
		//校验答案与解析内容不为空
		if($scope.model.options == null || $scope.model.options.length == 0){
			if($scope.model.answer == null || $scope.model.answer.length == 0){
				toaster.pop('error', '答案与解析不能为空！');
				invalid = true;
			}
		}
		
		//单项选择题选项校验
		if($scope.model.options && $scope.model.options.length == 4){
			if($scope.model.correctOptionNo == null){
				toaster.pop('error', '请选择一个正确答案！');
				invalid = true;
			}
		}
		//多项选择题选项校验
		var correctOptionCount = 0;
		if($scope.model.options && $scope.model.options.length == 5){
			angular.forEach($scope.model.options, function (option) {
				if(option.checked){
					correctOptionCount++;
				}
			});
			if(correctOptionCount < 1 ){
				toaster.pop('error', '请选择正确答案！');
				invalid = true;
			}
		}
		//选项内容重复校验
		var duplicate = false;
		if($scope.model.options && $scope.model.options.length > 0){
			angular.forEach($scope.model.options, function(option1){
				angular.forEach($scope.model.options, function(option2){
					if(option1.optionNo != option2.optionNo && option1.content == option2.content){
						duplicate = true;
					}
				})
			})
		}
		if(duplicate){
			toaster.pop('error', '有重复选项！');
			invalid = true;
		}
		
		return invalid;
	}
	
	$scope.submit = function(){
		if(_validateForm()){
			return;
		}
		
		var curBook = $scope.bookMap[$scope.model.book.id];
		if(curBook.enableDate && $scope.model.setTime){
			var setTime = new Date($scope.model.setTime);
			var bookEnableDate = new Date(curBook.enableDate);
			bookEnableDate.setHours(0);
			bookEnableDate.setMinutes(0);
			bookEnableDate.setSeconds(0);
			if(bookEnableDate.getTime() > setTime.getTime()){
				toaster.pop('error', "命题时间不能小于教材启用时间[" + bookEnableDate.getFullYear() + "-" + (bookEnableDate.getMonth() + 1) + "]");
				$scope.submitted = true;
				return false;
			}
		}else if(!curBook.enableDate){
			toaster.pop('error', "当前选中的教材没有配置教材启用时间，请与业务管理员联系。");
			$scope.submitted = true;
			return false;
		}
		
		var enableTimeYear = $scope.model.enableTimeYear;
		var enableTimeMonth = $scope.model.enableTimeMonth;
		if(enableTimeYear != '' && (typeof(enableTimeMonth) == "undefined" || enableTimeMonth == '')){
			toaster.pop('error', "请选择月份");
			$scope.submitted = true;
			return false;
		}
		if((typeof(enableTimeYear) == "undefined" || enableTimeYear == '') && enableTimeMonth != ''){
			toaster.pop('error', "请输入年份");
			$scope.submitted = true;
			return false;
		}
		var enableTime = '';
		if(enableTimeYear != ''){
			enableTime = new Date();
			enableTime.setFullYear(enableTimeYear);
			enableTime.setMonth(enableTimeMonth - 1);
			enableTime.setDate(1);
			enableTime.setHours(0);
			enableTime.setMinutes(0);
			enableTime.setSeconds(0);
			if($scope.model.setTime){
				var setTime = new Date($scope.model.setTime);
				setTime.setHours(0);
				setTime.setMinutes(0);
				setTime.setSeconds(0);
				if(setTime.getTime() > enableTime.getTime()){
					toaster.pop('error', "命题时间不能大于试题启用时间，请重新填写。");
					$scope.submitted = true;
					return false;
				}
			}
			if(curBook.enableDate){
				var bookEnableDate = new Date(curBook.enableDate);
				bookEnableDate.setHours(0);
				bookEnableDate.setMinutes(0);
				bookEnableDate.setSeconds(0);
				if(bookEnableDate.getTime() > enableTime.getTime()){
					toaster.pop('error', "试题启用时间不能小于教材启用时间[" + bookEnableDate.getFullYear() + "-" + (bookEnableDate.getMonth() + 1) + "]");
					$scope.submitted = true;
					return false;
				}
			}
		}
		
		if($scope.form.$invalid){
			toaster.pop('error', "校验失败，请检查表单中红框部分的内容！");
			$scope.submitted = true;
			return;
		}
		
		//单项选择题选项处理
		if($scope.model.options && $scope.model.options.length == 4){
			 angular.forEach($scope.model.options, function (option) {
				 	if(option.optionNo == $scope.model.correctOptionNo){
				 		option.isCorrectOption = 1;
				 	}else{
				 		option.isCorrectOption = 0;
				 	}
			    });
		}
		delete $scope.model.correctOptionNo;

		//多项选择题选项处理
		if($scope.model.options && $scope.model.options.length == 5){
			angular.forEach($scope.model.options, function (option) {
				if(option.checked){
					option.isCorrectOption = 1;
				}else{
					option.isCorrectOption = 0;
				}
				delete option.checked;
			});
		}
		
		//教材处理
		$scope.model.bookId = $scope.model.book.id;
		delete $scope.model.book;
		//命题教师处理
		$scope.model.setTeacherName = $scope.model.teacher ? $scope.model.teacher.name : null;
		delete $scope.model.teacher;
		
		$scope.model.enableTime = enableTime;
		delete $scope.model.enableTimeYear;
		delete $scope.model.enableTimeMonth;
		$scope.loading =  $http.post('question/saveQues', $scope.model).success(function(data){
			$scope.loadingMsg = '正在保存试题，请稍等...';
			if(data.question){
				toaster.pop('success', '保存成功，继续录入下一题。');
				if($scope.model.enableTime){
					var enableTime = new Date($scope.model.enableTime);
					$scope.model.enableTimeYear = enableTime.getFullYear();
					$scope.model.enableTimeMonth = enableTime.getMonth()+1;
				}else{
					$scope.model.enableTimeYear = '';
					$scope.model.enableTimeMonth = '';
				}
				//清空题干和答案。
				$scope.model.body = '';
				$scope.model.answer = $scope.model.answer ? '' : null; 
				angular.forEach($scope.model.options, function (option) {
					option.content = '';
					option.isCorrectOption = 0;
				});
				//处理教材和命题教师
				$scope.model.book = {
						id: $scope.model.bookId
				};
				$scope.model.teacher = {
						name: $scope.model.setTeacherName
				};
				//更新questionNo
				for(var i=0; i<$scope.courses.length; i++){
					var course = $scope.courses[i];
					if(course.id == $scope.model.courseId){
						$http.post('question/getNewQuestionNo/' + course.code).success(function(data){
							course.questionNo = data.questionNo;
							$scope.model.questionNo = course.questionNo;
						}).error(function(data, code){alert('error');});
						break;
					}
				}
			}else{
				toaster.pop('error', data.msg);
				//处理教材和命题教师
				$scope.model.book = {
						id: $scope.model.bookId
				};
				$scope.model.teacher = {
						name: $scope.model.setTeacherName
				};
			}
		})
	}
})

.controller('QuestionEditCtrl',function($cookieStore,$scope,$http,appConst,toaster,$stateParams){
	$scope.model = {};
	$scope.months=['',1,4,7,10];
	$scope.load = function(){
		$http.post('question/getById/' + $stateParams.id).success(function(data){
			$scope.model = data;
			if($scope.model.enableTime){
				var enableTime = new Date($scope.model.enableTime);
				$scope.model.enableTimeYear = enableTime.getFullYear();
				$scope.model.enableTimeMonth = enableTime.getMonth()+1;
			}else{
				$scope.model.enableTimeYear = '';
				$scope.model.enableTimeMonth = '';
			}
			
			$http.post('question/loadQuestionTypeByCourseId/' + $scope.model.courseId).success(function(data){
				$scope.questionTypes = data;
			})
			
			$http.post('question/loadTeachersByQuesId/' + $scope.model.id).success(function(data){
				$scope.teachers = data;
				$scope.model.teacher = {
					name:　$scope.model.setTeacherName
				}
			})
			
			var url = $stateParams.auditTask ? 'question/getAuditTaskCourses' : 'question/getInputTaskCourses';
			
			$http.get(url).success(function(data){
				$scope.courses = data.courses;
				$scope.status = data.status;
				$scope.codes = data.codes;
				
				$scope.books = [];
				$scope.bookMap = {};
				//获取所有课程的教材，并放入一个列表中。
				angular.forEach($scope.courses, function(course){
					var books = data.courseBookMap[course.id];
					angular.forEach(books, function(book){
						book.courseId = course.id;
						$scope.books.push(book);
						$scope.bookMap[book.id] = book;
					});
				});
				
				$scope.model.book = {
					id:　$scope.model.bookId
				};
			})
			
			//单项选择题选项处理
			if($scope.model.options && $scope.model.options.length == 4){
				 angular.forEach($scope.model.options, function (option) {
					 	if(option.isCorrectOption == 1){
					 		$scope.model.correctOptionNo = option.optionNo;
					 	}
				    });
			}
			//多项选择题选项处理
			if($scope.model.options && $scope.model.options.length == 5){
				angular.forEach($scope.model.options, function (option) {
					if(option.isCorrectOption == 1){
						option.checked = true;
					}else{
						option.checked = false;
					}
				});
			}
		})
	}
	$scope.load();
	
	$scope.changeQuestionType = function(){
		var selectedQt;
		for(var i=0; i<$scope.questionTypes.length; i++){
			var qt = $scope.questionTypes[i];
			if(qt.id == $scope.model.typeId){
				selectedQt = qt;
				break;
			}
		}
		switch(qt.correctOptionsNum){
		case 0:
			$scope.model.options = null;
			$scope.model.answer = '';
			break;
		case 1:
			$scope.model.options = [{'optionNo': 0, 'isCorrectOption': 0}
			,{'optionNo': 1, 'isCorrectOption': 0}
			,{'optionNo': 2, 'isCorrectOption': 0}
			,{'optionNo': 3, 'isCorrectOption': 0}
			];
			delete $scope.model.answer;
			break;
		case 2:
			$scope.model.options = [{'optionNo': 0, 'isCorrectOption': 0}
			,{'optionNo': 1, 'isCorrectOption': 0}
			,{'optionNo': 2, 'isCorrectOption': 0}
			,{'optionNo': 3, 'isCorrectOption': 0}
			,{'optionNo': 4, 'isCorrectOption': 0}
			];
			delete $scope.model.answer;
			break;
		default:
			break;
		}
	}
	
	function _validateForm(){
		var invalid = false;
		
		//校验题干不能为空
		if($scope.model.body == null || $scope.model.body.length == 0){
			toaster.pop('error', '题干不能为空！');
			invalid = true;
		}
		//校验选项内容不为空
		angular.forEach($scope.model.options, function (option) {
			if(option.content == null || option.content.length == 0){
				toaster.pop('error', '选项不能为空！');
				invalid = true;
			}
		});
		
		//校验答案与解析内容不为空
		if($scope.model.options == null || $scope.model.options.length == 0){
			if($scope.model.answer == null || $scope.model.answer.length == 0){
				toaster.pop('error', '答案与解析不能为空！');
				invalid = true;
			}
		}
		
		//单项选择题选项校验
		if($scope.model.options && $scope.model.options.length == 4){
			if($scope.model.correctOptionNo == null){
				toaster.pop('error', '请选择一个正确答案！');
				invalid = true;
			}
		}
		//多项选择题选项校验
		var correctOptionCount = 0;
		if($scope.model.options && $scope.model.options.length == 5){
			angular.forEach($scope.model.options, function (option) {
				if(option.checked){
					correctOptionCount++;
				}
			});
			if(correctOptionCount < 1 ){
				toaster.pop('error', '请选择正确答案！');
				invalid = true;
			}
		}
		//选项内容重复校验
		var duplicate = false;
		if($scope.model.options && $scope.model.options.length > 0){
			angular.forEach($scope.model.options, function(option1){
				angular.forEach($scope.model.options, function(option2){
					if(option1.optionNo != option2.optionNo && option1.content == option2.content){
						duplicate = true;
					}
				})
			})
		}
		if(duplicate){
			toaster.pop('error', '有重复选项！');
			invalid = true;
		}
		
		return invalid;
	}
	
	$scope.submit = function(){
		if(_validateForm()){
			return;
		}
		
		var curBook = $scope.bookMap[$scope.model.book.id];
		if(curBook.enableDate && $scope.model.setTime){
			var setTime = new Date($scope.model.setTime);
			var bookEnableDate = new Date(curBook.enableDate);
			bookEnableDate.setHours(0);
			bookEnableDate.setMinutes(0);
			bookEnableDate.setSeconds(0);
			if(bookEnableDate.getTime() > setTime.getTime()){
				toaster.pop('error', "命题时间不能小于教材启用时间[" + bookEnableDate.getFullYear() + "-" + (bookEnableDate.getMonth() + 1) + "]");
				$scope.submitted = true;
				return false;
			}
		}else if(!curBook.enableDate){
			toaster.pop('error', "当前选中的教材没有配置教材启用时间，请与业务管理员联系。");
			$scope.submitted = true;
			return false;
		}
		
		var enableTimeYear = $scope.model.enableTimeYear;
		var enableTimeMonth = $scope.model.enableTimeMonth;
		if(enableTimeYear != '' && (typeof(enableTimeMonth) == "undefined" || enableTimeMonth == '')){
			toaster.pop('error', "请选择月份");
			$scope.submitted = true;
			return false;
		}
		if((typeof(enableTimeYear) == "undefined" || enableTimeYear == '') && enableTimeMonth != ''){
			toaster.pop('error', "请输入年份");
			$scope.submitted = true;
			return false;
		}
		var enableTime = '';
		if(enableTimeYear != ''){
			enableTime = new Date();
			enableTime.setFullYear(enableTimeYear);
			enableTime.setMonth(enableTimeMonth - 1);
			enableTime.setDate(1);
			enableTime.setHours(0);
			enableTime.setMinutes(0);
			enableTime.setSeconds(0);
			enableTime.setMilliseconds(0);
			if($scope.model.setTime){
				var setTime = new Date($scope.model.setTime);
				setTime.setHours(0);
				setTime.setMinutes(0);
				setTime.setSeconds(0);
				if(setTime.getTime() > enableTime.getTime()){
					toaster.pop('error', "命题时间不能大于试题启用时间，请重新填写。");
					$scope.submitted = true;
					return false;
				}
			}
			if(curBook.enableDate){
				var bookEnableDate = new Date(curBook.enableDate);
				bookEnableDate.setHours(0);
				bookEnableDate.setMinutes(0);
				bookEnableDate.setSeconds(0);
				if(bookEnableDate.getTime() > enableTime.getTime()){
					toaster.pop('error', "试题启用时间不能小于教材启用时间[" + bookEnableDate.getFullYear() + "-" + (bookEnableDate.getMonth() + 1) + "]");
					$scope.submitted = true;
					return false;
				}
			}
		}
		
		if($scope.form.$invalid){
			toaster.pop('error', "校验失败，请检查表单中红框部分的内容！");
			$scope.submitted = true;
			return;
		}
		
		//单项选择题选项处理
		if($scope.model.options && $scope.model.options.length == 4){
			angular.forEach($scope.model.options, function (option) {
				if(option.optionNo == $scope.model.correctOptionNo){
					option.isCorrectOption = 1;
				}else{
					option.isCorrectOption = 0;
				}
			});
		}
		delete $scope.model.correctOptionNo;
		
		//多项选择题选项处理
		if($scope.model.options && $scope.model.options.length == 5){
			angular.forEach($scope.model.options, function (option) {
				if(option.checked){
					option.isCorrectOption = 1;
				}else{
					option.isCorrectOption = 0;
				}
				delete option.checked;
			});
		}
		
		//教材处理
		$scope.model.bookId = $scope.model.book.id;
		delete $scope.model.book;
		//命题教师处理
		$scope.model.setTeacherName = $scope.model.teacher.name;
		delete $scope.model.teacher;
		
		$scope.model.enableTime = enableTime;
		delete $scope.model.enableTimeYear;
		delete $scope.model.enableTimeMonth;
		$scope.loading = $http.post('question/saveQues', $scope.model).success(function(data){
			$scope.loadingMsg = '正在保存试题，请稍等...';
			if(data.question){
				toaster.pop('success', '保存成功!');
			}else{
				toaster.pop('error', data.msg);
			}
			
			if($scope.model.enableTime){
				var enableTime = new Date($scope.model.enableTime);
				$scope.model.enableTimeYear = enableTime.getFullYear();
				$scope.model.enableTimeMonth = enableTime.getMonth()+1;
			}else{
				$scope.model.enableTimeYear = '';
				$scope.model.enableTimeMonth = '';
			}
			
			//处理教材和命题教师
			$scope.model.book = {
					id: $scope.model.bookId
			};
			$scope.model.teacher = {
					name: $scope.model.setTeacherName
			};
			
			//单项选择题选项处理
			if($scope.model.options && $scope.model.options.length == 4){
				 angular.forEach($scope.model.options, function (option) {
					 	if(option.isCorrectOption == 1){
					 		$scope.model.correctOptionNo = option.optionNo;
					 	}
				    });
			}
			
			//多项选择题选项处理
			if($scope.model.options && $scope.model.options.length == 5){
				angular.forEach($scope.model.options, function (option) {
					if(option.isCorrectOption == 1){
						option.checked = true;
					}else{
						option.checked = false;
					}
				});
			}
		})
	}
})

/** 录入试题任务 - 获取相关课程等信息 **/
.controller('ToInputQuesTopCtrl',function($cookieStore,$scope,$http,appConst){
	/**
	$scope.load = function(){
		if(!$scope.courses){
			$http.get('question/getInputTaskCourses').success(function(data){
				$scope.courses = data.courses;
				$scope.status = data.status;
				$scope.codes = data.codes;
				
				$scope.books = [];
				//获取所有课程的教材，并放入一个列表中。
				angular.forEach($scope.courses, function(course){
					var books = data.courseBookMap[course.id];
					angular.forEach(books, function(book){
						book.courseId = course.id;
						$scope.books.push(book);
					});
				});
			})
			.error(function(data, code){alert(code);});
		}
	};
	$scope.load();
	**/
})
/** 录入试题任务 - 查看录入试题列表 **/
.controller('ToInputQuesListCtrl',function($cookieStore,$scope,$http,appConst,$sce,$state,toaster,$modal,$stateParams){
	//分页相关
	$scope.pageModel = {};
	$scope.pageModel.pageSize = 3;
	$scope.search = {
			'rows': $scope.pageModel.pageSize
	};
	
	$scope.load = function(){
		$http.get('question/getInputTaskCourses').success(function(data){
			$scope.courses = data.courses;
			$scope.status = data.status;
			$scope.codes = data.codes;
			$scope.appPath = data.appPath;
		})
		.error(function(data, code){alert(code);});
		
		_goPage(1);
		
		$http.post('user/queryCurUser').success(function(data){
			$scope.curUser = data;
		});
	};
	$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;
		$scope.search.page = pageNum;
		
		var url = 'question/search';
		
		$http.post(url, $scope.search).success(function(data){
			$scope.pageModel.array = data.rows;
			$scope.pageModel.total = data.total;
			$scope.pageModel.totalPage = Math.ceil(data.total / $scope.pageModel.pageSize);
			
			angular.forEach($scope.pageModel.array, function (question) {
				question.body = $sce.trustAsHtml(question.body);
				question.answer = $sce.trustAsHtml(question.answer);
				
				angular.forEach(question.options, function (option) {
					option.content = $sce.trustAsHtml(option.content);
			    });
		    });
		})
		.error(function(data, code){alert(code);});
	}
	
	$scope.changeCourse = function(){
		$http.post('question/loadQuestionTypeByCourseId/' + $scope.search.courseId).success(function(data){
			$scope.questionTypes = data;
		})
		
		$http.post('question/loadBooksByCourseId/' + $scope.search.courseId).success(function(data){
			$scope.books = data;
		})
	}
	
	$scope.openClientForAdd = function(courseId){
		if(courseId == null){
			toaster.pop('error', '必须选择一门课程才能启动录题客户端!');
			return;
		}
		var hostAddress = encodeURIComponent(location.protocol + "//" + location.host + $scope.appPath + "/");
		var url = 'proposition://Proposition/parm=' + hostAddress + 'parm=' + encodeURIComponent('client/getCourseInfo/' + courseId)
		+ 'parm=tikaparm=0parm=' + $scope.curUser.id;
		
		console.log('---- url ： ' + url);
		$scope.iframeUrl = $sce.trustAsResourceUrl(url);
	}
	
	/*
	 * 启动录题客户端
	 * */
	$scope.openClientForEdit = function(quesId){
		$http.post('question/isUsedByPaper?quesId='+quesId).success(function(res){
			if(res.used == true){
				res.used = 1;
			}else{
				res.used = 0;
			}
			var hostAddress = encodeURIComponent(location.protocol + "//" + location.host + $scope.appPath + "/");
			var url = 'proposition://Proposition/parm=' + hostAddress + 'parm=' + encodeURIComponent('client/getQuestionInfo/' + quesId)
	          + 'parm=tikaparm=' + res.used + 'parm=' + $scope.curUser.id;
			$scope.iframeUrl = $sce.trustAsResourceUrl(url);
		})
		
	}
	
	$scope.edit = function(id){
		var url = $state.href('toInput.edit', {'id':id});
		window.open(url,'toInput_edit_' + id);
	}
})

/** 审核试题列表 **/
.controller('AuditQuesListCtrl',function($cookieStore,$scope,$http,appConst,$sce,$state,toaster,$modal,$stateParams){
	//分页相关
	$scope.pageModel = {};
	$scope.pageModel.pageSize = 3;
	$scope.search = {
			'rows': $scope.pageModel.pageSize
	};
	
	$scope.load = function(){
		$scope.auditTask = true;
		
		$http.get('question/getAuditTaskCourses').success(function(data){
			$scope.courses = data.courses;
			$scope.status = data.status;
			$scope.codes = data.codes;
			$scope.appPath = data.appPath;
		})
		.error(function(data, code){alert(code);});
		
		_goPage(1);
		
		$http.post('user/queryCurUser').success(function(data){
			$scope.curUser = data;
		});
	};
	$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;
		$scope.search.page = pageNum;
		
		var url = 'question/searchAudit';
		
		$http.post(url, $scope.search).success(function(data){
			$scope.pageModel.array = data.rows;
			$scope.pageModel.total = data.total;
			$scope.pageModel.totalPage = Math.ceil(data.total / $scope.pageModel.pageSize);
			
			angular.forEach($scope.pageModel.array, function (question) {
				question.body = $sce.trustAsHtml(question.body);
				question.answer = $sce.trustAsHtml(question.answer);
				
				angular.forEach(question.options, function (option) {
					option.content = $sce.trustAsHtml(option.content);
			    });
		    });
		})
		.error(function(data, code){alert(code);});
	}
	
	$scope.changeCourse = function(){
		$http.post('question/loadQuestionTypeByCourseId/' + $scope.search.courseId).success(function(data){
			$scope.questionTypes = data;
		})
		
		$http.post('question/loadBooksByCourseId/' + $scope.search.courseId).success(function(data){
			$scope.books = data;
		})
	}
	
	/** 审核结果 **/
	var workflowAuditModal = $modal({title:'提交审核结果',scope: $scope, templateUrl: 'resources/app/question/audit.html', show: false});
	$scope.showWorkflowAuditModal = function(quesId) {
		$scope.quesId = quesId;
		$scope.workflow  = {
				remark:null,
				auditResult:'QUESTION_APPROVED'
			};
		workflowAuditModal.$promise.then(workflowAuditModal.show);
	};
	$scope.workflowAudit = function(){
		var params = "quesId=" + $scope.quesId
					+ "&auditResult=" + $scope.workflow.auditResult 
					+ "&remark=" + $scope.workflow.remark;
		$http.post('question/saveAudit?' + params).success(function(data){
			if(data.flag=="success"){
				toaster.pop('success','更新成功！');
				workflowAuditModal.hide();
				_goPage(1);
			}
			else{
				toaster.pop('error', data.msg);
			}
		});
	};
	
	/** 按课程统计审核进度 **/
	var auditStatsModal = $modal({title:'审核进度',scope: $scope, templateUrl: 'resources/app/question/auditStatsByCourse.html', show: false});
	$scope.showAuditStatsModal = function() {
		auditStatsModal.$promise.then(auditStatsModal.show);
	};
	
	/** 试题审核日志 **/
	var auditLogModal = $modal({title:'审核日志',scope: $scope, templateUrl: 'resources/app/question/auditLogByQues.html', show: false});
	$scope.showAuditLogModal = function(quesId) {
		$scope.quesId = quesId;
		auditLogModal.$promise.then(auditLogModal.show);
	};	
	
	/*
	 * 启动录题客户端
	 * */
	$scope.openClientForEdit = function(quesId){
		$http.post('question/isUsedByPaper?quesId='+quesId).success(function(res){
			if(res.used == true){
				res.used = 1;
			}else{
				res.used = 0;
			}
			var hostAddress = encodeURIComponent(location.protocol + "//" + location.host + $scope.appPath + "/");
			var url = 'proposition://Proposition/parm=' + hostAddress + 'parm=' + encodeURIComponent('client/getQuestionInfo/' + quesId)
	          + 'parm=tikaparm=' + res.used + 'parm=' + $scope.curUser.id;
			$scope.iframeUrl = $sce.trustAsResourceUrl(url);
		})
		
	}
	
	$scope.edit = function(id){
		var url = $state.href('toInput.edit', {'id':id, 'auditTask': $scope.auditTask});
		window.open(url,'_blank');
	}
})

/** 课程审核进度 **/
.controller('AuditStatsByCourseCtrl',function($cookieStore,$scope,$http,$state,toaster,$modal,$stateParams){
	$scope.load = function(){
		if($scope.search.courseId){
			$http.post('question/statAuditorJob?courseId=' + $scope.search.courseId).success(function(data){
				$scope.draftNum = data.draftNum;
				$scope.auditorJob = data.auditorJob;
			}).error(function(data, code){alert(code);});
		}else{
			toaster.pop('warning', '请先选择课程！');
		}
	}
	$scope.load();
})

/** 试题审核日志 **/
.controller('AuditLogByQuesCtrl',function($cookieStore,$scope,$http,$state,toaster,$modal,$stateParams){
	$scope.load = function(){
		if($scope.quesId){
			$http.post('question/getAuditLogs?quesId=' + $scope.quesId).success(function(data){
				$scope.auditLogs = data.auditLogs;
			}).error(function(data, code){alert(code);});
		}else{
			toaster.pop('warning', '请先选择试题！');
		}
	}
	$scope.load();
})
