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

.controller('CourseListCtrl',function($cookieStore,$scope,$http,appConst,$state,toaster,$modal){
	
	$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 = '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);
		})
		.error(function(data, code){alert(code);});
	}
	
	$scope.deleteCourse = function(id){
		
		$http.post('course/delete/' + id)
		.success(function(data){
		if(data.flag == 'failed'){
		toaster.pop('error', '此课程已经被关联,不允许删除！');
		}else{
			toaster.pop('success', '删除成功!');
			$scope.load();
			}
		}).error(function(data,code){
			alert(code);
		});
	}
	
	var editModal = $modal({title:'编辑课程',scope: $scope, templateUrl: 'resources/app/course/edit.html', show: false});
	$scope.edit = function(id){
		//$state.go('course.edit', {'id':id});
		$scope.selectedCourseId = id;
		$scope.editModal = editModal;
		editModal.$promise.then(editModal.show);
	}
	
	var relatedBooksModal = $modal({title:'关联教材',scope: $scope, templateUrl: 'resources/app/course/relatedBooks.html', show: false});
	$scope.relatedBooks = function(id){
		//$state.go('course.relatedBooks', {'id':id});
		$scope.selectedCourseId = id;
		relatedBooksModal.$promise.then(relatedBooksModal.show);
	}
	
	var editBookModal = $modal({title:'编辑教材',scope: $scope, templateUrl: 'resources/app/book/edit.html', show: false});
	$scope.editBook = function(id){
		$http.post('course/selectedBooks/'+id).success(function(data){
			if(data && data.length > 0){
				var openWin = false;
				for(var i=0;i<data.length;i++){
					if(data[i].inCourseStatus == 1){
						$scope.selectedBookId = data[i].id;
						$scope.isEditInCourse = true;
						$scope.editBookModal = editBookModal;
						editBookModal.$promise.then(editBookModal.show);
						openWin = true;
						break;
					}
				}
				if(!openWin){
					toaster.pop('warn', '当前关联教程中设置启用的教程，请先设置启用教材。');
				}
			}else{
				toaster.pop('warn', '当前没有关联的教材，请先关联教材。');
			}
		})
	}
	
	var relatedQuestionTypesModal = $modal({title:'关联题型',scope: $scope, templateUrl: 'resources/app/course/relatedQuestionTypes.html', show: false});
	$scope.relatedQuestionTypes = function(id){
		//$state.go('course.relatedQuestionTypes', {'id':id});
		$scope.selectedCourseId = id;
		relatedQuestionTypesModal.$promise.then(relatedQuestionTypesModal.show);
	}
	
	var skelSettingsModal = $modal({title:'细目表配置',scope: $scope, templateUrl: 'resources/app/course/skelSettings.html', show: false});
	
	$scope.showSkelSettingsModal = function(row) {
		$http.post('paperSkeleton/getSkelCfgInfo/' + row.id).success(function(data){
			if(data.skelCfg){
				$scope.skelSettings = data.skelCfg; 
				skelSettingsModal.$promise.then(skelSettingsModal.show);
			}else{
				toaster.pop('error', data.msg);
			}
		})
	};
	$scope.resetSkelSettings = function(){
		var settings = $scope.skelSettings;
		settings.ability1Percent = 20;
		settings.ability2Percent = 30;
		settings.ability3Percent = 30;
		settings.ability4Percent = 20;
		settings.abilityOffset = 3;
		
		settings.estimateDifficulty1Percent = 20;
		settings.estimateDifficulty2Percent = 30;
		settings.estimateDifficulty3Percent = 30;
		settings.estimateDifficulty4Percent = 20;
		settings.estimateDifficultyOffset = 3;
	}
	
	$scope.saveSkelSettings = function(){
		var settings = $scope.skelSettings;
		var abilityTotal = settings.ability1Percent + settings.ability2Percent + settings.ability3Percent + settings.ability4Percent;
		var diffTotal = settings.estimateDifficulty1Percent + settings.estimateDifficulty2Percent + settings.estimateDifficulty3Percent + settings.estimateDifficulty4Percent;
		
		if(abilityTotal != 100){
			toaster.pop('error', '能力要求比例总和应为100！您当前输入的总和为：' +abilityTotal);
		}else if(diffTotal != 100){
			toaster.pop('error', '预计难度比例总和应为100！您当前输入的总和为：' +diffTotal);
		}else{
			$http.post('paperSkeleton/saveSkelCfg', settings).success(function(data){
				if(data.flag == 'failed'){
					toaster.pop('error', data.msg);
				}else{
					toaster.pop('success', '保存成功!');
				}
			})
		}
	};
	
	$scope.$on('courseModified', function (event, course) {
		for(var i=0;i<$scope.pageModel.array.length;i++){
			if($scope.pageModel.array[i].id == course.id){
				$scope.pageModel.array[i] = course;
			}
		}
	});
})

