'use strict';
angular.module('qrzk')
.controller('RootCtrl',function($scope,$http,$state,$cookieStore,$location,$modal,toaster,userType){
	
	$scope.menus = [];
	$scope.userType = userType;
	
	$scope.load = function(){
		$http.post('user/queryCurUserRole').success(function(data){
			$scope.curUserRole = data;
			var menuUrl = 'resources/app/menu/menu.json.jsp';
			
			$http.get(menuUrl).success(function(data){
				$scope.menus = data;
				//console.log(data);
			});
			
		})
		.error(function(data, code){
			alert(code);
		});
		
		$http.post('user/queryCurUser').success(function(data){
			$scope.curUser = data;
		});
	};
	
	$scope.load();
	
	$scope.changePassword  = {
		password:null,
		password2:null
	};
	
	$scope.imCount = 0;
	//更新任务提醒
	$scope.updateTaskCount = function(){
		$http.post('message/queryRelatedMessage').success(function(data){
			$scope.array = data.rows;
			$scope.appPath = data.appPath;
			
			var todoTaskCount = 0;
			
			$http.post('user/queryCurUser').success(function(data){
				$scope.curUser = data;
				
				angular.forEach($scope.array, function(task){
					if(task.curDealer == $scope.curUser.id && task.status != 'ARCHIVED' && task.msgStatus == '1'){
						todoTaskCount++;
					}
				});
				
				var rootPath = window.location.protocol + "//" + window.location.host + $scope.appPath;
				if($scope.imCount == 0){
					if(todoTaskCount == 0){
						$('#im_count').hide();
					}else{
						$('#im_count').html(todoTaskCount);
						$('#im_count').show();
						$scope.imCount = todoTaskCount;
						//新任务提醒
						if($('#newMessageDIV').html() == ''){
							$('#newMessageDIV').append('<audio id="player" autoplay="true"><source src="' + rootPath + '/resources/sound/sound.wav" type="audio/wav"/></audio>');
						}else{
							$('#newMessageDIV').html('');
							$('#newMessageDIV').append('<audio id="player" autoplay="true"><source src="' + rootPath + '/resources/sound/sound.wav" type="audio/wav"/></audio>');
						}
//						$http.post('attachment/openSound');
					}
				}else{
					if(todoTaskCount == 0){
						$('#im_count').hide();
					}else{
						//新任务提醒
						if(todoTaskCount > $scope.imCount){
							if($('#newMessageDIV').html() == ''){
								$('#newMessageDIV').append('<audio id="player" autoplay="true"><source src="' + rootPath + '/resources/sound/sound.wav" type="audio/wav"/></audio>');
							}else{
								$('#newMessageDIV').html('');
								$('#newMessageDIV').append('<audio id="player" autoplay="true"><source src="' + rootPath + '/resources/sound/sound.wav" type="audio/wav"/></audio>');
							}
//							$http.post('attachment/openSound');
						}
						$('#im_count').html(todoTaskCount);
						$('#im_count').show();
						$scope.imCount = todoTaskCount;
					}
				}
			});
		});
	};
	$scope.updateTaskCount();
	
	//定时执行
	setInterval(function() {
		$scope.updateTaskCount();
	}, 10000);
	
	var myTaskModal = $modal({title:'我的任务',scope: $scope, templateUrl: 'resources/app/myTaskTip.html', show: false});
	
	//我的任务提醒页面
	$scope.showMyTaskModal = function(userId){
		$http.post('message/queryRelatedMessage').success(function(data){
			$scope.array = data.rows;
			
			$scope.search = {};
			//设置默认查询条件为待处理
			$scope.search.curDealer = userId;
			$scope.search.status = '!ARCHIVED';
			$scope.matchType = true;
			
			var todoTaskCount = 0;
			var finishedTaskCount = 0;
			
			angular.forEach($scope.array, function(task){
				if(task.curDealer == $scope.search.curDealer && task.status != 'ARCHIVED' && task.msgStatus == '1'){
					todoTaskCount++;
				}
				
				if(task.status == 'ARCHIVED'){
					finishedTaskCount++;
				}
			});
				
//			if(todoTaskCount == 0){
//				toaster.pop('warning', '没有未读消息！');
//			}else{
//				
//			}
			myTaskModal.$promise.then(myTaskModal.show);
		});
	};
	
	$scope.showTaskDetail = function(row){
		myTaskModal.hide();
		$state.go('task.paperTask.reviewDetail', {taskId: row.taskId});
	};
	
	var changePasswordModal = $modal({title:'修改密码',scope: $scope, templateUrl: 'resources/app/changePassword.html', show: false});
	
	$scope.showChangePasswordModal = function() {
		changePasswordModal.$promise.then(changePasswordModal.show);
	};
	
	var olUserModal = $modal({title:'在线用户列表',scope: $scope, templateUrl: 'resources/app/olUser.html', show: false});
	$scope.showOLUserModal = function(){
	olUserModal.$promise.then(olUserModal.show);
		$http.post('user/olUser').success(function(data){
			$scope.olUser = data;
			$scope.number = data.length;
		});
	};
	$scope.savePassword = function(){
		if($scope.changePassword.password != $scope.changePassword.password2){
			$scope.changePassword.password = null;
			$scope.changePassword.password2 = null;
			toaster.pop('error','两次输入的密码不一致。');
		}else{
			$http.post('user/changePassword', $scope.changePassword.password)
			.success(function(data){
				if(data.result){
					toaster.pop('success','更新成功！');
					$scope.changePassword.password = null;
					$scope.changePassword.password2 = null;
				}
				else{
					toaster.pop('warning','保存失败！');
				}
				changePasswordModal.hide();
			});
		}
	};
})

