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

/** 用户管理 **/
.controller('UserListCtrl',function($cookieStore,$scope,$http,appConst,$state,toaster,$stateParams,userType,$modal,FileUploader,$q){
	
	$scope.pageModel = {};
	$scope.pageModel.pageSize = 10;
	$scope.search = {};
	$scope.load = function(){
		_goPage(1);
		$scope.userType = $stateParams.userType;
		$scope.showFullInfo = ($scope.userType == userType.teacher || !$stateParams.userType);
		$scope.showMajor = ($scope.userType == userType.secretary || !$stateParams.userType);
		$scope.userTypes = userType;
	};
	$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 = 'user/queryUsers';
		var params = {'page': pageNum
						, 'rows': $scope.pageModel.pageSize
						, 'keyword': $scope.search.keyword};
		if($stateParams.userType){
			params.userType = $stateParams.userType;
		}
		$http.post(url, params).success(function(data){
			$scope.pageModel.array = data.rows;
			$scope.pageModel.total = data.total;
			$scope.pageModel.totalPage = Math.ceil(data.total / $scope.pageModel.pageSize);
		})
		.error(function(data, code){alert(code);});
	}
	
	$scope.edit = function(id){
		if($stateParams.userType == userType.teacher){
			$state.go('userMng.teachersEdit', {'id':id});
		}else if($stateParams.userType == userType.secretary){
			$state.go('userMng.secretaryEdit', {'id':id});
		}else if($stateParams.userType == userType.inputer){
			$state.go('userMng.inputersEdit', {'id':id});
		}else{
			$state.go('users.edit', {'id':id});
		}
	}
	
	$scope.add = function(){
		if($stateParams.userType == userType.teacher){
			$state.go('userMng.teachersAdd');
		}else if($stateParams.userType == userType.secretary){
			$state.go('userMng.secretaryAdd');
		}else if($stateParams.userType == userType.inputer){
			$state.go('userMng.inputersAdd');
		}else{
			$state.go('users.add');
		}
	};
	
	$scope.resetPassword = function(id){
		var params = {id: id};
		$http.post('user/resetPwd', params).success(function(data){
			if(data.type=="success"){
				toaster.pop('success','重置该用户密码成功!');
			}else{
				toaster.pop('error','重置该用户密码失败!');
			}
		})
	};
	
	$scope.expForClient = function(){
		$http.post('teacher/expForClient', {}).success(function(data){
			if(data.flag=="success"){
				toaster.pop('success',data.msg);
				$("#downloadForm").attr("action","attachment/download/" + data.attId);
				$("#downloadForm").submit();
			}else{
				toaster.pop('error',data.msg);
			}
		})
	};
	
	/** 上传用户开始 **/
	var uploadModal = $modal({title:'上传',scope: $scope, templateUrl: 'resources/app/common/upload.html', show: false});

	$scope.uploadParams = {
			accept: '.xls,.xlsx;',
			template: null,
			fileType: null,
			title: ''
	};
	
	$scope.showUploadModal = function() {
		if($stateParams.userType == userType.teacher){
			$scope.uploadParams.title = '上传命题教师';
			$scope.uploadParams.template = '命题教师导入模板.xlsx';
		}else if($stateParams.userType == userType.secretary){
			$scope.uploadParams.title = '上传学科秘书';
			$scope.uploadParams.template = '学科秘书模板.xlsx';
		}else if($stateParams.userType == userType.inputer){
			$scope.uploadParams.title = '上传录入员';
			$scope.uploadParams.template = '录入员模板.xlsx';
		}
		
		uploadModal.$promise.then(uploadModal.show);
	};
	
	var uploader = $scope.uploader = new FileUploader({
        url: 'user/importUser/' + $stateParams.userType
    });
	
	$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.msg);
			uploadModal.hide();
			$scope.load();
    	}
    };
    
    $scope.files = $scope.uploader.queue;
    
    $scope.uploader.onCompleteAll = function() {
		$scope.loading = null;
		$scope.uploader.clearQueue();
	}
    /** 上传用户结束 **/
    
    /** 关联课程 **/
    var relatedCoursesModal = $modal({title:'关联课程',scope: $scope, templateUrl: 'resources/app/user/relatedCourses.html', show: false});
	
	$scope.showRelatedCoursesModal = function(user) {
		$scope.curTeacher = user;
		relatedCoursesModal.$promise.then(relatedCoursesModal.show);
	};
})