.controller('CourseAddCtrl',function($scope,$http,$state,$stateParams,toaster,$rootScope){
	$scope.load = function(){
		if($scope.selectedCourseId){
			$stateParams.id = $scope.selectedCourseId;
			var url = 'course/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;
		}
		var course = {};
		course.id = $scope.model.id;
		course.code = $scope.model.code;
		course.name = $scope.model.name;
		course.status = $scope.model.status;
		course.openEdit = $scope.model.openEdit;
		
		$scope.myPromise = $http.post('course/save',course)
		.success(function(data){
			if(data.flag == 'failed'){
				toaster.pop('error', data.msg);
			}
			else{
				toaster.pop('success', '操作成功！');
				$rootScope.$broadcast('courseModified', data.course);
				$scope.editModal.hide();
//				$scope.load();
				//$state.go('course.list');
			}
		})
		.error(function(data,code){
			alert(code);
		});
	};
})

.controller('CourseRelatedBooksCtrl', function($scope,$http,$state,$stateParams, toaster){
	$scope.pageModel = {};
	$scope.pageModel.pageSize = 6;
	$scope.relatedBooks = [];
	$scope.search = {};
	
	$scope.load = function(){
		$stateParams.id = $scope.selectedCourseId;
		$http.post('course/selectedBooks/'+$stateParams.id).success(function(data){
			$scope.relatedBooks = data;
		})
		
		var url = 'course/getById/'+ $stateParams.id;
			$http.get(url).success(function(data){
				$scope.course = data;
			})
			.error(function(data, code){alert(code);});
		
		_goPage(1);
	}
	$scope.load();
	
	function _goPage(pageNum){
		if(pageNum < 1 || (pageNum > $scope.pageModel.totalPage && $scope.pageModel.totalPage > 0)){
			return;
		}
		
		$scope.pageModel.curPage = pageNum;
		
		var url = 'book/queryBooks';
		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.goPage = function(pageNum){
		_goPage(pageNum);
	}
	
	$scope.addRelatedBook = function(row){
		var exists = false;
		for(var i=0; i < $scope.relatedBooks.length; i++){
			var book = $scope.relatedBooks[i];
			book.inCourseStatus = 0;
			if(book.id == row.id){
				exists = true;
				book.inCourseStatus = 1;
			}
		}
		if(!exists){
			row.inCourseStatus = 1;
			$scope.relatedBooks.push(row);
			$scope.submit();
		}else{
			toaster.pop('warning', '教材已关联！');
		}
	}
	
	$scope.deleteRelatedBook = function(row){
		var i=0; 
		for(;i < $scope.relatedBooks.length; i++){
			var book = $scope.relatedBooks[i];
			var bookStatus = $scope.relatedBooks[i - 1];
			if(book.id == row.id){
				bookStatus.inCourseStatus = 1;
				break;
			}
		}
		$scope.relatedBooks.splice(i,1);
		$scope.submit();
	}
	
	$scope.enableRelatedBook = function(row){
		for(var i=0; i < $scope.relatedBooks.length; i++){
			var book = $scope.relatedBooks[i];
			if(book.id == row.id){
				book.inCourseStatus = 1;
			}else{
				book.inCourseStatus = 0;
			}
		}
		$scope.submit();
	}
	
	$scope.search = function(){
		_goPage(1);
	}
	
	$scope.submit = function(){
		var params = {};
		var relatedBooks = [];
		for(var i = 0; i < $scope.relatedBooks.length; i++){
			relatedBooks.push($scope.relatedBooks[i].id + '@' + $scope.relatedBooks[i].inCourseStatus);
		}
		$scope.myPromise = $http.post('course/saveLinkBooks/' + $stateParams.id, relatedBooks)
		.success(function(data){
			if(data.flag == 'success'){
				toaster.pop('success', '操作成功！');
			}else{
				toaster.pop('error', '操作失败！');
			}
		})
		.error(function(data,code){
			alert(code);
		});
	};
})

.controller('CourseRelatedQuestionTypeCtrl', function($scope,$http,$state,$stateParams, toaster){
	$scope.pageModel = {};
	$scope.pageModel.pageSize = 6;
	$scope.relatedQuestionTypes = [];
	$scope.search = {};
	
	$scope.load = function(){
		$stateParams.id = $scope.selectedCourseId;
		$http.post('course/selectedQuestionTypes/'+$stateParams.id).success(function(data){
			$scope.relatedQuestionTypes = data;
		})
		
		var url = 'course/getById/'+ $stateParams.id;
			$http.get(url).success(function(data){
				$scope.course = data;
			})
			.error(function(data, code){alert(code);});
		
		_goPage(1);
	}
	$scope.load();
	
	function _goPage(pageNum){
		if(pageNum < 1 || (pageNum > $scope.pageModel.totalPage && $scope.pageModel.totalPage > 0)){
			return;
		}
		
		$scope.pageModel.curPage = pageNum;
		
		var url = 'questionType/queryQuestionTypes';
		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.goPage = function(pageNum){
		_goPage(pageNum);
	}
	
	$scope.questionTypeUp = function(index){
		var curQT = $scope.relatedQuestionTypes[index];
		$scope.relatedQuestionTypes[index] = $scope.relatedQuestionTypes[index-1];
		$scope.relatedQuestionTypes[index-1] = curQT;
		$scope.submit();
	}
	$scope.questionTypeDown = function(index){
		var curQT = $scope.relatedQuestionTypes[index];
		$scope.relatedQuestionTypes[index] = $scope.relatedQuestionTypes[index+1];
		$scope.relatedQuestionTypes[index+1] = curQT;
		$scope.submit();
	}
	$scope.addRelatedQuestionType = function(row){
		var exists = false;
		for(var i=0; i < $scope.relatedQuestionTypes.length; i++){
			var questionType = $scope.relatedQuestionTypes[i];
			if(questionType.id == row.id){
				exists = true;
			}
		}
		if(!exists){
			$scope.relatedQuestionTypes.push(row);
			$scope.submit();
		}else{
			toaster.pop('warning', '题型已关联!');
		}
	}
	
	$scope.deleteRelatedQuestionType = function(row){
		var i=0; 
		for(;i < $scope.relatedQuestionTypes.length; i++){
			var questionType = $scope.relatedQuestionTypes[i];
			if(questionType.id == row.id){
				break;
			}
		}
		$scope.relatedQuestionTypes.splice(i,1);
		$scope.submit();
	}
	
	$scope.search = function(){
		_goPage(1);
	}
	
	$scope.submit = function(){
		var params = {};
		var relatedQuestionTypes = [];
		for(var i = 0; i < $scope.relatedQuestionTypes.length; i++){
			relatedQuestionTypes.push($scope.relatedQuestionTypes[i].id);
		}
		$scope.myPromise = $http.post('questionType/saveLinkQuestionType/' + $stateParams.id, relatedQuestionTypes)
		.success(function(data){
			if(data.flag == 'success'){
				toaster.pop('success', '操作成功！');
			}else{
				toaster.pop('error', '操作失败！');
			}
		})
		.error(function(data,code){
			alert(code);
		});
	};
})


.controller('CourseImportCtrl',function($cookieStore, $scope, $http, FileUploader, $q,$stateParams,toaster,$state,$modal){
	var uploader = $scope.uploader = new FileUploader({
        url: 'course/importCourse'
    });
	$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'){
    		$modal({title:'导入失败',type:'error', content:response.msg,html:true, show: true,placement:'center'});
    	}else if(response.result == 'success'){
    		toaster.pop('success', '上传成功 ' +response.successNum+ ' 条用户记录！');
    		$state.go('course.list');
    	}
    };
    
    $scope.files = $scope.uploader.queue;
    $scope.uploader.onCompleteAll = function() {
		$scope.loading = null;
		$scope.uploader.clearQueue();
	}
})

