(function(){
	define("dbfen/client/view/tasklist", function(require, exports, module) {
		var User = require("dbfen/client/api/user");
		var dbfen = require("dbfen/client/com/dbfen");
		var Task = require("dbfen/client/api/task");
		var Mysql = require("dbfen/client/api/task/mysql");
        var Mssql = require("dbfen/client/api/task/mssql");
		var File = require("dbfen/client/api/task/file");
        var Oracle = require("dbfen/client/api/task/oracle");
		require("lib/jquery/cookie");
        require("lib/jquery/titletip");
		var Module = {
			init: function() {
				//title 美化
				setTimeout(function() {
					$(".backup-list .group a[title]").colorTip({
						color: "blue"
					});
					$(".backup-list").show();
				}, 200);
				Module.showTaskList();//提示任务列表,并显示任务列表
				Module.__initEvent();
				setTimeout(function(){
					Module.checkProgress();
				},4000);
				if(!$.cookie('create')){
					$(".tasklist .title-bar").append('<i class="arrow-mark"></i>');
				};
			},
			/** 检测任务进度 */
			checkProgress: function(task){
				setTimeout(function(){
                    if($(".z-task.runing").length < 1){
                        Module.checkProgress(task);
                        return;
                    }
					Task.getState({
						taskFilter: Task.TASK_FILTER.backup
					},function(result){
						var data = result.data || {};
						switch(result.code){
						case 0:
							$.each(data.list || [], function(i, item) {
								updateView(item);//更新界面
							});
							break;
						default:
						}
					});
					Module.checkProgress(task);
				}, 3000);
			},
			__initEvent: function(){
				/*** 自定义事件 全局事件,,,任务触发 start */

				//任务关闭事件
				$('.z-task').live({
					click: function(e){
						var target = e.target || e.srcElement;
						var $task = $(this).closest(".z-task"),
							$li = $(this).closest("li");
						var task = {
							taskId: parseInt($task.attr("taskid"))||0,
							taskType: $task.attr("tasktype")
						};
						if($(target).closest(".z-opt,.z-switch").length > 0){
							return;
						}
						if( task.taskId > 0 ){
							if ($li.hasClass('z-mysql')) {
								Mysql.showViewReports(task);
							} else if ($li.hasClass('z-mssql')) {
								Mssql.showViewReports(task);
							} else if ($li.hasClass('z-file')) {
								File.showViewReports(task);
							} else if ($li.hasClass('z-oracle')) {
                                Oracle.showViewReports(task);
                            }
						}						
					},
					backup: function(e){//调用备份任务事件
						var $task = $(e.target).closest(".z-task");
						var task = {
							taskId: $task.attr("taskId"),
							taskType: $task.attr("taskType")
						};
						$task.addClass('runing').removeClass('shut');

						//判断有没有任务在运行中,没有就开始备份
						Task.isHandle(task, function(){
							Task.backup(task, function(result){//触发任务备份
								switch(result.code){
								case 0: 
									$(window).trigger("updateView");//触发更新进度任务,让更新进度去负责逻辑处理
									break;
								default:
									$.alert(result.msg || "启动任务备份失败!");
								}
							});
						});
						
					}
				});
				$(window).on({
					resize: function(){
						var height =$(".backup").height();
						$("body").css("height", (height+250)+"px");
					},
					login: function(){//用户登录
						Module.showTaskList();//显示任务列表
					},
					updateView: function(e){//更新进度事件
						Module.showTaskList();
					},
					//创建任务事件,任务创建完成,由具体页面来触发
					viewCreate: function(e) { 
						//打开开关
						Module.showTaskList();									
					}
				});
				/*** 自定义事件 end */

				//创建,打开,关闭任务
				$(".backup-list .z-task .switch-ic").live({
					click: function(e) {
						var $task = $(this).closest(".z-task"),
							taskId = parseInt( $task.attr("taskId") ),
							taskType = $task.attr("taskType"),
                            me = this,
							task = {
								taskId: taskId,
								taskType: taskType
							};
						if($(".arrow-mark").length){
							writeCookie("create", 1);
							$(".arrow-mark").remove();
						};
						if ($task.hasClass('runing')) { //任务存在
							$.confirm("确定关闭备份吗?", function(bool) {
								if (bool) { //确认关闭
									$(".z-tipbb").remove();
									Task.close(task, function(result) {
										switch (result.code) {
											case 0:
												$task.addClass('shut').removeClass('runing');
												$task.find(".z-tip").text('关闭成功');
												$task.find(".z-opt").hide();
												$task.find(".z-progress").hide();
												$task.find(".z-time p").html("");
												$task.find(".switch-ic span").text("启动备份");
												break;
											default:
												$.alert(result.msg || "关闭备份失败");
												break;
										}
									});
								}
							});
						} else if( taskId>0 ){//任务存在,但是关闭,这时打开任务
							Task.getInfo(task, function(result){
								var data = result.data || {};
								var $type = $task.closest("li");
								if ($type.hasClass('z-mysql')) {
									Mysql.showViewDB(task);
								} else if ($type.hasClass('z-mssql')) {
									Mssql.showViewDB(task);
								} else if ($type.hasClass('z-file')) {
									File.showViewSetting(task);
								} else if ($type.hasClass('z-oracle')) {
                                    $.confirm("确定进行Oracle全库增量模式备份吗？", function(bool) {
                                        if (bool) { //确认关闭
                                            $(".z-tipbb").remove();
                                            openTask(task, $task);
                                        }
                                    });
                                    return;
                                }
                                openTask(task, $task);
							});
						} else { //任务不存在,创建
							var $type = $task.closest("li");
							if ($type.hasClass('z-mysql')) {
								Mysql.showViewCreate();
							} else if ($type.hasClass('z-mssql')) {
								Mssql.showViewCreate();
							} else if ($type.hasClass('z-file')) {
								File.showViewCreate();
							} else if ($type.hasClass('z-oracle')) {
                                Oracle.showDir();
                            }
						}
						stopPropagation(e);
					}
				});

				//参数设置
				$(".backup-list .z-task .z-setting").live({
					click: function(e) {
						var $task = $(this).closest(".z-task"),
							$li = $(this).closest("li");
						var task = {
							taskId: $task.attr("taskid"),
							taskType: $task.attr("tasktype")
						};
						if ($li.hasClass('z-mysql')) {
							Mysql.showViewSetting(task);
						} else if ($li.hasClass('z-mssql')) {
							Mssql.showViewSetting(task);
						} else if ($li.hasClass('z-file')) {
							File.showViewSetting(task);
						} else if ($li.hasClass('z-oracle')) {
                            Oracle.showViewSetting(task);
                        }
						stopPropagation(e);
					}
				});

				//查看报告
				$(".backup-list .z-task .z-reports").live({
					click: function(e) {
						var $task = $(this).closest(".z-task"),
							$li = $(this).closest("li");
						var task = {
							taskId: $task.attr("taskid"),
							taskType: $task.attr("tasktype")
						};
						if ($li.hasClass('z-mysql')) {
							Mysql.showViewReports(task);
						} else if ($li.hasClass('z-mssql')) {
							Mssql.showViewReports(task);
						} else if ($li.hasClass('z-file')) {
							File.showViewReports(task);
						}
						stopPropagation(e);
					}
				});

				//设置备份
				$(".backup-list .z-task .z-backup").live({
					click: function(e) {
						var $task = $(this).closest(".z-task"),
							$li = $(this).closest("li");
						var task = {
							taskId: $task.attr("taskid"),
							taskType: $task.attr("tasktype")
						};
						if ($li.hasClass('z-mysql')) {
							Mysql.showViewBackup(task);
						} else if ($li.hasClass('z-mssql')) {
							Mssql.showViewBackup(task);
						} else if ($li.hasClass('z-file')) {
							File.showViewBackup(task);
						} else if ($li.hasClass('z-oracle')) {
                            Oracle.showViewBackup(task);
                        }
						stopPropagation(e);
					}
				});

				//设置备份数据库
				$(".backup-list .z-task .z-db").live({
					click: function(e) {
						var $task = $(this).closest(".z-task"),
							$li = $(this).closest("li");
						var task = {
							taskId: $task.attr("taskid"),
							taskType: $task.attr("tasktype")
						};
						if ($li.hasClass('z-mysql')) {
							Mysql.showViewDB(task);
						} else if ($li.hasClass('z-mssql')) {
							Mssql.showViewDB(task);
						} else if ($li.hasClass('z-file')) {
							File.showViewDir(task);
						}
						stopPropagation(e);
					}
				});

                //设置临时上当
                $(".backup-list .z-task .z-dir").live({
                    click: function(e) {
                        var $task = $(this).closest(".z-task"),
                            $li = $(this).closest("li");
                        var task = {
                            taskId: $task.attr("taskid"),
                            taskType: $task.attr("tasktype")
                        };
                        if ($li.hasClass('z-mysql')) {
                            Mysql.showViewDir(task);
                        } else if ($li.hasClass('z-mssql')) {
                            Mssql.showViewDir(task);
                        }
                        stopPropagation(e);
                    }
                });

				//停止备份
				$(".backup-list .z-task .z-stop").live({
					click: function(e) {
						var $task = $(this).closest(".z-task"),
							$li = $(this).closest("li");
						var task = {
							taskId: $task.attr("taskid"),
							taskType: $task.attr("tasktype")
						};
						$.confirm("确认取消任务吗?", function(bool){
							bool && Task.stop(task, function(result) {
								switch (result.code) {
									case 0:
										$task.find(".z-tip").show().html("已取消");
										$task.find(".z-progress").hide();
										//$(".n2", $li).html('<p class="mt8 z-time">已停止</p>');
								}
							});
						});
						stopPropagation(e);
					}
				});
				$(".backup-list .z-task .z-opt, .z-tipbb").live({
					mouseenter: function(e){
						$(".z-tipbb").hide();
						var expires = new Date();
							expires.setFullYear(expires.getFullYear() + 99); //保存99年
						var cookieConfig = {//cookie参数
							path: "/",
							expires: expires
						};
						$.cookie("showtipbb","true", cookieConfig);
					}
				});
				//立即备份
				$(".backup-list .z-task .z-once").live({
					click: function(e) {
						var $task = $(this).closest(".z-task");
						var task = {
							taskId: $task.attr("taskid"),
							taskType: $task.attr("tasktype")
						};
						Task.getState(function(result){
							var data = result.data || {};
							var list = data.list || [];
							var isHandle = false;
							for(var i in list){
								var item = list[i];
								switch(item.taskState){
								case Task.TASK_STATE.backupFinish:
								case Task.TASK_STATE.recoveryFinish:
								case 0:
									break;
								default:
									isHandle = true;
								}
								if(isHandle)break;
							}
							//有任务在执行中
							if(isHandle == true){
								$task.find(".z-moreLink").tips("亲,你有任务在备份或恢复中,不能执行备份操作^^");
								//$.alert();
								return;
							}
							$task.trigger("backup");//触发立即备份事件;
						});
						stopPropagation(e);
					}
				});

                //备份远程MySQL
                 $(".z-addMysqlRemote").live({
                    click: function(e){
                        Mysql.showViewCreate({
                            create: "remote"
                        });
                    }
                });

                //备份远程MSSQL
                $(".z-addMssqlRemote").live({
                    click: function(e){
                        Mssql.showViewCreateRemote();
                    }
                });
			},
			/** 显示任务列表 */
			showTaskList: function() {
				//取任务列表数据
				Task.getList(function(result) {
					var data = result.data || {};
					switch (result.code) {
						case 0:
							var localList = [], remoteList=[];
							$.each(data.list, function(i, item){
								if(item.startTime){
									item.formatTime = new Date(parseInt(item.startTime)*1000).format("yyyy-MM-dd hh:mm:ss");
								}
								item.formatChangedSize = dbfen.formatByte(item.changedSize);
								if(item.host==""||item.host=="127.0.0.1"||item.host.toLocaleLowerCase()=="localhost"){
									localList.push(item);
								}else{
									remoteList.push(item);
								}
							});

							function showItem(i, item) {							
								updateView(item);//更新界面
								if(i==data.list.length-1&&$.cookie("showtipbb")!="true"&&
									item.switchState == Task.SWITCH_STATE.normal){
									showTippp(item);//显示提示箭头
								}
							}
							try{
								if(remoteList.length > 0){
									$('.z-remote').show();
								}
								var $remote = $("#remoteTask").html("");
								var template = $("#dbTemplate").html();
								$.each(remoteList, function(i, item){
									var html = doT.template( template )( item );
									var $host = $remote.find('[host="'+item.host+'"]');
									if($host.length > 0){
										$host.append(html);
									}else{
										html='<div host="'+item.host+'" class="ipgroup"><h4 class="iptitle">'+item.host+'</h4>'+html+"</div>";
										$remote.append(html);
									}
									showItem(i, item);
								});
                                $remote.append('<p class="remote-link"><a href="javascript:;" class="cor_blue underline z-addMysqlRemote">备份远程MySQL</a><a href="javascript:;" class="cor_blue underline ml70 z-addMssqlRemote">备份远程MSSQL</a></p>');
								//var html = doT.template( template )( remoteList );
								//$("#remoteTask").html(html);
								//$.each(remoteList, showItem)
							}catch(e){
								console.error(e.stack,e);
							}
							$.each( localList, showItem);
							$(window).trigger("resize");
							break;
						default:
							$.alert(result.msg || "");
					}
				});
			}
		}
		function showTippp(item){
			var $task = getTaskNode(item);
			var $link = $task.find(".z-opt");
			$task.append('<img class="z-tipbb" src="../../images/more.png" style="position:absolute;z-index:9;" />');
			var $tipbb = $task.find(".z-tipbb");
			var leftdf = 169 - parseInt($link.css("width"))/2 - 13;
			$tipbb.css({
				top : ( $link.position().top + parseInt($link.css("height")) )+"px",
				left: ( $link.position().left - leftdf)+"px"
			});
		}

		function getTaskNode(task){
			var $task;
			if(task.host==""||task.host=="127.0.0.1"||task.host.toLocaleLowerCase()=="localhost"){
				$task = $(".z-local .z-file .z-task"); //默认文件
				switch (task.taskType) {
				case Task.TASK_TYPE.mysql: //mysql
					$task = $(".z-local .z-mysql .z-task");
					break;
				case Task.TASK_TYPE.mssql: //mssql
					$task = $(".z-local .z-mssql .z-task");
					break;
                case Task.TASK_TYPE.oracle: //oracle
                    $task = $(".z-local .z-oracle .z-task");
                    break;
				}
			}else{
				$task = $(".z-remote .z-task[taskid='"+task.taskId+"']"); //默认文件
			}
			return $task;
		}	

		/** 改变任务进度显示 */
		function updateView(task){
			if(!task) return;//参数为空
			var TASK_TYPE   = Task.TASK_TYPE;
			var TASK_STATE  = Task.TASK_STATE;//静态变量,任务状态

			var $task = getTaskNode(task);
			//存储任务信息
			$task.attr({
				taskId: task.taskId,
				taskType: task.taskType
			});
            if(parseInt(task.startTime)<=0 && parseInt(new Date().getTime()) < parseInt(task.startTime)*1000){
                return;
            }

			var scanSize = parseInt(task.scanSize);//扫描大小
			var totalSize = parseInt(task.totalSize);//总大小
			var progress = parseInt(scanSize * 100 / totalSize) || 0;//进度
			var changedSize = parseInt(task.changedSize) || 0;
			progress = Math.min(progress, 100);
			progress = Math.max(progress, 0);
			if(task.taskState == TASK_STATE.backupFile ||
				task.taskState == TASK_STATE.backupDb){
				if(progress >= 100){
					progress = 99;
				}				
			}
			switch(task.switchState){
			case Task.SWITCH_STATE.normal://任务打开正常状态
				$task.addClass('runing').removeClass('shut');
				//这里是备份页面,只显示跟备份相关的任务进度就可
				
				switch(task.taskState){
				case TASK_STATE.backupFinish: //完成 FinishTaskState
					var msg = "备份成功";
					if(task.errCode != 0){ //备份失败
						msg = task.errMsg || "备份失败";
					}
					$task.find(".z-tip").show().html(msg);
					$task.find(".z-progress").hide();
					break;
				case TASK_STATE.backupWait:// 等待备份任务 WaittingBackupTaskState
				case TASK_STATE.backupDb: //导出db ExportingDbTaskState
				case TASK_STATE.backupFile://备份文件中,更新进度 BackupFileTaskState
					progress = progress+"%";
					$task.find(".z-tip").hide();
					$task.find(".z-progress").show();
					$task.find(".plan").css("width", progress);
					$task.find(".text").text(progress);
					break;
				}
				$task.find(".z-opt").show();
				$task.find(".switch-ic").attr("title","关闭备份");
				break;
			case Task.SWITCH_STATE.close://任务关闭状态
			case Task.SWITCH_STATE.incomplete://任务不完整状态
				$task.addClass('shut').removeClass('runing');
				$task.find(".z-opt").hide();
				$task.find(".z-tip").show().text("关闭");
				$task.find(".switch-ic").attr("title","启动任务");
				break;				
			}
			$task.find(".z-time p").show();
			if(parseInt(task.startTime)>0){
				var date = new Date(parseInt(task.startTime)*1000);
                $task.find(".z-time p").show().text(date.format('yyyy-MM-dd hh:mm:ss'));
			}
            switch (task.taskType) {
                case TASK_TYPE.file: //文件
                    $task.find(".z-num p").show().html(task.changedFiles);
                    break;
                case TASK_TYPE.mysql: //mysql
                case TASK_TYPE.mssql: //mssql
                case TASK_TYPE.oracle: //oracle
                    $task.find(".z-num p").show().html("-");
                    break;
            }
            $task.find(".z-size p").show().html(dbfen.formatByte( changedSize ));//文件变化
		}
		function stopPropagation(e){
			e.stopPropagation();
			e.preventDefault();
		}
		function writeCookie(name, value){
			var expires = new Date();
				expires.setFullYear(expires.getFullYear() + 99); //保存99年
			var cookieConfig = {//cookie参数
				path: "/",
				expires: expires
			};
			$.cookie(name, value, cookieConfig);
		};
        /** 开启任务 */
        function openTask(task, obj){
            Task.open(task, function(result){
                switch(result.code){
                    case 0:
                        obj.addClass('runing').removeClass('shut');
                        obj.find(".z-tip").text('开启成功');
                        obj.find(".z-opt").show();
                        obj.find(".switch-ic span").text("关闭备份");
                        break;
                    default:
                        $.alert(result.msg || "开启备份失败");
                        break;
                }
            });
        };
		module.exports = Module;
	});
})();