/** 新增用户 **/
.controller('UserAddOrEditCtrl',function($scope,$http,$state,$stateParams,toaster,userType){
	$scope.model = {};
	
	$scope.load = function(){
		
		if($stateParams.id != null){
			var url = 'user/getById/'+ $stateParams.id;
			$http.get(url).success(function(data){
				$scope.model = data;
				
				var url = 'user/getAllRole';
				$http.get(url).success(function(data){
					$scope.allRoles = data;
					for(var i=0; i < $scope.allRoles.length; i++){
						for(var j=0; j < $scope.model.roles.length; j++){
							var userRole = $scope.model.roles[j];
							if($scope.allRoles[i].id == userRole.id){
								$scope.allRoles[i].selected = true;
								break;
							}
						}
					}
				})
				.error(function(data, code){alert(code);});
				
			})
			.error(function(data, code){alert(code);});
		}else{
			$scope.model = {};
			$scope.model.isEnabled = 1;

			if($stateParams.userType >= userType.teacher){
				$scope.model.userType = $stateParams.userType;
			}
			
			var url = 'user/getAllRole';
			$http.get(url).success(function(data){
				$scope.allRoles = data;
				//如果用户类型不为空，则角色默认为普通用户。
				if($stateParams.userType >= userType.teacher){
					for(var i=0; i<$scope.allRoles.length; i++){
						var role = $scope.allRoles[i];
						if(role.code=='domesticConsumer'){
							role.selected = true;
						}
					}
				}
			})
			.error(function(data, code){alert(code);});
		}
		
		$scope.showUserType = function(selected , name){
			var showUserType = selected;
			if(name == '普通用户' && showUserType == true){
				$("#showUserType").show();
			}else{
				$("#showUserType").hide();
			}
		}
		
		$scope.check = function($event , name){
			var checkbox = $event.target;
			if(name == '普通用户'){
				checkbox.checked? $("#showUserType").show() : $("#showUserType").hide();
			}
		}
	};
	$scope.load();
	
	$scope.submit = function(){
		if($scope.form.$invalid){
			toaster.pop('error' , '校验失败，请检查表单红框部分的内容！');
			$scope.submitted = true;
			return;
		}
		var selectedRoleIds = [];
		var isNormalRole = false;
		for(var i=0; i < $scope.allRoles.length; i++){
			var role = $scope.allRoles[i];
			if(role.selected){
				selectedRoleIds.push(role.id);
				if(!isNormalRole && role.name=='普通用户'){
					isNormalRole = true;
				}
			}
		}

		var user = {};
		if(selectedRoleIds.length == 0){
			toaster.pop('error', '请选择角色！');
			return;
		}else{
			user.role = selectedRoleIds;
		}
		if(isNormalRole && $scope.model.userType == null || $scope.model.userType == 0){
			toaster.pop('error', '请选择用户类型！');
			return false;
		}
		if($scope.model.certino != null){
			if(($scope.model.certino).length == 16 || ($scope.model.certino).length == 17){
				toaster.pop('error', "身份证号必须为15位或18位");
				return false;
			}
		}
		user.id = $scope.model.id;
		user.loginName = $scope.model.loginName;
		user.userType = $scope.model.userType;
		user.name = $scope.model.name;
		user.gender = $scope.model.gender;
		user.certino = $scope.model.certino;
		user.position = $scope.model.position;
		user.school = $scope.model.school;
		user.department = $scope.model.department;
		user.major = $scope.model.major;
		user.officePhone = $scope.model.officePhone;
		user.phone = $scope.model.phone;
		user.email = $scope.model.email;
		user.isEnabled = $scope.model.isEnabled;
		user.bankno = $scope.model.bankno;//银行账号
		/**
		if($stateParams.userType >= userType.teacher){
			user.userType = $stateParams.userType;
		}
		**/
		$scope.myPromise = $http.post('user/save',user)
		.success(function(data){
			if(data.flag == 'failed'){
				toaster.pop('error', data.msg);
			}
			else{
				toaster.pop('success', '操作成功！');
				if($stateParams.userType == userType.teacher){
					$state.go('teachers.list');
				}else if($stateParams.userType == userType.secretary){
					$state.go('secretary.list');
				}else if($stateParams.userType == userType.inputer){
					$state.go('inputer.list');
				}else{
					$state.go('users.list');
				}
			}
		})
		.error(function(data,code){
			alert(code);
		});
		
	};
	
	 function inspect(){
		
	}
	
	$scope.changeCall = function(){
		var officePhone = $scope.model.officePhone;
		if(officePhone.length > 11){
			$scope.messageCall = "超出电话号码最大位数，请检查";
		}else{
			$scope.messageCall = "";
		}
	}
	
})

/** 关联课程 **/
.controller('TeacherRelatedCourseCtrl',function($scope,$http,$state,$stateParams,toaster,userType){
	$scope.pageModel = {};
	$scope.pageModel.pageSize = 6;
	$scope.search = {};
	
	$scope.load = function(){
		$scope.curTeacherCourses = $scope.curTeacher.courses;
		_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);
			
			//当前教师关联课程不为空时，设置当前页所有课程的related状态
			
			angular.forEach($scope.curTeacherCourses, function(inCourse) {
				angular.forEach($scope.pageModel.array, function(course) {
					if(inCourse.code == course.code){
						course.related = true;
					}
				});
			})
		})
		.error(function(data, code){alert(code);});
	}
	
	$scope.addRelation = function(row){
		$http.post('user/addRelatedCourse/' + $scope.curTeacher.id + "/" + row.id)
		.success(function(res){
			if(res.flag=='failed'){
				toaster.pop('error', "操作失败！");
	           return false;
			}else{
				row.related = true;
				toaster.pop('success', "操作成功！");
				$scope.curTeacherCourses.push(row);
			}
		});
	}
	
	$scope.removeRelation = function(row){
		$http.post('user/removeRelatedCourse/' + $scope.curTeacher.id + "/" + row.id)
		.success(function(res){
			if(res.flag=='failed'){
				toaster.pop('error', "操作失败！");
				return false;
			}else{
				row.related = false;
				toaster.pop('success', "操作成功！");
				
				for(var i=0; i<$scope.curTeacherCourses.length; i++){
					var inCourse = $scope.curTeacherCourses[i];
					if(inCourse.code == row.code){
						$scope.curTeacherCourses.splice(i, 1);
						break;
					}
				}
			}
		});
	}
})