.controller('BookListCtrl',function($cookieStore,$scope,$http,appConst,$state,$location,$modal,toaster,$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 = 'book/queryBooks';
		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.deleteBook = function(id){
		$http.post('book/delete/' + id)
		.success(function(data){
			if(data.flag == 'success'){
				toaster.pop('success', '操作成功！');
				$scope.load();
			}else{
				toaster.pop('error', '该教材被关联，无法删除！');
			}
		})
		.error(function(data,code){
			alert(code);
		});
	}
	
	var editBookModal = $modal({title:'编辑教材',scope: $scope, templateUrl: 'resources/app/book/edit.html', show: false});
	$scope.edit = function(id){
		$scope.selectedBookId = id;
		$scope.isEditInBook = true;
		$scope.editBookModal = editBookModal;
		editBookModal.$promise.then(editBookModal.show);
	}
	
	$scope.$on('bookModified', function (event, book) {
		for(var i=0;i<$scope.pageModel.array.length;i++){
			if($scope.pageModel.array[i].id == book.id){
				$scope.pageModel.array[i] = book;
			}
		}
	});
})

.controller('BookAddCtrl',function($scope,$http,$state,$stateParams,toaster,$rootScope){
	$scope.load = function(){
		if($scope.selectedBookId){
			$stateParams.id = $scope.selectedBookId;
			var url = 'book/queryById/'+ $stateParams.id;
			$http.get(url).success(function(data){
				$scope.model = data;
				if($scope.model.enableDate){
					var enableDate = new Date($scope.model.enableDate);
					$scope.model.enableDateYear = enableDate.getFullYear();
					$scope.model.enableDateMonth = enableDate.getMonth()+1;
				}
			})
			.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;
		}
		var enableDateYear = $scope.model.enableDateYear;
		var enableDateMonth = $scope.model.enableDateMonth;
		var enableDate = new Date();
		enableDate.setFullYear(enableDateYear);
		enableDate.setMonth(enableDateMonth - 1);
		enableDate.setDate(1);
		enableDate.setHours(0);
		enableDate.setMinutes(0);
		enableDate.setSeconds(0);
		var book = {};
		book.id = $scope.model.id;
		book.code = $scope.model.code;
		book.name = $scope.model.name;
		book.editor = $scope.model.editor;
		book.press = $scope.model.press;
		book.version = $scope.model.version;
		book.chapterSize = $scope.model.chapterSize;
		book.status = $scope.model.status;
		book.enableDate = enableDate;
		
		$scope.myPromise = $http.post('book/save',book)
		.success(function(data){
			if(data.flag == 'failed'){
				toaster.pop('error', data.msg);
			}
			else{
				toaster.pop('success', '操作成功！');
				if($scope.isEditInCourse){
					$scope.editBookModal.hide();
				}else if($scope.isEditInBook){
					$rootScope.$broadcast('bookModified', data.book);
					$scope.editBookModal.hide();
				}else{
					$state.go('book.list');
				}
			}
		})
		.error(function(data,code){
			alert(code);
		});
	};
})