.controller('HomeCurUserReportCtrl',function($scope,$http,$state,$cookieStore,$location,$modal,toaster,userType){
	$scope.load = function(){
		$scope.reportLoading = $http.post('user/queryCurAllRoleCodes').success(function(data){
			for(var i=0;i<data.length;i++){
				if(data[i] == 'quesAuditor'){
					$scope.isQuesAuditor = true;
					$http.post('question/statMyAuditJob').success(function(data){
						$scope.statMyAuditJobArr = data.auditJob;
					})
					.error(function(data, code){
						alert(code);
					});
				}else if(data[i] == 'quesInputer'){
					$scope.isQuesInputer = true;
					$http.post('question/statMyInputJob').success(function(data){
						$scope.statMyInputJobArr = data.inputJob;
					})
					.error(function(data, code){
						alert(code);
					});
				}else if(data[i] == 'domesticConsumer'){
					$scope.domesticConsumer = true;
					$http.post('taskCenter/queryRelatedPaperTasks').success(function(data){
						$scope.totalTaskCount = data.total;
						if($scope.totalTaskCount > 0){
							$http.post('business/queryBatchById/' + data.rows[0].batchId).success(function(data){
								$cookieStore.userBatch = data;
							});
						}
					});
					$http.post('taskCenter/queryTodoPaperTasks').success(function(data){
						$scope.todoTaskCount = data.total;
					});

					
				}
			}
			
		}).error(function(data, code){ alert(code);});
		$http.get('corrigendum/user/list').success(function (data) {
			$scope.corrigendum = data;
		}).error(function (data, code) {
			alert(code);
		});
		};
	
	$scope.load();
})

.controller('LearnCenterListCtrl',function($scope,$http,$state,$location,$modal,toaster,$stateParams,FileUploader,$q,learnCenter,userType){
	$scope.load = function(){
		$scope.categoryCode = $stateParams.categoryCode;
		
		if(!$stateParams.categoryName){
			angular.forEach(learnCenter.categories, function(category) {
				if(category.code == $stateParams.categoryCode){
					$stateParams.categoryName = category.name;
				}
			});
		}
		
		$http.post('learnCenter/queryByCode/' + $stateParams.categoryCode).success(function(data){
			$scope.array = data.rows;
		})
		.error(function(data, code){
			alert(code);
		});
	};
	$scope.load();
	
	$scope.deleteRow = function(data){
		var param ={'ids': data.id, 'attIds': data.attachmentId}; 	
		$.post('learnCenter/delete',param,function(res){
			if(res.flag=='failed'){
				toaster.pop('error', "删除失败，请联系管理员。");
	           return false;
			}else{
				toaster.pop('success', "删除成功");
				$scope.load();
			}
		});
	};
	
	//上传
	$scope.goUpload = function() {
		$state.go('learnCenter.upload', {'categoryCode':$stateParams.categoryCode, 'categoryName':$stateParams.categoryName});
	};
	
})
.controller('LearnCenterRootCtrl',function($scope,$http,$state,$location,$modal,toaster,$stateParams){
	$scope.menus = [];
	
	$scope.goList = function(categoryCode, categoryName){
		$state.go('learnCenter.list', {'categoryCode':categoryCode, 'categoryName':categoryName});
	};
})
/** 上传帮助文档 **/
.controller('LearnCenterUploadCtrl',function($scope, $http, FileUploader, $q,$stateParams, toaster,learnCenter){
	
	$scope.load = function(){
		if(!$stateParams.categoryName){
			angular.forEach(learnCenter.categories, function(category) {
				if(category.code == $stateParams.categoryCode){
					$stateParams.categoryName = category.name;
				}
			});
		}
	};
	$scope.load();
	
	var uploader = $scope.uploader = new FileUploader({
        url: 'attachment/upload'
    });
	
    $scope.model = {};
    uploader.onSuccessItem = function(fileItem, response, status, headers) {
    	if(response.att){
    		var fileNameArray = response.att.originalName.split('_');
    		
    		var courseCode = $scope.model.courseCode;
    		if(fileNameArray[0].length == 5 && fileNameArray[0].match(new RegExp('[0-9]{5}'))){
    			courseCode = fileNameArray[0];
    		}
    		
    		var param = {'categoryCode': $stateParams.categoryCode, 'courseCode': courseCode
					, 'attachmentId': response.att.id, 'keyword': response.att.originalName};
    		
    		$http.post('learnCenter/uploadLearnCenter',param).success(function(res){
    			if(res.flag=='failed'){
    				toaster.pop('error', "上传失败，请联系管理员。");
    	           return false;
    			}else{
    				//toaster.pop('success', "上传成功。");
    			}
    		});
    	}else{
    		alert(response.msg);
    	}
    };
    
});
