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

/** 密码本管理 **/
.controller('PswSettingCtrl',function($cookieStore,$scope,$http,appConst){
	
	$scope.load = function(){
		var url = 'examSetting/queryLog';
		$http.get(url).success(function(data){
			$scope.array = data.rows;
			$scope.total = data.total;
		});
	};
	$scope.load();
})

/** 创建密码本 **/
.controller('PswSettingAddCtrl',function($scope,$http,$state,toaster){
	$scope.model = {};
	$scope.submit = function(){
		var obj = angular.toJson($scope.model);
		$http.post('examSetting/addCodeBook',$scope.model)
		.success(function(data){
			if(!data.result){
//				alert(data.msg);
				toaster.pop('error', data.msg);
			}
			else{
				$state.go('pswSetting');
			}
		})
		.error(function(data,code){
			alert(code);
		});
	};
})

/** 备份还原 **/
.controller('BackupAndRestoreCtrl',function($cookieStore,$scope,$http,appConst,$modal,FileUploader, $q, toaster, $window){
	$scope.load = function(){
		var url = 'examSetting/validateCodeBook';
		$http.get(url).success(function(data){
			$scope.canBackup = data.canBackup;
		});
	};
	$scope.load();
	
	$scope.backup = function(){
		$scope.loading = $http.post('examSetting/backupSys').success(function(data){
			if(data.zipFileName){
				toaster.pop('success', '处理完成, 文件名：' + data.zipFileName);
				$window.open("examSetting/downloadBackupFile/" + data.zipFileName);
			}else{
				toaster.pop('error', '处理失败');
			}
			$scope.load();
		});
	};
	
	/** 导入备份文件 **/
	var uploadModal = $modal({title:'上传文档',scope: $scope, templateUrl: 'resources/app/common/upload.html', show: false});
	$scope.showUploadWin = function() {
		$scope.uploadParams = {
				accept: '.zip',
				fileType: null,
				title: '上传备份文件'
		};
		
		uploadModal.$promise.then(uploadModal.show);
	};
	
	$scope.uploader = new FileUploader({
        url: 'examSetting/restoreSys'
    });
	
	$scope.upload = function() {
		$scope.loading = $q.defer().promise;
		$scope.uploader.queue[0].upload();
    };
    
    $scope.uploader.onSuccessItem = function(fileItem, response, status, headers) {
    	if(response.randomCode){
    		toaster.pop('success', '导入成功！');
    		uploadModal.hide();
    		$scope.randomCode = response.randomCode;
    		$scope.zipPassword = "";
    	}else{
    		toaster.pop('fail', '导入失败！');
    	}
    };
    
    $scope.files = $scope.uploader.queue;
    
    $scope.uploader.onCompleteAll = function() {
		$scope.loading = null;
		$scope.uploader.clearQueue();
	};
	
	/** 还原 **/
	$scope.unZipAndRestore = function(validate){
		if(validate){
			$scope.loading = $http.post('examSetting/continueRestoreSys', {randomCode: $scope.randomCode, password: $scope.zipPassword})
				.success(function(result){
				if(result.success){
					toaster.pop('success', '恢复成功。');
					$scope.randomCode = null;
		    		$scope.zipPassword = "";
				}else{
					toaster.pop('error', result.message);
				}
			});
		}
		if(!validate){
			$scope.submitted = true;
		}
	};
})