.controller('QuestionTypeListCtrl',function($cookieStore,$scope,$http,appConst,$state,toaster,$modal){
	
	$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 = 'questionType/queryQuestionTypes';
		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.deleteQuestionType = function(id){
		$http.post('questionType/delete/' + id)
		.success(function(data){
			if(data.flag == 'success'){
				toaster.pop('success', '操作成功！');
				$scope.load();
			}else{
				toaster.pop('error', '该题型被关联，无法删除！');
			}
		})
		.error(function(data,code){
			alert(code);
		});
	}
	
	$scope.edit = function(id){
		$state.go('questionType.edit', {'id':id});
	}
})

.controller('QuestionTypeAddCtrl',function($scope,$http,$state,$stateParams,toaster){
	$scope.load = function(){
		if($stateParams.id != null){
			var url = 'questionType/queryById/'+ $stateParams.id;
			$http.get(url).success(function(data){
				$scope.model = data;
			})
			.error(function(data, code){alert(code);});
		}else{
			$scope.model = {};
			$scope.model.statusCode = 1;
		}
		
	};
	$scope.load();
	
	$scope.submit = function(){
		if($scope.form.$invalid){
			toaster.pop('error', "校验失败，请检查表单中红框部分的内容！");
			$scope.submitted = true;
			return;
		}
		var questionType = {};
		questionType.id = $scope.model.id;
		questionType.code = $scope.model.code;
		questionType.name = $scope.model.name;
		questionType.correctOptionsNum = $scope.model.correctOptionsNum;
		questionType.defaultScore = $scope.model.defaultScore;
		questionType.statusCode = $scope.model.statusCode;
		questionType.remark = $scope.model.remark;
		$scope.myPromise = $http.post('questionType/save',questionType)
		.success(function(data){
			if(data.flag == 'failed'){
				toaster.pop('error', data.msg);
			}
			else{
				toaster.pop('success', '操作成功！');
				$state.go('questionType.list');
			}
		})
		.error(function(data,code){
			alert(code);
		});
	};
	
})
.controller('QuestionTypeImportCtrl',function($cookieStore, $scope, $http, FileUploader, $q,$stateParams,toaster,$state){
	var uploader = $scope.uploader = new FileUploader({
        url: 'questionType/importQuestionType'
    });
	
	$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('questionType.list');
    	}
    };
    
    $scope.files = $scope.uploader.queue;
    
    $scope.uploader.onCompleteAll = function() {
		$scope.loading = null;
		$scope.uploader.clearQueue();
	}
})
.controller('QuestionSimilarCtrl',function($cookieStore,$scope,$http,appConst,$state,toaster,$modal,$sce){
    	
    	$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 = 'question/queryQuestionSimilarity';
    		var params = {'page': pageNum
    				, 'rows': $scope.pageModel.pageSize
    				, 'similarQuestionNo': $scope.search.similarQuestionNo
    				, 'courseNo': $scope.search.courseNo
    				, 'courseName': $scope.search.courseName
    				, 'bookName': $scope.search.bookName
    				, 'typeName': $scope.search.typeName
    				, 'similarityBegin':$scope.search.similarityBegin
    				, 'similarityEnd':$scope.search.similarityEnd};
    		$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.calSimilarity = function(){
    		var url = 'question/checkSimilarity';
    		var params = '';
    		$scope.myPromise = $http.post(url, params).success(function(data){
    			toaster.pop('success','计算成功！');
    			_goPage(1);
    		}).error(function(data, code){alert(code);});
    	}
    	
    	$scope.searchSimilarQuestion = function(){
    		var reg = /^[6-9][0-9]|100/;//相似度填写范围［60，100］
    		var search_similarityBegin = $scope.search.similarityBegin;
    		var search_similarityEnd = $scope.search.similarityEnd;
    		if(search_similarityBegin || search_similarityEnd){
    			if(!reg.test(search_similarityBegin) || !reg.test(search_similarityEnd)){
    				toaster.pop('error','相似度填写范围为［60，100］的正整数！');
    			}else{
    				_goPage(1);
    			}
    		}else{
    			_goPage(1);
    		}
    	}
    	
    	$scope.viewQuestion = function(quesId,courseId){
    		var ques = {courseId:courseId,quesId:quesId};
    		var paramStr = JSON.stringify(ques);
    		//window.open("question/questionForEdit?courseId=" + courseId + "&fun=initEditQuesParam&paramStr=" + encodeURIComponent(paramStr));
    		window.open("question/mng?questionId=" + quesId);
    	}
    	
    	$scope.viewQuestionAll = function(quesIdA,quesIdB,courseId){
    		
    		var urlA = 'question/queryQuestionSimilarityById/'+quesIdA;
    		var urlB = 'question/queryQuestionSimilarityById/'+quesIdB;
    		var params = "";
    		$.ajax({
				   type: "POST",
				   url: urlA,
				   async: false,
				   data: "",
				   success: function(data){
					  $scope.question_a = data.question;
				   }
			});
			$.ajax({
				   type: "POST",
				   url: urlB,
				   async: false,
				   data: "",
				   success: function(data){
					  $scope.question_b = data.question;
				   }
			});
    		var viewQuestionModal = $modal(
    				{title:'试题比对',scope: $scope, templateUrl: 'resources/app/questionsimilarity/view_question.html', show: false,
    					});
    		$scope.viewQuestionModal = viewQuestionModal;
    		viewQuestionModal.$promise.then(viewQuestionModal.show);
    		
        	var diffChars = function(one,other){
        		var diff = JsDiff.diffChars(one, other);
        		var p = document.createElement('p');
        		diff.forEach(function(part){
        		  // green for additions, red for deletions
        		  // grey for common parts
        		  var color = part.added ? 'green' :
        		    part.removed ? 'red' : '';  
        		  var span = document.createElement('span');
        		  span.style.color = color;
        		  span.appendChild(document
        		    .createTextNode(part.value));
        		  p.appendChild(span);
        		});
        		return p.innerHTML;
        	};
        	var qa = angular.fromJson($scope.question_a); 
        	var qb = angular.fromJson($scope.question_b);
    		$scope.question_diff_body_html = $sce.trustAsHtml("<span>结果：</span>"+diffChars(qa.bodySummary,qb.bodySummary));
    		if(qa.options && qb.options){
    			for(var i = 0;i<qa.options.length;i++){
    				//console.log(diffChars(qa.options[i].summary,qb.options[i].summary));
    				$scope['question_diff_option_html_'+i] = $sce.trustAsHtml("<span>"+$scope.getOptionNo(qb.options[i].optionNo)+"、</span>"+diffChars(qa.options[i].summary,qb.options[i].summary));
        	    }
    		}
    		//console.log($scope);
    	}
    	
    	$scope.getHtml = function(sKey) {
    		return $scope['question_diff_option_html_' + sKey];
    	};
    	
    	$scope.getOptionNo = function(optionNo){
    		return String.fromCharCode(parseInt(65)+parseInt(optionNo));
    	};
    	
})
.controller('PaperSimilarCtrl',function($cookieStore,$scope,$http,appConst,$state,toaster,$modal){
    	
    	$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 = 'zujuan/queryPaperSimilarity';
    		var params = {'page': pageNum
    				, 'rows': $scope.pageModel.pageSize
    				, 'similarPaperNo': $scope.search.similarPaperNo
    				, 'courseNo': $scope.search.courseNo
    				, 'courseName': $scope.search.courseName
    				, 'bookName': $scope.search.bookName
    				, 'createdByName': $scope.search.createdByName
    				, 'similarityBegin':$scope.search.similarityBegin
    				, 'similarityEnd':$scope.search.similarityEnd};
    		$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);
    			//console.log(data.total);
    		})
    		.error(function(data, code){alert(code);});
    	}
    	
    	$scope.calSimilarity = function(){
    		var url = 'zujuan/checkPaperSimilarity';
    		var params = '';
    		$scope.myPromise = $http.post(url, params).success(function(data){
    			toaster.pop('success','计算成功！');
    			_goPage(1);
    		}).error(function(data, code){alert(code);});
    	}
    	
    	$scope.searchSimilarPaper = function(){
    		var reg = /^\d{1,2}|100/;//相似度填写范围［0，100］
    		var search_similarityBegin = $scope.search.similarityBegin;
    		var search_similarityEnd = $scope.search.similarityEnd;
    		if(search_similarityBegin || search_similarityEnd){
    			if(!reg.test(search_similarityBegin) || !reg.test(search_similarityEnd)){
    				toaster.pop('error','相似度填写范围为［0，100］的正整数！');
    			}else{
    				_goPage(1);
    			}
    		}else{
    			_goPage(1);
    		}
    	}
    	
    	$scope.viewPaper = function(taskId,taskNo,num){
    		window.open("zujuan/manualAdd?taskId=" + taskId.split(",")[num],
					"paper_win_" + taskNo.split(",")[num]);
    	}
    	
    	$scope.viewPaperAll = function(similarPaperNo,taskId,taskNo){
    		$state.go('papersimilarity.paperquestion',{similarPaperNo:similarPaperNo,taskId:taskId,taskNo:taskNo});
    		//console.log(similarPaperNo);
    		
    	}
})
.controller('PaperQuestionSimilarCtrl',function($cookieStore,$scope,$http,appConst,$state,toaster,$modal,$stateParams,$sce){
    	
    	$scope.load = function(similarPaperNo){
    		$scope.paperNoA = similarPaperNo.split(",")[0];
    		$scope.paperNoB = similarPaperNo.split(",")[1];
    		var urlA = 'zujuan/queryPaperQuestionSimilarity/'+similarPaperNo+'/A';
    		var urlB = 'zujuan/queryPaperQuestionSimilarity/'+similarPaperNo+'/B';
    		$.ajax({
				   type: "POST",
				   url: urlA,
				   async: false,
				   data: "",
				   success: function(data){
					  $scope.question_a = data.paperquestion;
				   }
			});
			$.ajax({
				   type: "POST",
				   url: urlB,
				   async: false,
				   data: "",
				   success: function(data){
					  $scope.question_b = data.paperquestion;
				   }
			});
//    		console.log($scope.paperNoA);
//    		console.log($scope.paperNoB);
//    		console.log($scope.question_a);
    		
        	var diffChars = function(one,other){
        		var diff = JsDiff.diffChars(one, other);
        		var p = document.createElement('p');
        		diff.forEach(function(part){
        		  // green for additions, red for deletions
        		  // grey for common parts
        		  var color = part.added ? 'green' :
        		    part.removed ? 'red' : '';  
        		  var span = document.createElement('span');
        		  span.style.color = color;
        		  span.appendChild(document
        		    .createTextNode(part.value));
        		  p.appendChild(span);
        		});
        		return p.innerHTML;
        	};
        	var qa = angular.fromJson($scope.question_a);
        	var qb = angular.fromJson($scope.question_b);
        	if(qa && qb){
        		for(var i = 0;i<qa.length;i++){
	        		$scope['question_diff_body_html_'+i] = $sce.trustAsHtml("<span>结果：</span>"+diffChars(qa[i].bodySummary,qb[i].bodySummary));
	        		if(qa.options && qb.options){
	        			for(var j = 0;j<qa.options.length;j++){
	        				//console.log(diffChars(qa[i].options[j].summary,qb[i].options[j].summary));
	        				$scope['question_diff_option_html_'+i+'_'+j] = $sce.trustAsHtml("<span>"+$scope.getOptionNo(qb[i].options[j].optionNo)+"、</span>"+diffChars(qa[i].options[j].summary,qb[i].options[j].summary));
	            	    }
	        		}
        		}
        	}
    	}
    	$scope.load($stateParams.similarPaperNo);
    	
    	$scope.viewPaper = function(num){
    		var taskId = $stateParams.taskId;
    	    var taskNo = $stateParams.taskNo;
    		window.open("zujuan/manualAdd?taskId=" + taskId.split(",")[num],
					"paper_win_" + taskNo.split(",")[num]);
    	}
    	
    	$scope.getOptionHtml = function(bodyindex,optionindex) {
    		//console.log('question_diff_option_html_' + bodyindex+"_"+optionindex);
    		return $scope['question_diff_option_html_' + bodyindex+'_'+optionindex];
    	};
    	
    	$scope.getBodyHtml = function(sKey) {
    		//console.log('question_diff_body_html_' + sKey);
    		return $scope['question_diff_body_html_' + sKey];
    	};
    	
    	$scope.getOptionNo = function(optionNo){
    		return String.fromCharCode(parseInt(65)+parseInt(optionNo));
    	};
})
.controller('BackupAndRestoreCtrl',function($cookieStore,$scope,$http,appConst,$state,toaster,$modal){
    	
    	$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 = 'attachment/backuplist';
    		var params = {'page': pageNum
    				, 'rows': $scope.pageModel.pageSize
    				, 'originalName': $scope.search.originalName};
    		$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.backup = function(){
    		var url = 'attachment/backup';
    		var params = '';
    		$scope.myPromise = $http.post(url, params).success(function(data){
    			toaster.pop('success','备份成功！');
    			_goPage(1);
    		}).error(function(data, code){alert(code);});
    	};
    	
    	$scope.restore = function(originalName){
    		var url = 'attachment/restore/'+originalName;
    		var params = '';
    		$scope.myPromise = $http.post(url, params).success(function(data){
    			toaster.pop('success','还原成功！');
    			_goPage(1);
    		}).error(function(data, code){alert(code);});
    	};
})
