define(function(require, exports, module) {
	var global = require("../../js/global");
	var jGlobal = require("./faultDiagGlobal");
	var selectDiagContent = require("./selectDiagContent");
	var selectDevice = require("./selectDevice");
	var upload = require("./upload");
	var deviceManage = require('../../deviceManage/js/deviceManage');
	
	var diagDirectorIns = null;
	var execOverallDiag = false;    //执行全面诊断的标志
	var overallDiagWarnCount = 0;   //全面深入诊断检测出的问题数
	var isClickOverallDiag = false; //全面深入诊断提示框, 用户是否点击过'确定'或'取消' 
	
	// 将警告信息描述拼接起来
	function buildWarnsubTitle(result) {
		var subTitle = {
			name: result.subTitle,
			descs: []
		};
		result.problems.forEach(function(item) {
			subTitle.descs.push(item.desc);
		});

		return subTitle;
	}

	function checkResultCallback(result, totalNum) {		
		if(jGlobal.faultDiag.curStatus != 'diagnosis') {
			return;
		}

		/* 更新诊断进度条 */
		jGlobal.faultDiag.diagCount++;
		if(totalNum > 0) {
			var percent = Math.floor((jGlobal.faultDiag.diagCount / totalNum) * 100);
			if((jGlobal.faultDiag.tmpDiagPercent == 0 && percent != 0) || ((percent - jGlobal.faultDiag.tmpDiagPercent) >= 5)) { //诊断的总数totalNum会发生变化				
				$("#diagnosis_progress").text(percent + '%');
				$("#diagnosis_progressBar").css('width', percent + '%');
				jGlobal.faultDiag.tmpDiagPercent = percent;
			}
		}

		/* 诊断结果(有些故障类型，如端口不能up需要分端口显示诊断结果) */
		var result = jGlobal.judgeDiagResultType(result);
		
		/* 全面深入诊断 */
		if (!jGlobal.faultDiag.flag && execOverallDiag) {
			var $div_overallwarn = "";
			$div_overallwarn += '<div class="diag-title" style="margin-bottom:5px; margin-top:8px ">深入诊断处理建议</div>';
			$div_overallwarn += '<div id="diag_overallwarn" class="panel-group" style="margin-bottom:15px; padding-right:15px;">';
			$div_overallwarn += '</div>';
			$("#diagResult").append($div_overallwarn);			
			
			jGlobal.faultDiag.flag = true;
		}
		if (execOverallDiag && result.level === "warn") {
			overallDiagWarnCount++;
			jGlobal.faultDiag.diagnoseResult.push(buildWarnsubTitle(result));

			var $div_warn_result = "";
				$div_warn_result += '<div class="panel panel-info">' +
				'<div class="panel-heading">' +
				'<div class="panel-title">' +
				'<img src="./image/warn.png" style="margin-right:2px;"></img>' +
				'<a data-toggle="collapse" data-parent=""' +
				'href="#collapse_overallwarn_' + overallDiagWarnCount + '"' + 'style="font-size:12px;">' +
				result.subTitle +
				'</a>' +
				'</div>' +
				'</div>' +
				'<div id="collapse_overallwarn_' + overallDiagWarnCount + '"' + 'class="panel-collapse collapse">' +
				'<div class="panel-body" style="font-size:12px;">';

			for (var i = 0; i < result.problems.length; i++) {
				$div_warn_result += '<div>' +
					'<img src="./image/red_circle.png" style="margin-left:3px;"></img>' +
					'<span>' +
					result.problems[i].desc.replace(/\r\n/g, '<br />').replace(/\t/g, '&nbsp;&nbsp;&nbsp;&nbsp;') +
					'</span>';

				if (result.problems[i].fixIns != undefined) {
					jGlobal.faultDiag.autoRepairCmds.push(result.problems[i].fixIns);
					jGlobal.faultDiag.backRepairCmds.push(result.problems[i].backIns);
					$div_warn_result +=
						'<div>' +
						'<span class="btn btn-success btn-xs" style="margin-top:2px; margin-left:55px;" onclick="autoReailClick(this)" addAttr=' + (jGlobal.faultDiag.autoRepairCmds.length - 1) + '>' +
						'自动修复' +
						'</span>' +
						'</div>';
				}

				$div_warn_result +=
					'</div>' +
					'<div style="margin-top:5px;">' +
					'<img src="./image/blue_circle.png" style="margin-left:3px;"></img>' +
					'<span>' +
					result.problems[i].advice.replace(/\r\n/g, '<br />').replace(/\t/g, '&nbsp;&nbsp;&nbsp;&nbsp;') +
					'</span>' +
					'</div>';
			}
			$div_warn_result += '</div></div></div>';
			
			$('#diag_overallwarn').append($div_warn_result);
		}
		
		/* 当前诊断项 */
		if (!execOverallDiag) {
			if (result.otherInfo == undefined) { //无需分端口显示的故障类型，如cpu异常冒高
				if (!jGlobal.faultDiag.flag) {
					var $div_title = "";
					$div_title += '<div class="diag-title">本次诊断结果</div>';
					$("#diagResult").append($div_title);
					
					var $div_warn = "";
					$div_warn += '<div style="width:100%; height:20px; line-height:20px; border-left: 4px solid #366ff5; font-size: 12px; color: #525252; padding-left: 15px; margin-bottom: 10px;">处理建议</div>';
					$div_warn += '<div id="diag_warn" class="panel-group" style="margin-bottom:0px; padding-right:15px;">';
					$div_warn += '</div>';
					$("#diagResult").append($div_warn);

					var $div_manual = "";
					$div_manual += '<div style="width:100%; height:20px; line-height:20px; border-left: 4px solid #366ff5; font-size: 12px; color: #525252; padding-left: 14px; margin-top: 20px; margin-bottom: 10px;">需协助判断</div>';
					$div_manual += '<div id="diag_manual" class="panel-group" style="margin-bottom:0px; padding-top:5px; padding-right:15px;">';
					$div_manual += '</div>';
					$("#diagResult").append($div_manual);

					var $div_success = "";
					$div_success += '<div style="width:100%; height:20px; line-height:20px; border-left: 4px solid #366ff5; font-size: 12px; color: #525252; padding-left: 15px; margin-top: 20px; margin-bottom: 10px;">已排查问题</div>';
                    $div_success += '<div id="diag_success" class="panel-group" style="margin-bottom:10px; padding-top:5px; padding-right:15px;">';
					$div_success += '</div>';
					$("#diagResult").append($div_success);
					
					jGlobal.faultDiag.flag = true;
				}

				//添加当前端口的warn和success结果至指定区域
				if (result.level === "warn") {
					jGlobal.faultDiag.totalWarnCount++;
					jGlobal.faultDiag.diagnoseResult.push(buildWarnsubTitle(result));

					var $div_warn_result = "";
					$div_warn_result += '<div class="panel panel-info">' +
						'<div class="panel-heading">' +
						'<div class="panel-title">' +
						'<img src="./image/warn.png" style="margin-right:2px;"></img>' +
						'<a data-toggle="collapse" data-parent=""' +
						'href="#collapse_warn_' + jGlobal.faultDiag.totalWarnCount + '"' + 'style="font-size:12px;">' +
						result.subTitle +
						'</a>' +
						'</div>' +
						'</div>' +
						'<div id="collapse_warn_' + jGlobal.faultDiag.totalWarnCount + '"' + 'class="panel-collapse collapse">' +
						'<div class="panel-body" style="font-size:12px;">';

					for (var i = 0; i < result.problems.length; i++) {
						$div_warn_result += '<div>' +
							'<img src="./image/red_circle.png" style="margin-left:3px;"></img>' +
							'<span>' +
							result.problems[i].desc.replace(/\r\n/g, '<br />').replace(/\t/g, '&nbsp;&nbsp;&nbsp;&nbsp;') +
							'</span>';

						if (result.problems[i].fixIns != undefined) {
							jGlobal.faultDiag.autoRepairCmds.push(result.problems[i].fixIns);
							jGlobal.faultDiag.backRepairCmds.push(result.problems[i].backIns);
							$div_warn_result +=
								'<div>' +
								'<span class="btn btn-success btn-xs" style="margin-top:2px; margin-left:55px;" onclick="autoReailClick(this)" addAttr=' + (jGlobal.faultDiag.autoRepairCmds.length - 1) + '>' +
								'自动修复' +
								'</span>' +
								'</div>';
						}

						$div_warn_result +=
							'</div>' +
							'<div style="margin-top:5px;">' +
							'<img src="./image/blue_circle.png" style="margin-left:3px;"></img>' +
							'<span>' +
							result.problems[i].advice.replace(/\r\n/g, '<br />').replace(/\t/g, '&nbsp;&nbsp;&nbsp;&nbsp;') +
							'</span>' +
							'</div>';
					}
					$div_warn_result += '</div></div></div>';
					
					$('#diag_warn').append($div_warn_result);
				} else if (result.level === "success") {
					jGlobal.faultDiag.successCount++;

					var $div_success_result = "";
					$div_success_result += '<div class="panel panel-info">' +
						'<div class="panel-heading">' +
						'<div class="panel-title">' +
						'<img src="./image/success.png" width="16" height="16" style="margin-right:2px;"></img>' +
						'<a data-toggle="collapse" data-parent=""' +
						'href="#collapse_success_' + jGlobal.faultDiag.successCount + '"' + 'style="font-size:12px; text-decoration: none; cursor: default;">' +
						result.subTitle +
						'</a>' +
						'</div>' +
						'</div>' +
						'</div>';

					$('#diag_success').append($div_success_result);
				} else if (result.level === "manual") {
					jGlobal.faultDiag.manualCount++;

					var $div_warn_manual = "";
					$div_warn_manual += '<div class="panel panel-info">' +
						'<div class="panel-heading">' +
						'<div class="panel-title">' +
						'<img src="./image/warn.png" style="margin-right:2px;"></img>' +
						'<a data-toggle="collapse" data-parent=""' +
						'href="#collapse_manual_' + jGlobal.faultDiag.manualCount + '"' + 'style="font-size:12px;">' +
						result.subTitle +
						'</a>' +
						'</div>' +
						'</div>' +
						'<div id="collapse_manual_' + jGlobal.faultDiag.manualCount + '"' + 'class="panel-collapse collapse">' +
						'<div class="panel-body" style="font-size:12px;">';

					$div_warn_manual += '<div>' +
						'<img src="./image/red_circle.png" style="margin-left:3px;"></img>' +
						'<span>' +
						result.problems[0].desc.replace(/\r\n/g, '<br />').replace(/\t/g, '&nbsp;&nbsp;&nbsp;&nbsp;') +
						'</span>';

					jGlobal.faultDiag.manualConfirmAdvice.push(result.problems[0].checkIns);
					
					$div_warn_manual += '<div style="margin-top:5px;">';
					var checkArray = result.problems[0].checkIns;
					for (var i = 0; i < checkArray.length; i++) {
						if (checkArray[i].advice != undefined) {
							$div_warn_manual += '<img src="../../common/image/blue_circle.png" style="margin-left:3px;"></img>' +
												'<span>' + checkArray[i].advice.replace(/\r\n/g, '<br />').replace(/\t/g, '&nbsp;&nbsp;&nbsp;&nbsp;') + '</span>';
						}
					}
					$div_warn_manual += '</div>' +
						'</div>';
					$div_warn_manual += '</div></div></div>';
					$('#diag_manual').append($div_warn_manual);
				}
			} else { //需要分端口显示的故障类型，如端口不能up
				if ($.inArray(result.otherInfo, jGlobal.faultDiag.portNameArray) === -1) {
					var id_portName = result.otherInfo.replace(/\s|\/|\:/g, '');
					jGlobal.faultDiag.portNameArray.push(result.otherInfo);

					// 对于不同的端口，创建各自的div来存储各端口的检测结果
					var $div = "";
					$div += '<div id=' + result.otherInfo.replace(/\s|\/|\:/g, '') + ' style="padding-bottom:20px;">';
					$div += '<div class="diag-title">端口<span style="margin-left:5px; margin-right:5px; color:#fff;">' + result.otherInfo + '</span>的检测结果:</div>';
					$div += '</div>';
					$("#diagResult").append($div);

					// 对存储各端口检测结果的div，再创建warn和success两个div来存储当前端口检测结果的warn和success消息
					var $div_warn = "";
					$div_warn += '<div style="width:100%; height:20px; line-height:20px; border-left: 4px solid #366ff5; font-size: 12px; color: #525252; padding-left: 15px; margin-bottom: 10px;">处理建议</div>';
					$div_warn += '<div id=' + result.otherInfo.replace(/\s|\/|\:/g, '') + '_warn' + ' class="panel-group mult-port-warn" style="margin-bottom:0px; padding-right:15px;">';
					$div_warn += '</div>';
					$('#' + result.otherInfo.replace(/\s|\/|\:/g, '')).append($div_warn);

					var $div_manual = "";
					$div_manual += '<div style="width:100%; height:20px; line-height:20px; border-left: 4px solid #366ff5; font-size: 12px; color: #525252; padding-left: 14px; margin-top: 20px; margin-bottom: 10px;">需协助判断</div>';
					$div_manual += '<div id=' + result.otherInfo.replace(/\s|\/|\:/g, '') + '_manual' + ' class="panel-group mult-port-manual" style="margin-bottom:0px; padding-top:5px; padding-right:15px;">';
					$div_manual += '</div>';
					$('#' + result.otherInfo.replace(/\s|\/|\:/g, '')).append($div_manual);

					var $div_success = "";
                    $div_success += '<div style="width:100%; height:20px; line-height:20px; border-left: 4px solid #366ff5; font-size: 12px; color: #525252; padding-left: 15px; margin-top: 20px; margin-bottom: 10px;">已排查问题</div>';
                    $div_success += '<div id=' + result.otherInfo.replace(/\s|\/|\:/g, '') + '_success' + ' class="panel-group mult-port-success" style="margin-bottom:0px; padding-top:5px; padding-right:15px;">';
					$div_success += '</div>';
					$('#' + result.otherInfo.replace(/\s|\/|\:/g, '')).append($div_success);
				}
				
				//添加当前端口的warn和success结果至指定区域
				if (result.level === "warn") {
					jGlobal.faultDiag.diagnoseResult.push(buildWarnsubTitle(result));
					jGlobal.faultDiag.totalWarnCount++;

					var $div_warn_result = "";
					$div_warn_result += '<div class="panel panel-info">' +
						'<div class="panel-heading">' +
						'<div class="panel-title">' +
						'<img src="./image/warn.png" style="margin-right:2px;"></img>' +
						'<a data-toggle="collapse" data-parent=""' +
						'href="#collapse_warn_' + jGlobal.faultDiag.totalWarnCount + '"' + 'style="font-size:12px;">' +
						result.subTitle +
						'</a>' +
						'</div>' +
						'</div>' +
						'<div id="collapse_warn_' + jGlobal.faultDiag.totalWarnCount + '"' + 'class="panel-collapse collapse">' +
						'<div class="panel-body" style="font-size:12px;">';

					for (var i = 0; i < result.problems.length; i++) {
						$div_warn_result += '<div>' +
							'<img src="./image/red_circle.png" style="margin-left:3px;"></img>' +
							'<span>' +
							result.problems[i].desc.replace(/\r\n/g, '<br />').replace(/\t/g, '&nbsp;&nbsp;&nbsp;&nbsp;') +
							'</span>';

						if (result.problems[i].checkIns != undefined) {
							jGlobal.faultDiag.manualConfirmAdvice.push(result.problems[i].checkIns);
							$div_warn_result += '<div style="margin-top:2px; margin-left:80px;">';
							for (var j = 0; j < result.problems[i].checkIns.length; j++) {
								$div_warn_result += '<input type="radio" name="option_' + jGlobal.faultDiag.manualConfirmAdvice.length + '" onclick="manualConfirmClick(this)" style="margin-left:5px;" addAttr=' + (jGlobal.faultDiag.manualConfirmAdvice.length - 1) + '>' +
									'<span style="margin-left:1px;">' + result.problems[i].checkIns[j].checkItem + '</span>';
							}
							$div_warn_result += '</div>' +
								'</div>';
						} else {
							if (result.problems[i].fixIns != undefined) {
								jGlobal.faultDiag.autoRepairCmds.push(result.problems[i].fixIns);
								jGlobal.faultDiag.backRepairCmds.push(result.problems[i].backIns);
								$div_warn_result +=
									'<div>' +
									'<span class="btn btn-success btn-xs" style="margin-top:2px; margin-left:55px;" onclick="autoReailClick(this)" addAttr=' + (jGlobal.faultDiag.autoRepairCmds.length - 1) + '>' +
									'自动修复' +
									'</span>' +
									'</div>';
							}

							$div_warn_result +=
								'</div>' +
								'<div style="margin-top:5px;">' +
								'<img src="./image/blue_circle.png" style="margin-left:3px;"></img>' +
								'<span>' +
								result.problems[i].advice.replace(/\r\n/g, '<br />').replace(/\t/g, '&nbsp;&nbsp;&nbsp;&nbsp;') +
								'</span>' +
								'</div>';
						}
					}
					$div_warn_result += '</div></div></div>';

					$('#' + result.otherInfo.replace(/\s|\/|\:/g, '') + '_warn').append($div_warn_result);
				} else if (result.level === "success") {
					jGlobal.faultDiag.successCount++;

					var $div_success_result = "";
					$div_success_result += '<div class="panel panel-info">' +
						'<div class="panel-heading">' +
						'<div class="panel-title">' +
						'<img src="./image/success.png" width="16" height="16" style="margin-right:2px;"></img>' +
						'<a data-toggle="collapse" data-parent=""' +
						'href="#collapse_success_' + jGlobal.faultDiag.successCount + '"' + 'style="font-size:12px;  text-decoration: none; cursor: default;">' +
						result.subTitle +
						'</a>' +
						'</div>' +
						'</div>' +
						'</div>';

					$('#' + result.otherInfo.replace(/\s|\/|\:/g, '') + '_success').append($div_success_result);
				} else if (result.level === "manual") {
					jGlobal.faultDiag.manualCount++;

					var $div_warn_manual = "";
					$div_warn_manual += '<div class="panel panel-info">' +
						'<div class="panel-heading">' +
						'<div class="panel-title">' +
						'<img src="./image/warn.png" style="margin-right:2px;"></img>' +
						'<a data-toggle="collapse" data-parent=""' +
						'href="#collapse_manual_' + jGlobal.faultDiag.manualCount + '"' + 'style="font-size:12px;">' +
						result.subTitle +
						'</a>' +
						'</div>' +
						'</div>' +
						'<div id="collapse_manual_' + jGlobal.faultDiag.manualCount + '"' + 'class="panel-collapse collapse">' +
						'<div class="panel-body" style="font-size:12px;">';

					$div_warn_manual += '<div>' +
						'<img src="./image/red_circle.png" style="margin-left:3px;"></img>' +
						'<span>' +
						result.problems[0].desc.replace(/\r\n/g, '<br />').replace(/\t/g, '&nbsp;&nbsp;&nbsp;&nbsp;') +
						'</span>';

					jGlobal.faultDiag.manualConfirmAdvice.push(result.problems[0].checkIns);
					
//					$div_warn_manual += '<div style="margin-top:2px; margin-left:80px;">';
//					for (var j = 0; j < result.problems[0].checkIns.length; j++) {
//						$div_warn_manual += '<input type="radio" name="option_' + jGlobal.faultDiag.manualConfirmAdvice.length + '" onclick="manualConfirmClick(this)" style="margin-left:5px;" addAttr=' + (jGlobal.faultDiag.manualConfirmAdvice.length - 1) + '>' +
//							'<span style="margin-left:1px;">' + result.problems[0].checkIns[j].checkItem + '</span>';
//					}
//					$div_warn_manual += '</div>' +
//						'</div>';					
					
					$div_warn_manual += '<div style="margin-top:5px;">';
					var checkArray = result.problems[0].checkIns;				
					for (var i = 0; i < checkArray.length; i++) {
						if (checkArray[i].advice != undefined) {
							$div_warn_manual += '<img src="../../common/image/blue_circle.png" style="margin-left:3px;"></img>' +
												'<span>' + checkArray[i].advice.replace(/\r\n/g, '<br />').replace(/\t/g, '&nbsp;&nbsp;&nbsp;&nbsp;') + '</span>';
						}
					}					
					$div_warn_manual += '</div>' +
						'</div>';
					$div_warn_manual += '</div></div></div>';
					$('#' + result.otherInfo.replace(/\s|\/|\:/g, '') + '_manual').append($div_warn_manual);
				}
			}
		}
	}

	var diffTime = 0; //用户点击确定或取消，跟alert显示出来的时间差(扣除这个时间才是真正诊断的时间)
	function checkEnd(obj) {
		console.log("-------------------diag end---------------------");

		if (jGlobal.faultDiag.curStatus != 'diagnosis') {
			return;
		}
		jGlobal.faultDiag.curStatus = jGlobal.changeDevStatus(jGlobal.faultDiag.curStatus, 'connected');
		
		global.tftpOperateInstance.changeDirName(jGlobal.faultDiag.collectDevName[0]);
		
		if (!execOverallDiag) {
			$("#dlg_diagnosis").modal('hide');
			
			var beforeClickTime = global.moment();
			
			//如果当前诊断项本身已经是深入诊断(全面诊断),不再提示用户是否再进行深入诊断
			console.error(jGlobal.faultDiag.typeName);
			if (jGlobal.faultDiag.typeName == "全面诊断" || jGlobal.faultDiag.typeName == "深入检测") {				
				_actionAfterDiag(0);
				return;
			}
			
			//全面深入诊断
			alert(undefined, "当前诊断完成, 是否需要启动深入诊断?", function() {
				var afterClickTime = global.moment();
				diffTime = afterClickTime.diff(beforeClickTime);
				
				if (jGlobal.faultDiag.curSelectNode.overallDiag == null) {
					setTimeout(function() {
						alert(undefined, "当前设备类型的配置文件未添加全面诊断项！");
					}, 500);
					_actionAfterDiag(diffTime);
					return;
				}
				
				$("#dlg_diagnosis").modal('show');
				execOverallDiag = true;
				isClickOverallDiag = true;
				jGlobal.faultDiag.flag = false;
				
				/* 初始化进度条相关 */
				jGlobal.faultDiag.diagCount = 0;
				jGlobal.faultDiag.tmpDiagPercent = 0;
				$("#diagnosis_progress").text('0%');
				$("#diagnosis_progressBar").css('width', '0%');
				
				/* 重新调用诊断接口 */
				jGlobal.faultDiag.curStatus = jGlobal.changeDevStatus(jGlobal.faultDiag.curStatus, 'diagnosis');
				diagDirectorIns = new global.diagDirector.DiagDirector();
				diagDirectorIns.setBasedInfo({
					devMgr: global.devicesIns,
					deviceName: jGlobal.faultDiag.collectDevName[0]
				});
				registDiagEvent(diagDirectorIns);
				
				var scriptErr = diagDirectorIns.doDiag(jGlobal.faultDiag.curSelectNode.overallDiag, undefined, jGlobal.faultDiag.diagSavePath);
				if (scriptErr == false) {
					if(jGlobal.faultDiag.curStatus != 'closing' && jGlobal.faultDiag.curStatus != 'init') {
						jGlobal.faultDiag.curStatus = jGlobal.changeDevStatus(jGlobal.faultDiag.curStatus, 'connected');
					}
					setTimeout(function() {
						execOverallDiag = false;       //变量不改回来也可以
						jGlobal.faultDiag.flag = true; //变量不改回来也可以
						alert(undefined, "当前设备类型的全面诊断脚本还未添加！");
					}, 500);
					_actionAfterDiag(diffTime);
				}
			}, true, function() {
				isClickOverallDiag = true;
				var afterClickTime = global.moment();
				diffTime = afterClickTime.diff(beforeClickTime);
				
				_actionAfterDiag(diffTime);
			});
		} else {
			_actionAfterDiag(diffTime);
		}
		
		function _actionAfterDiag(diffTime) {
            if (jGlobal.faultDiag.totalWarnCount == 0) {
                if (overallDiagWarnCount == 0) {
                    $("#diag_warn").append('<span style="font-size: 12px; margin-left: 18px;">未发现问题,请执行一键收集帮助定位故障</span>');
                } else {
                    $("#diag_warn").append('<span style="font-size: 12px; margin-left: 18px;">请查看深入诊断结果确定问题是否解决,若未能定位,请执行一键收集</span>');
                }
				
//				$(".diagResultContent").children().each(function() {
//					var id = $(this).attr("id") + "_warn";
//					$("#" + id).append('<span style="font-size: 12px; margin-left: 20px;">无</span>');
//				});
				$(".mult-port-warn").each(function() {
                    $(this).append('<span style="font-size: 12px; margin-left: 20px;">未发现问题</span>');
				});
			}
			if (jGlobal.faultDiag.successCount == 0) {
                $("#diag_success").append('<span style="font-size: 12px; margin-left: 20px;">无</span>');
//				$(".diagResultContent").children().each(function() {
//					var id = $(this).attr("id") + "_success";
//					$("#" + id).append('<span style="font-size: 12px; margin-left: 20px;">无</span>');
//				});
				$(".mult-port-success").each(function() {
                    $(this).append('<span style="font-size: 12px; margin-left: 20px;">无</span>');
				});
			}
			if (jGlobal.faultDiag.manualCount == 0) {
                $("#diag_manual").append('<span style="font-size: 12px; margin-left: 20px;">无</span>');
//				$(".diagResultContent").children().each(function() {
//					var id = $(this).attr("id") + "_manual";
//					$("#" + id).append('<span style="font-size: 12px; margin-left: 20px;">无</span>');
//				});
				$(".mult-port-manual").each(function() {
                    $(this).append('<span style="font-size: 12px; margin-left: 20px;">无</span>');
				});
			}
			if (overallDiagWarnCount == 0) {
                $("#diag_overallwarn").append('<span style="font-size: 12px; margin-left: 20px;">未发现问题,请执行一键收集帮助定位故障</span>');
			}

			/* 更新诊断进度条 */
			$("#diagnosis_progress").text('100%');
			$("#diagnosis_progressBar").css('width', '100%');
			$("#cancelDiagnosis").text("完成");
			$("#cancelDiagnosis").removeClass("btn-force-cancel");
			$("#cancelDiagnosis").addClass("btn-complete");
			$("#diagResultText").text("诊断完成.");
			
			/* 显示诊断时长 */
			jGlobal.faultDiag.endTime_diag = global.moment();
			var realEndTime_diag = jGlobal.faultDiag.endTime_diag.subtract(diffTime/1000, 'seconds');
			
			jGlobal.showTime(jGlobal.faultDiag.startTime_diag, realEndTime_diag, "#min_time_diag", "#sec_time_diag");
			$("#diagTime").show();
			$("#diagResultText").show();
			
			/* 更新步骤进度 */
			$(".curStepText div:last-child").addClass('strongCurStepDiv');
			$(".curStepIcon div:nth-last-child(2)").addClass('strongStepLine');
			$(".curStepIcon div:nth-last-child(1) img").attr('src', './image/step-icon-on.png');

			var uploadParam = {};			
			uploadParam.diagnoseId = jGlobal.faultDiag.diagnoseId;
			uploadParam.dataType = "faultDiagnose";
			uploadParam.curAction = "diagnosis";
			uploadParam.actionResult = JSON.stringify(jGlobal.faultDiag.diagnoseResult);
			uploadParam.duration = parseInt((realEndTime_diag - jGlobal.faultDiag.startTime_diag) / 1000);
			uploadParam.isResolved = "F"; //F表示完整的走完一次诊断
			jGlobal.uploadInfoToCloud(uploadParam);

			if (jGlobal.faultDiag.totalWarnCount == 0) {
				var uploadParam = {};
				uploadParam.diagnoseId = jGlobal.faultDiag.diagnoseId;
				uploadParam.dataType = "faultDiagnose";
				uploadParam.curAction = "diagnosis";
				uploadParam.actionResult = JSON.stringify(jGlobal.faultDiag.diagnoseResult);
				uploadParam.duration = parseInt((realEndTime_diag - jGlobal.faultDiag.startTime_diag) / 1000);
				uploadParam.isResolved = "U"; //U表示完整的走完一次诊断后没有诊断出问题
				jGlobal.uploadInfoToCloud(uploadParam);
			}

//			for(var i = 1; i <= jGlobal.faultDiag.totalWarnCount; i++) {
//				var collapseId = "#collapse_" + i;
//				$(collapseId).collapse('hide');
//			}
		}
	}

	/* 当前正常状态:init closing diagnose */
	function cancelDiagnosis() {
		if($("#cancelDiagnosis").text() == "强制取消") {
			jGlobal.faultDiag.isClickCancel = true;

			if(jGlobal.faultDiag.curStatus != 'closing' && jGlobal.faultDiag.curStatus != 'init') {
				jGlobal.faultDiag.curStatus = jGlobal.changeDevStatus(jGlobal.faultDiag.curStatus, 'closing');

				diagDirectorIns.stop();
				global.devicesIns.closeDeviceLink(jGlobal.faultDiag.collectDevName[0]);

				jGlobal.faultDiag.endTime_diag = global.moment();

				var uploadParam = {};
				uploadParam.diagnoseId = jGlobal.faultDiag.diagnoseId;
				uploadParam.dataType = "faultDiagnose";
				uploadParam.curAction = "diagnosis";
				uploadParam.actionResult = "";
				uploadParam.duration = parseInt((jGlobal.faultDiag.endTime_diag - jGlobal.faultDiag.startTime_diag) / 1000);
				uploadParam.isResolved = "NA";
				jGlobal.uploadInfoToCloud(uploadParam);
			}
		} else if($("#cancelDiagnosis").text() == "完成") {
			if(jGlobal.faultDiag.curStatus != 'closing' && jGlobal.faultDiag.curStatus != 'init') {
				jGlobal.faultDiag.curStatus = jGlobal.changeDevStatus(jGlobal.faultDiag.curStatus, 'connected');
			}
		}
	}

	//当前正常状态connected closing init
	function autoReailClick(self) {
		if(jGlobal.faultDiag.curStatus == "connecting" || jGlobal.faultDiag.curStatus == "collect" || jGlobal.faultDiag.curStatus == "diagnosis") {
			return;
		}

		if(jGlobal.faultDiag.curStatus == "closing") {
			alert(undefined, "设备正在断开连接，无法修复，请等连接断开后重新连接设备！");
			return;
		} else if(jGlobal.faultDiag.curStatus == "init") {
			alert(undefined, "设备已断开连接，无法修复，请重新连接设备！");
			return;
		}

		if(jGlobal.faultDiag.curStatus == "connected") {
			jGlobal.faultDiag.curStatus = jGlobal.changeDevStatus(jGlobal.faultDiag.curStatus, 'repair');

			var tmpRepairPercent = 0;
			var repairCurCmd = "";
			var repairCmdHistory = [];

			$("#repair_progress").text('0%');
			$("#repair_progressBar").css('width', '0%');
			$("#cancelRepair").text("强制取消");
			$("#cancelRepair").removeClass("btn-complete");
			$("#cancelRepair").addClass("btn-force-cancel");
			$("#repairResultText").hide();
			$("#repairTime").hide();

			global.diagFixerIns = new global.diagFixer();
			global.diagFixerIns.setBasedInfo({
				devMgr: global.devicesIns,
				deviceName: jGlobal.faultDiag.collectDevName[0],
				logPath: jGlobal.faultDiag.diagSavePath
			});

			var fixIndex = parseInt($(self).attr('addAttr'));
			var fixIns = jGlobal.faultDiag.autoRepairCmds[fixIndex];
			console.log(fixIns);

			$("#dlg_repairProgress").modal('show');
			jGlobal.faultDiag.startTime_repair = global.moment();
			//			$("#txtRepairAllCmd").html(fixIns.fixCmds.join('<br>'));

			global.diagFixerIns.fix(fixIns, function(err, cmd, res, curIndex, totalNum) {
				if(err != null) {
					alert(undefined, "修复失败！");
					$("#cancelRepair").text("完成");
					$("#cancelRepair").removeClass("btn-force-cancel");
					$("#cancelRepair").addClass("btn-complete");
					$("#repairResultText").text("修复失败.");
					$("#repairResultText").show();

					jGlobal.faultDiag.endTime_repair = global.moment();
					jGlobal.showTime(jGlobal.faultDiag.startTime_repair, jGlobal.faultDiag.endTime_repair, "#min_time_repair", "#sec_time_repair");
					$("#repairTime").show();

					var $div = '<span class="label label-success" style="margin-top:2px; margin-left:55px; font-size:11px;">' + '修复失败' + '</span>' +
						'<span class="btn btn-danger" style="margin-left:5px; font-size:11px; padding:0px 10px; border-radius:2px;" onclick="backRepairClick(this)" addAttr=' + fixIndex + '>' +
						'回退' +
						'</span>';
					$(self).parent().append($div);
					$(self).remove();
					return;
				}

				//            console.log('当前修复第' + curIndex + '条命令');
				//            console.log('一共有' + totalNum +'条命令');
				//            console.log('当前执行命令:' + cmd);
				//            console.log('设备响应内容:' + res);

				/* 修复命令、修复回显内容显示 */
				repairCurCmd = "当前修复的命令:" + '<span>' + cmd + '</span>';
				$("#txtRepairCurCmd").html(repairCurCmd);
				$("#txtRepairCmdHistory").html(repairCmdHistory.join('<br>'));
				repairCmdHistory.unshift(cmd);

				/* 更新修复进度条 */
				var percent = Math.floor((curIndex / totalNum) * 100);
				if((tmpRepairPercent == 0 && percent != 0) || ((percent - tmpRepairPercent) >= 5)) {
					$("#repair_progress").text(percent + '%');
					$("#repair_progressBar").css('width', percent + '%');
					tmpRepairPercent = percent;
				}

				if(curIndex == totalNum) {
					console.log('修复结束: 修复成功');

					$("#repair_progress").text('100%');
					$("#repair_progressBar").css('width', '100%');
					$("#cancelRepair").text("完成");
					$("#cancelRepair").removeClass("btn-force-cancel");
					$("#cancelRepair").addClass("btn-complete");
					$("#repairResultText").text("修复成功.");
					$("#repairResultText").show();
					jGlobal.faultDiag.endTime_repair = global.moment();
					jGlobal.showTime(jGlobal.faultDiag.startTime_repair, jGlobal.faultDiag.endTime_repair, "#min_time_repair", "#sec_time_repair");
					$("#repairTime").show();

					$("#txtRepairCmdHistory").html(repairCmdHistory.join('<br>'));
					$("#txtRepairCurCmd").html("当前修复的命令:<span>无</span>");

					var $div = '<span class="label label-success" style="margin-top:2px; margin-left:55px; font-size:11px;">' + '已修复' + '</span>' +
						'<span class="btn btn-danger" style="margin-left:5px; font-size:11px; padding:0px 10px; border-radius:2px;" onclick="backRepairClick(this)" addAttr=' + fixIndex + '>' +
						'回退' +
						'</span>';
					$(self).parent().append($div);
					$(self).remove();
				}
			});
		}
	}

	//当前正常状态closing init repair
	function cancelRepair() {
		if($("#cancelRepair").text() == "强制取消") {
			if(jGlobal.faultDiag.curStatus == 'repair') {
				jGlobal.faultDiag.curStatus = jGlobal.changeDevStatus(jGlobal.faultDiag.curStatus, 'closing');

				global.diagFixerIns.abort();
				global.devicesIns.closeDeviceLink(jGlobal.faultDiag.collectDevName[0]);
			}
		} else if($("#cancelRepair").text() == "完成") {
			if(jGlobal.faultDiag.curStatus == 'repair') {
				jGlobal.faultDiag.curStatus = jGlobal.changeDevStatus(jGlobal.faultDiag.curStatus, 'connected');
			}
		}
	}

	function backRepairClick(self) {
		if(jGlobal.faultDiag.curStatus == "connecting" || jGlobal.faultDiag.curStatus == "collect" || jGlobal.faultDiag.curStatus == "diagnosis") {
			return;
		}

		if(jGlobal.faultDiag.curStatus == "closing") {
			alert(undefined, "设备正在断开连接，无法回退，请等连接断开后重新连接设备！");
			return;
		} else if(jGlobal.faultDiag.curStatus == "init") {
			alert(undefined, "设备已断开连接，无法回退，请重新连接设备！");
			return;
		}

		if(jGlobal.faultDiag.curStatus == "connected") {
			jGlobal.faultDiag.curStatus = jGlobal.changeDevStatus(jGlobal.faultDiag.curStatus, 'backRepair');

			var tmpbackRepairPercent = 0;
			var backrepairCurCmd = "";
			var backrepairCmdHistory = [];

			$("#back_progress").text('0%');
			$("#back_progressBar").css('width', '0%');
			$("#cancelBack").text("强制取消");
			$("#cancelBack").removeClass("btn-complete");
			$("#cancelBack").addClass("btn-force-cancel");
			$("#cancelBackText").show();
			$("#backResultText").hide();
			$("#backTime").hide();

			global.diaRollbackerIns = new global.diaRollbacker();
			global.diaRollbackerIns.setBasedInfo({
				devMgr: global.devicesIns,
				deviceName: jGlobal.faultDiag.collectDevName[0],
				logPath: jGlobal.faultDiag.diagSavePath
			});

			var backIndex = parseInt($(self).attr('addAttr'));
			var backIns = jGlobal.faultDiag.backRepairCmds[backIndex];
			console.log(backIns);

			$("#dlg_backProgress").modal('show');
			jGlobal.faultDiag.startTime_back = global.moment();
			//			$("#txtBackAllCmd").html(backIns.backCmds.join('<br>'));

			global.diaRollbackerIns.rollback(backIns, function(err, cmd, res, curIndex, totalNum) {
				if(err != null) {
					alert(undefined, "回退失败！");
					$("#cancelBack").text("完成");
					$("#cancelBack").removeClass("btn-force-cancel");
					$("#cancelBack").addClass("btn-complete");
					$("#backResultText").text("回退失败.");
					$("#backResultText").show();

					jGlobal.faultDiag.endTime_back = global.moment();
					jGlobal.showTime(jGlobal.faultDiag.startTime_back, jGlobal.faultDiag.endTime_back, "#min_time_back", "#sec_time_back");
					$("#backTime").show();

					var $div = '<span class="label label-success" style="margin-top:2px; margin-left:55px; font-size:11px;">' + '回退失败' + '</span>';
					$(self).prev().remove();
					$(self).parent().append($div);
					$(self).remove();
					return;
				}

				//            console.log('当前修复第' + curIndex + '条命令');
				//            console.log('一共有' + totalNum +'条命令');
				//            console.log('当前执行命令:' + cmd);
				//            console.log('设备响应内容:' + res);

				/* 修复命令、修复回显内容显示 */
				backrepairCurCmd = "当前回退的命令:" + '<span>' + cmd + '</span>';
				$("#txtBackCurCmd").html(backrepairCurCmd);
				$("#txtBackCmdHistory").html(backrepairCmdHistory.join('<br>'));
				backrepairCmdHistory.unshift(cmd);

				/* 更新修复进度条 */
				var percent = Math.floor((curIndex / totalNum) * 100);
				if((tmpbackRepairPercent == 0 && percent != 0) || ((percent - tmpbackRepairPercent) >= 5)) {
					$("#back_progress").text(percent + '%');
					$("#back_progressBar").css('width', percent + '%');
					tmpbackRepairPercent = percent;
				}

				if(curIndex == totalNum) {
					console.log('回退结束: 回退成功');

					$("#back_progress").text('100%');
					$("#back_progressBar").css('width', '100%');
					$("#cancelBack").text("完成");
					$("#cancelBack").removeClass("btn-force-cancel");
					$("#cancelBack").addClass("btn-complete");
					$("#backResultText").text("回退成功.");
					$("#backResultText").show();
					jGlobal.faultDiag.endTime_back = global.moment();
					jGlobal.showTime(jGlobal.faultDiag.startTime_back, jGlobal.faultDiag.endTime_back, "#min_time_back", "#sec_time_back");
					$("#backTime").show();

					$("#txtBackCmdHistory").html(backrepairCmdHistory.join('<br>'));
					$("#txtBackCurCmd").html("当前回退的命令:<span>无</span>");

					var $div = '<span class="label label-success" style="margin-top:2px; margin-left:55px; font-size:11px;">' + '回退成功' + '</span>';
					$(self).prev().remove();
					$(self).parent().append($div);
					$(self).remove();
				}
			});
		}
	}

	function cancelBackRepair() {
		if($("#cancelBack").text() == "强制取消") {
			if(jGlobal.faultDiag.curStatus == 'backRepair') {
				jGlobal.faultDiag.curStatus = jGlobal.changeDevStatus(jGlobal.faultDiag.curStatus, 'closing');

				global.diaRollbackerIns.abort();
				global.devicesIns.closeDeviceLink(jGlobal.faultDiag.collectDevName[0]);
			}
		} else if($("#cancelBack").text() == "完成") {
			if(jGlobal.faultDiag.curStatus == 'backRepair') {
				jGlobal.faultDiag.curStatus = jGlobal.changeDevStatus(jGlobal.faultDiag.curStatus, 'connected');
			}
		}
	}

	function manualConfirmClick(self) {
		$(self).parent().next().remove();

		var checkArray = jGlobal.faultDiag.manualConfirmAdvice[parseInt($(self).attr('addAttr'))];
		for(var i = 0; i < checkArray.length; i++) {
			if(checkArray[i].checkItem == $(self).next().text()) {
				if(checkArray[i].advice != undefined) {
					var $div = '<div style="margin-top:5px;">' +
						'<img src="../../common/image/blue_circle.png" style="margin-left:3px;"></img>' +
						'<span>' +
						checkArray[i].advice.replace(/\r\n/g, '<br />').replace(/\t/g, '&nbsp;&nbsp;&nbsp;&nbsp;')
					'</span>' +
					'</div>';
					$(self).parent().parent().append($div);

					break;
				}
			}
		}
	}

	function uploadIsResolvedIssue(isResovledSign) {
		var uploadParam = {};
		uploadParam.diagnoseId = jGlobal.faultDiag.diagnoseId;
		uploadParam.dataType = "faultDiagnose";
		uploadParam.curAction = "diagnosis";
		uploadParam.actionResult = JSON.stringify(jGlobal.faultDiag.diagnoseResult);
		uploadParam.duration = parseInt((jGlobal.faultDiag.endTime_diag - jGlobal.faultDiag.startTime_diag) / 1000);
		uploadParam.isResolved = isResovledSign;
		jGlobal.uploadInfoToCloud(uploadParam);
	}
	
	function registDiagEvent(diagDirectorIns) {
		var newDiagDirectorIns = diagDirectorIns;
		var diagCurCmd = "";
		var diagCmdHistory = [];
		
		newDiagDirectorIns.on('diag_start', function(diagName) {
			diagCurCmd = "当前诊断项目:" + '<span>' + diagName + '</span>';
			$("#txtDiagCurCmd").html(diagCurCmd);
			diagCmdHistory.push("诊断项目:" + '<span>' + diagName + '</span>');
		});
		newDiagDirectorIns.on('cmd_exec', function(cmd) {			
			$("#txtDiagCmdHistory").html(diagCmdHistory.join('<br>'));
			diagCmdHistory.push("诊断命令:" + '<span>' + cmd + '</span>');

			//收到新的内容，将滚动条置底
			$('#diagScroll').scrollTop($('#diagScroll')[0].scrollHeight);
		});
		newDiagDirectorIns.on('check_end', function(obj) {
			$("#txtDiagCmdHistory").html(diagCmdHistory.join('<br>'));
			$("#txtDiagCurCmd").html("当前诊断的项目:<span>无</span>");

			//收到新的内容，将滚动条置底
			$('#diagScroll').scrollTop($('#diagScroll')[0].scrollHeight);
		});
		
		newDiagDirectorIns.on('check_result', checkResultCallback);
		newDiagDirectorIns.on('check_end', checkEnd);
	}

	function init() {
		initWindowEvent();
		initPageStatistic();
		initVariable();
		initDom();
		removeGlobalEvent();
		initEvent();
		initGlobalEvent();
		initGuide();

		function initGuide() {
			if(global.guide) {
				$('#red-point').css({
					display: 'block',
					top: '545px',
					left: '250px'
				});
			}
		}

		function initWindowEvent() {
			window.cancelDiagnosis = cancelDiagnosis;
			window.cancelRepair = cancelRepair;
			window.cancelBackRepair = cancelBackRepair;
			window.manualConfirmClick = manualConfirmClick;
			window.autoReailClick = autoReailClick;
			window.backRepairClick = backRepairClick;
		}

		function initPageStatistic() {
			window.statRecordEle("faultDiag#diagEnd");
		}

		function initVariable() {
			jGlobal.faultDiag.isClickResolved = false;
			jGlobal.faultDiag.isClickCancel = false;
			
			diagDirectorIns = null;
			execOverallDiag = false;
			overallDiagWarnCount = 0;
			isClickOverallDiag = false;
		}

		function initDom() {
			$('#dlg_diagnosis').modal({
				backdrop: 'static'
			});
			$('#dlg_repairProgress').modal({
				backdrop: 'static',
				show: false
			});
			$('#dlg_backProgress').modal({
				backdrop: 'static',
				show: false
			});
		}

		function removeGlobalEvent() {
			global.devicesIns.removeAllListeners("deviceConnected");
			global.devicesIns.removeAllListeners("deviceError");
			global.devicesIns.removeAllListeners("deviceDisconnected");

			/* diagDirectorIns每一次都是重新new, 可以不用移除事件 */
//			global.diagDirectorIns.removeAllListeners("check_result");
//			global.diagDirectorIns.removeAllListeners("check_end");
//
//			global.diagDirectorIns.removeAllListeners("diag_start");
//			global.diagDirectorIns.removeAllListeners("cmd_exec");
//			global.diagDirectorIns.removeAllListeners("check_end");
		}

		function initEvent() {
			$("#reConnect").click(function() {
				var connectStatus = global.devicesIns.getDeviceStatus(jGlobal.faultDiag.collectDevName[0]);
				//				console.log(connectStatus);
				if(connectStatus == "notConnected") {
					var row = {};
					row.deviceName = jGlobal.faultDiag.collectDevName[0];
					selectDevice.collectClick(row);
				} else {
					alert(undefined, "设备已连上，无需重新连接！");
				}
			});

			$('#uploadModal').on('show.bs.modal', function() {
				$('#uploadModal .modal-body').load("./faultDiagMenu/html/upload.html", function() {
					var productType = global.tftpOperateInstance.checkProductType(jGlobal.faultDiag.collectDevName[0]);
					var emailSubject = $("#uploadFaultId").text() + " + " + productType.deviceType + " + " + jGlobal.faultDiag.typeName + "。";
					upload.setEmailSubject(emailSubject);

					var curUploadParams = {};
					curUploadParams.deviceName = jGlobal.faultDiag.collectDevName[0];
					curUploadParams.logParams = null;
					upload.setUploadParams(curUploadParams);
				});
			});

			$('#uploadModal .claim>span').click(function() {
				$('#claimModal').modal('show');
			});

			$("#diagBack").click(function() {
				//				if (jGlobal.faultDiag.curStatus == 'connecting' || jGlobal.faultDiag.curStatus == 'collect' || jGlobal.faultDiag.curStatus == 'diagnosis') {
				//		            return;
				//		        }
				//				if (jGlobal.faultDiag.curStatus == 'init') {
				//					$(".main_content").load("./faultDiagMenu/html/faultDiagMenu.html");
				//				}
				//				if (jGlobal.faultDiag.curStatus == 'connected' || jGlobal.faultDiag.curStatus == 'closing') {
				//					jGlobal.faultDiag.curStatus = jGlobal.changeDevStatus(jGlobal.faultDiag.curStatus, 'closing');	            
				//					global.devicesIns.closeDeviceLink(jGlobal.faultDiag.collectDevName[0]);
				//					$(".main_content").load("./faultDiagMenu/html/faultDiagMenu.html");
				//				}

				var curElement = ".main_content",
					nextPageUrl = "./faultDiagMenu/html/faultDiagMenu.html";
				global.enterPageCallback(curElement, nextPageUrl);
			});

			$("#openDiagLogDir").click(function() {
				global.jsUtil.openDir(jGlobal.faultDiag.diagSavePath);
			});

			$("#oneCollect").click(function() {
				jGlobal.faultDiag.isLoadFromDiag = true;

				var connectStatus = global.devicesIns.getDeviceStatus(jGlobal.faultDiag.collectDevName[0]);
				if(connectStatus == "connected") {
					$("#checkDevEnvModal").modal('show');
					global.tftpOperateInstance.getCpuUsingRate(jGlobal.faultDiag.collectDevName[0], selectDiagContent.getCpuUsingRateCallback);
				} else {
					alert(undefined, "设备断开，请重新连接设备！");
				}
			});

			/* 现在已无用 */
			//			$('#yes_solveIssue').click(function() {
			//				jGlobal.faultDiag.isClickResolved = true;				
			//				uploadIsResolvedIssue('Y');		//Y表示解决问题
			//			});			
			//			
			//			$('#no_solveIssue').click(function() {
			//				jGlobal.faultDiag.isClickResolved = true;				
			//				uploadIsResolvedIssue('N');		//N表示未解决问题
			//			});

			global.devicesIns.on("deviceConnected", function(devName) {
				$('#connectDevModal').modal('hide');

				if (jGlobal.faultDiag.curStatus != 'connecting') {
					return;
				}
				jGlobal.faultDiag.curStatus = jGlobal.changeDevStatus(jGlobal.faultDiag.curStatus, 'connected');
			});

			global.devicesIns.on("deviceError", function(res) {
				$('#connectDevModal').modal('hide');
				
				if (jGlobal.faultDiag.curStatus == 'closing' || jGlobal.faultDiag.curStatus == 'init') {
					return;
				}

				if (jGlobal.faultDiag.curStatus == "diagnosis") {
					diagDirectorIns.stop();
					$("#cancelDiagnosis").text("完成");
					$("#cancelDiagnosis").removeClass("btn-force-cancel");
					$("#cancelDiagnosis").addClass("btn-complete");
					$("#diagResultText").text("连接断开,诊断失败.");
					jGlobal.faultDiag.endTime_diag = global.moment();
					jGlobal.showTime(jGlobal.faultDiag.startTime_diag, jGlobal.faultDiag.endTime_diag, "#min_time_diag", "#sec_time_diag");
					$("#diagTime").show();
					$("#diagResultText").show();
					
					var uploadParam = {};
					uploadParam.diagnoseId = jGlobal.faultDiag.diagnoseId;
					uploadParam.dataType = "faultDiagnose";
					uploadParam.curAction = "diagnosis";
					uploadParam.actionResult = "";
					uploadParam.duration = parseInt((jGlobal.faultDiag.endTime_diag - jGlobal.faultDiag.startTime_diag) / 1000);
					uploadParam.isResolved = "NA";
					jGlobal.uploadInfoToCloud(uploadParam);
				} else if (!isClickOverallDiag && jGlobal.faultDiag.curStatus == "connected") { //弹出是否深入诊断提示框后, 若用户长时间未操作, 设备断开连接, 此时状态为conneted, 上传诊断结果					
					diagDirectorIns.stop();					
					var uploadParam = {};
					uploadParam.diagnoseId = jGlobal.faultDiag.diagnoseId;
					uploadParam.dataType = "faultDiagnose";
					uploadParam.curAction = "diagnosis";
					uploadParam.actionResult = JSON.stringify(jGlobal.faultDiag.diagnoseResult);
					uploadParam.duration = parseInt((global.moment() - jGlobal.faultDiag.startTime_diag) / 1000);
					uploadParam.isResolved = "F"; //F表示完整的走完一次诊断
					jGlobal.uploadInfoToCloud(uploadParam);

					if (jGlobal.faultDiag.totalWarnCount == 0) {
						uploadParam.isResolved = "U"; //U表示完整的走完一次诊断后没有诊断出问题
						jGlobal.uploadInfoToCloud(uploadParam);
					}
				} else if (jGlobal.faultDiag.curStatus == "repair") {
					global.diagFixerIns.abort();

					$("#cancelRepair").text("完成");
					$("#cancelRepair").removeClass("btn-force-cancel");
					$("#cancelRepair").addClass("btn-complete");
					$("#repairResultText").text("连接断开,修复失败.");
					$("#repairResultText").show();

					jGlobal.faultDiag.endTime_repair = global.moment();
					jGlobal.showTime(jGlobal.faultDiag.startTime_repair, jGlobal.faultDiag.endTime_repair, "#min_time_repair", "#sec_time_repair");
					$("#repairTime").show();

					/* $(self).parent().append('<span class="label label-danger" style="float:right; font-size:11px;">' + '修复失败' + '</span>');
					$(self).remove(); */
				} else if (jGlobal.faultDiag.curStatus == "backRepair") {
					global.diaRollbackerIns.abort();

					$("#cancelBack").text("完成");
					$("#cancelBack").removeClass("btn-force-cancel");
					$("#cancelBack").addClass("btn-complete");
					$("#backResultText").text("连接断开,回退失败.");
					$("#backResultText").show();

					jGlobal.faultDiag.endTime_back = global.moment();
					jGlobal.showTime(jGlobal.faultDiag.startTime_back, jGlobal.faultDiag.endTime_back, "#min_time_back", "#sec_time_back");
					$("#backTime").show();
				}

				jGlobal.faultDiag.curStatus = jGlobal.changeDevStatus(jGlobal.faultDiag.curStatus, 'closing');
				global.tftpOperateInstance.changeDirName(jGlobal.faultDiag.collectDevName[0]);

				alert(undefined, '连接设备(' + res.deviceName + ')失败！错误信息: ' + res.errInfo);
				return;
			});

			global.devicesIns.on("deviceDisconnected", function(devName) {
				$('#connectDevModal').modal('hide');

				if(jGlobal.faultDiag.curStatus == 'closing' || jGlobal.faultDiag.curStatus == 'init') {
					jGlobal.faultDiag.curStatus = jGlobal.changeDevStatus(jGlobal.faultDiag.curStatus, 'init');
					return;
				}

				var msg = '';
				if(jGlobal.faultDiag.curStatus == 'connecting') {
					msg = '无法与设备(' + devName + ')建立连接！';
				} else if(jGlobal.faultDiag.curStatus == 'collect') { //* 原则上不会跑到
					msg = '收集失败，与设备(' + devName + ')断开连接';
				} else if(jGlobal.faultDiag.curStatus == 'diagnosis') { //* 原则上不会跑到
					msg = '诊断失败，与设备(' + devName + ')断开连接';
				} else if(jGlobal.faultDiag.curStatus == 'repair') { //* 原则上不会跑到
					msg = '修复失败，与设备(' + devName + ')断开连接';
				} else if(jGlobal.faultDiag.curStatus == 'backRepair') { //* 原则上不会跑到
					msg = '回退失败，与设备(' + devName + ')断开连接';
				} else {
					msg = '与设备(' + devName + ')连接断开！';
				}

				jGlobal.faultDiag.curStatus = jGlobal.changeDevStatus(jGlobal.faultDiag.curStatus, 'init');
				alert(undefined, msg);
			});

			diagDirectorIns = global.diagDirectorIns;
			registDiagEvent(diagDirectorIns);
			
			var scriptErr = diagDirectorIns.doDiag(jGlobal.faultDiag.curSelectNode.diagRule, jGlobal.faultDiag.preconditionParams.paramForDiag, jGlobal.faultDiag.diagSavePath);
			if (scriptErr == false) {
				if(jGlobal.faultDiag.curStatus != 'closing' && jGlobal.faultDiag.curStatus != 'init') {
					jGlobal.faultDiag.curStatus = jGlobal.changeDevStatus(jGlobal.faultDiag.curStatus, 'connected');
				}
				alert(undefined, "当前故障诊断脚本还未添加！");
			}
		}

		function initGlobalEvent() {
			global.exitPageCallback.exitFun = function() {
				//移除注册事件
				removeGlobalEvent();
				// 离开该页面，断开设备
				if(jGlobal.faultDiag.curStatus != 'init') {
					global.devicesIns.once("deviceDisconnected", function(devName) {
						jGlobal.faultDiag.curStatus = jGlobal.changeDevStatus(jGlobal.faultDiag.curStatus, 'init');
					});
					jGlobal.faultDiag.curStatus = jGlobal.changeDevStatus(jGlobal.faultDiag.curStatus, 'closing');
					global.devicesIns.closeDeviceLink(jGlobal.faultDiag.collectDevName[0]);
				}

				if(jGlobal.faultDiag.isClickCancel == true) {
					return true;
				} else {
					//自服务率对话框
					$('#selfServiceRateModal .btn-confirm').unbind('click');
					$('#selfServiceRateModal .btn-cancel').unbind('click');

					$('#selfServiceRateModal .btn-confirm').click(function() {
						uploadIsResolvedIssue('Y');
						var curElement = global.curClickPageId.split('|')[0];
						var nextPageUrl = global.curClickPageId.split('|')[1];
						$(curElement).load(global.pageIdToUrl[curElement][nextPageUrl]);
					});
					$('#selfServiceRateModal .btn-cancel').click(function() {
						uploadIsResolvedIssue('N');
						var curElement = global.curClickPageId.split('|')[0];
						var nextPageUrl = global.curClickPageId.split('|')[1];
						$(curElement).load(global.pageIdToUrl[curElement][nextPageUrl]);
					});

					$('#selfServiceRateModal').modal('show');
					return false;
				}
			}
		}
	}
	exports.init = init;
});