/**
* 任务相关api
* 使用: seajs.use("dbfen/client/api/user", function(User){
		User.login({userId:33});
	});
*@author kenny
*/
(function(){

	//任务处理状态
	var g_taskState = {
		
		backupFinish: 1,//完成 FinishTaskState
		backupWait: 2,// 等待备份任务 WaittingBackupTaskState
		backupDb: 3,//导出db ExportingDbTaskState
		backupFile: 4,//备份文件 BackupFileTaskState
		backupWaitWtop: 5,//备份等待停止 BackupWaittingStopTaskState
		
		recoveryFinish: 21,//完成恢复任务 WaittingRestoreTaskState
		recoveryWait: 22,//恢复文件任务 RestoreFileTaskState
		recoveryFile: 23, //恢复file任务 ImportingDbTaskState
		recoveryDb: 24, //恢复db
		recoveryWaitStop: 25//恢复等待停止 RestoreWaittingStopTaskState,		
	};
	//任务类型
	var g_taskType = {
		file: 0,
		mysql: 1,
        mssql: 2,
        psql: 3,
        oracle: 4
	}
	//任务开关状态
	var g_switchState = {
		normal: 0,//正常状态
		close: 1,//关闭状态
		incomplete: 2 //残缺状态(内容不完整)
	};
	//备份策略
	var g_schedType = {
		day: 1, //按天备份
		week: 2 //按周备份
	};
	//状态过滤器
	var g_taskFilter = {
		all: 0,//取所有
		backup: 1,//只取备份的
		recovery: 2 //只取恢复的
	};
	define("dbfen/client/api/task", function(require, exports, module){
		var dbfen = require("dbfen/client/com/dbfen");
		var User = require("dbfen/client/api/user");
		var Module = {
			TASK_STATE: g_taskState,//任务状态
			TASK_TYPE: g_taskType, //任务类型
			SCHED_TYPE: g_schedType,
			SWITCH_STATE: g_switchState,
			TASK_FILTER: g_taskFilter,
			//停止任务执行
			stop: function(task, callback){
				dbfen.ajaxLogin({//需要登录才能调用接口
					url:"/task/stop",
					data: task,
					success: callback
				});
			},
			/** 启动运行备份 
				task:{
					taskId,1,
					taskType:1
				}
			*/
			backup: function(task, callback){
				dbfen.ajaxLogin({//需要登录才能调用接口
					url:"/task/backup",
					data: task,
					success: callback
				});
			},
			//启动运行恢复
			recovery: function(task, callback){
				dbfen.ajaxLogin({//需要登录才能调用接口
					url:"/task/restore",
					data: task,
					success: callback
				});
			},
			//启动任务
			start: function(task, callback){
				dbfen.ajaxLogin({//需要登录才能调用接口
					url:"/task/start",
					data: task,
					success: callback
				});
			},
			/**关闭任务,任务不可调度
				task:{
					taskId,
					taskType
				}
			*/
			close: function(task, callback){
				dbfen.ajaxLogin({//需要登录才能调用接口
					url:"/task/close",
					data: task,
					success: callback
				});
			},
			/** 
				打开关闭的任务
				task:{taskId, taskType}
			*/
			open: function(task, callback){
				dbfen.ajaxLogin({//需要登录才能调用接口
					url:"/task/open",
					data: task,
					success: callback
				});
			},
			/**
				判断是否有任务在处理中,任务任务来做处理
			*/
			isHandle: function(task, callback){
				Module.getState(task, function(result){
					var data = result.data;
					var res = {
						code: result.code,
						data:{
							isHandle:false //标记任务状态处理,true=有,false=无
						}
					};
					if(result.code == 0){
						//文件任务
						switch(data.taskType){
						case g_taskType.file:
							//如果任务正在备份或恢复或等待中,标记处理状态为true
							if(data.taskState == g_taskState.backupFile||
								data.taskState == g_taskState.recoveryFile||
								data.taskState == g_taskState.backupWait||
								data.taskState == g_taskState.recoveryWait){
								res.data.isHandle = true;
							}else{
								res.data.isHandle = false;
							}
							break;
						case g_taskType.mysql:
						case g_taskType.mssql:
                        case g_taskType.oracle:
							//如果任务正在备份或恢复或等待中,标记处理状态为true
							if( data.taskState == g_taskState.backupDb||
								data.taskState == g_taskState.recoveryDb||
                                data.taskState == g_taskState.recoveryFile||
								data.taskState == g_taskState.backupWait||
								data.taskState == g_taskState.recoveryWait){
								res.data.isHandle = true;
							}else{
								res.data.isHandle = false;
							}
							break;
						}
						
					}
					callback && callback(res);
				});
			},
			/**
			*	取得任务列表
			*/
			getList: function(task, callback){
				if(task instanceof Function){
					callback = task;
					task = {};
				}
				dbfen.ajax({//需要登录才能调用接口
					url:"/task/get_list",
					data: task,
					dataType:'json',
					success: callback
				});
			},
			/* 取可以恢复的任务列表  */
			getRecoverTaskList: function(callback){
				
				Module.getList(function(res1){
					var result = {
						code: 0,
						data: {
							list: []
						}
					};
					var list1 = (res1.data||{}).list||[];
					if(res1.code != 0){
						return callback && callback(res1);
					}
					if(list1.length < 1){
						return callback && callback(result);
					}
					var curExecTask ;//当前正在执行的任务
					Module.getState({
						taskFilter: g_taskFilter.recovery
					}, function(res){
						var data = res.data||{};
						var list2 = data.list||[];
						if(list1.length < 1){
							return;
						}
						//取有恢复任务的
						for(var i in list2){
							var item = list2[i];
							switch(item.taskState){
							case g_taskState.recoveryWait:
							case g_taskState.recoveryDb:
							case g_taskState.recoveryFile:
								if(curExecTask==null){
									curExecTask = item;
								}						
								break;
							}
						}

						//没有恢复的,取最后完成的任务
						if(curExecTask==null){
							for(var i in list2){
							    var item = list2[i];
							    switch(item.taskState){
								case g_taskState.recoveryFinish:
									if(curExecTask==null){
										curExecTask = item;
									}						
									break;
								}
							}
						}

						//把取到的curExecTask放到第一个位置
						curExecTask && result.data.list.push(curExecTask);
						for(var i in list1){
							var task = list1[i];
                            if(task.host == "127.0.0.1" || task.host.toLocaleLowerCase() == "localhost"){
                                task.host = "127.0.0.1";
                            }
							if(curExecTask && curExecTask.taskId==task.taskId){
								continue;
							}
							if(task.backupedNum>0){//成功备份记录数
                                result.data.list.push(task);
							}
							if(result.data.list.length > 100){
								break;
							}
						}
						callback && callback(result);
					});
				
					/*var dealCount = 0;
					$.each(list1, function(i, task){
						Module.getInfo({
							taskId: task.taskId,
							taskType: task.taskType
						}, function(res){
							dealCount++;
							var data = res.data || {};
							if( data.backupList && data.backupList.length > 0 ){
								result.data.list.push(task);
							}
							if(dealCount == list1.length){
								callback && callback(result);
							}
						});
					});*/
				});
			},
			/** 
				取任务状态,
				task:{ 
					taskId:1 取单个任务时要传.批量取不用传
				}
				调用:
				getState(task,callback);
				getState(callback);
			*/
			getState: function(task, callback){
				if(task instanceof Function){
					callback = task;
					task = {};
				}
				var data = {};
				data.taskFilter = g_taskFilter.all;
				if(task){
					data.taskId = task.taskId;
					data.taskType = task.taskType;
					data.taskFilter = task.taskFilter||g_taskFilter.all; //0 - all, 1 - backup, 2 - restore
				}
				dbfen.ajax({
					url:"/task/get_progress",
					data: data,
					success: function(result){
						var res = {
							code: result.code,
							msg: result.msg
						};
						var data = result.data || {};
						var list = data.list || [];
						list = list.sort(function(d1, d2){
							var t1 = parseInt( d1.finishTime );
							var t2 = parseInt( d2.finishTime );
							return t1 < t2;
						});
						if(task && task.taskId>0){
							res.data = list[0];
						}else{
							res.data = result.data;
						}
						callback && callback(res);
					}
				});
			},
			/**
			* 取任务信息
			*	task:{
					taskId,
					taskType
				}
			*/
			getInfo: function(task, callback){
				/*dbfen.ajaxLogin({//需要登录才能调用接口
					url:"/task/get_info",
					data: task,
					success: function(result){
						callback({
							code: 0,
							data: {
								taskId: task.taskId,
								taskType: task.taskType,
								backupList: [
									{count:10, uploadSize:100,backupDate:new Date().getTime()}
								]
							}
						});
					}
				});*/
				var data = {
					taskId: task.taskId,
					taskType: task.taskType
				}
				dbfen.ajaxLogin({
					url:'/task/get_info',
					data: data,
					type: 'GET',
					success: function(result){
						var data = result.data || {};
						var backupList = data.backupList||[];
						data.backupList = backupList.slice(0, 100);
						result.data = data;
						callback && callback(result);
					}
				});
			},
			/** 取用户备份内容列表,用户 
				task: 
					taskId,
					taskType,
					date: 时间版本,可选
			*/
			getBackupContentList: function(task, callback){
				var data = {
					taskId: task.taskId,
					taskType: task.taskType,
					date: task.date||""
				}
				dbfen.ajaxLogin({//需要登录才能调用接口
					url:"/task/get_restore_list",
					data: data,
					success: callback
				});
			},
            /**
             临时目录设置
             */
            getCache: function(callback){
                dbfen.ajaxLogin({//需要登录才能调用接口
                    url:"/task/db/get_cache",
                    success: callback
                });
            },
			//运行恢复
			showViewVerify: function(task) {
				var taskId = task.taskId || "",
					taskType = task.taskType || "";
				dbfen.popWindow({//打开页面,默认需要登录
					title: '文件恢复',
					url:'/view/recover/verify.html?taskId=' + taskId + "&taskType=" + taskType
				});	
				/*User.checkLogin(function(user){//检测用户登录
					if(!user) return;//用户登录没有成功或没有登录
					parent.seajs.use("lib/jquery/layer", function() {
						var layer = parent.__popWindowId;
						parent.__popWindowId = parent.$.layer({
							type: 2,
							shade: [0.2, '#000'],
							shadeClose: false,
							closeBtn: [0, true],
							fix: false,
							title: '确认恢复',
							iframe: {
								src: getBaseUrl() + '/view/recover/verify.html?' + new Date().getTime()
							},
							area: ['400px', '390'],
							border: [1, 1, '#ccc'],
							close: function(index) {}
						});
						parent.$("#xubox_layer" + layer + ", #xubox_shade" + layer).remove();
					});
				}, {
					isShow: true
				});*/
			}
		};

		module.exports = Module;
	});

})();