define(function(require, exports, module) {
	var global = require("../../js/global");
	var jGlobal = require("./faultDiagGlobal");
	var upload = require("./upload");
	//	var selectDevice = require("./selectDevice");

	//循环收集进度条变量
	var count = 0;
	var record = 0;
	var percent = 0;

	/* 当前正常状态:init closing collect */
	function cancelCollect() {
		if ($("#cancelCollect").text() == "强制取消") {
			if (jGlobal.faultDiag.curStatus != 'closing' && jGlobal.faultDiag.curStatus != 'init') {
				if (jGlobal.faultDiag.typeName == "自定义收集") {
					jGlobal.faultDiag.collectStatus = 'cancel';
				}
				jGlobal.faultDiag.curStatus = jGlobal.changeDevStatus(jGlobal.faultDiag.curStatus, 'closing');

				global.tftpOperateInstance.cancelCollectInfo(jGlobal.faultDiag.collectDevName[0]);
				global.devicesIns.closeDeviceLink(jGlobal.faultDiag.collectDevName[0]);

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

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

	function uploadIsResolvedIssue(isResovledSign) {
		var uploadParam = {};
		uploadParam.diagnoseId = jGlobal.faultDiag.diagnoseId;
		uploadParam.dataType = "faultDiagnose";
		uploadParam.curAction = "diagnosis";
		uploadParam.actionResult = jGlobal.faultDiag.diagnoseResult;
		uploadParam.duration = parseInt((jGlobal.faultDiag.endTime_diag - jGlobal.faultDiag.startTime_diag) / 1000);
		uploadParam.isResolved = isResovledSign;
		jGlobal.uploadInfoToCloud(uploadParam);
	}

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

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

		function initWindowEvent() {
			window.cancelCollect = cancelCollect;
		}

		function initPageStatistic() {
			statRecordEle("faultDiag#collectEnd");
		}

		function initDom() {
			$('#dlg_collectProgress').modal({
				backdrop: 'static'
			});
		}

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

			global.tftpOperateInstance.removeAllListeners("collectInfo");
			global.tftpOperateInstance.removeAllListeners("collectEnd");

			global.tftpOperateInstance.removeAllListeners("collectProcess");
			global.tftpOperateInstance.removeAllListeners("collectEnd");
			global.tftpOperateInstance.removeAllListeners("collectFullInfo");
		}

		function initVariable() {
			count = 0;
			record = 0;
			percent = 0;
		}

		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, "设备已连上，无需重新连接！");
			//				}
			//			});

			$("#collectBack").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);
			});

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

			$('#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);
				});

				// 新手引导
				if(global.guide) {
					$('#red-point').css('display', 'none');
					global.guide = false;
				}
				//
			});

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

			global.devicesIns.on("deviceConnected", function(devName) {
				console.log("-------------------------deviceConnected--------------------------");
				console.log(jGlobal.faultDiag.curStatus);

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

				if(jGlobal.faultDiag.typeName == "自定义收集") {
					console.log("自定义收集过程中与设备连接断开后自动重连！");
				}

				jGlobal.faultDiag.curStatus = jGlobal.changeDevStatus(jGlobal.faultDiag.curStatus, 'connected');
			});

			//除程序主动断开连接时不会收到deviceError外,其余任何情况都会收到deviceError,此时正常状态:
			//自定义收集——connecting connected collect, 
			//非自定义收集——connected collect
			global.devicesIns.on("deviceError", function(res) {
				console.log("-------------------------deviceError--------------------------");
				console.log(jGlobal.faultDiag.curStatus);

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

				if(jGlobal.faultDiag.curStatus == "collect") {
					global.tftpOperateInstance.cancelCollectInfo(jGlobal.faultDiag.collectDevName[0]);

					$("#cancelCollect").text("完成");
					$("#cancelCollect").removeClass("btn-force-cancel");
					$("#cancelCollect").addClass("btn-complete");
					$("#collectResultText").text("连接断开,收集失败.");
					jGlobal.faultDiag.endTime_collect = global.moment();
					jGlobal.showTime(jGlobal.faultDiag.startTime_collect, jGlobal.faultDiag.endTime_collect, "#min_time_collect", "#sec_time_collect");
					$("#collectTime").show();
					$("#collectResultText").show();

					var uploadParam = {};
					uploadParam.diagnoseId = jGlobal.faultDiag.diagnoseId;
					uploadParam.dataType = "faultCollect";
					uploadParam.curAction = "collect";
					uploadParam.actionResult = "";
					uploadParam.duration = parseInt((jGlobal.faultDiag.endTime_collect - jGlobal.faultDiag.startTime_collect) / 1000);
					uploadParam.isResolved = "NA";
					jGlobal.uploadInfoToCloud(uploadParam);
				}

				if(jGlobal.faultDiag.curStatus == "collect" || jGlobal.faultDiag.curStatus == "connecting" ||
					(jGlobal.faultDiag.curStatus == "connected" && jGlobal.faultDiag.typeName != "自定义收集")) {
					jGlobal.faultDiag.curStatus = jGlobal.changeDevStatus(jGlobal.faultDiag.curStatus, 'closing');
					global.tftpOperateInstance.changeDirName(jGlobal.faultDiag.collectDevName[0]);

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

			//收到deviceDisconnected时, connected只可能在自定义收集时跑到, connecting只可能在自定义收集时强制取消可能跑到
			//其他情况下只可能收到closing init(其他情况下collect和connecting都已在deviceError中改变了)
			//自定义收集——closing init connecting connected,
			//非自定义收集——closing init
			global.devicesIns.on("deviceDisconnected", function(devName) {
				console.log("-------------------------deviceDisconnected--------------------------");
				console.log(jGlobal.faultDiag.curStatus);

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

				if(jGlobal.faultDiag.curStatus == "connected" && jGlobal.faultDiag.typeName == "自定义收集") {
					console.log("自定义收集过程中与设备连接断开！");
					jGlobal.faultDiag.curStatus = jGlobal.changeDevStatus(jGlobal.faultDiag.curStatus, 'connecting');
					global.devicesIns.connectDeviceByDeviceName(devName);

					return;
				}

				var msg = '';
				if(jGlobal.faultDiag.curStatus == 'connecting') {
					msg = '无法与设备(' + devName + ')建立连接！';
				} else if(jGlobal.faultDiag.curStatus == "connected") {
					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 + ')断开连接';
				}

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

			global.tftpOperateInstance.on("collectInfo", function(res) {
				if(jGlobal.faultDiag.curStatus != 'collect') {
					return;
				}

				/* 更新收集进度条 */
				percent = Math.floor(((res.totalNum - res.remainingNum) / (res.totalNum * (jGlobal.faultDiag.cycleNum + 1))) * 100);
				console.log('!!!!!!!!!!!!collect bar,percent:', percent, '%,record+percent:', percent + record, '%,totalNum:', res.totalNum, ' remainingNum:', res.remainingNum, ' cycleNum+1:', jGlobal.faultDiag.cycleNum);
				if((jGlobal.faultDiag.tmpCollectPercent == 0 && percent != 0) || ((percent - jGlobal.faultDiag.tmpCollectPercent) >= 5)) {
					$("#collect_progress").text((percent + record) + '%');
					$("#collect_progressBar").css('width', (percent + record) + '%');
					jGlobal.faultDiag.tmpCollectPercent = percent;
				}
			});

			global.tftpOperateInstance.on("collectEnd", function(res) {
				// 设置执行状态为done，这个在循环收集中要用到，预示着下一次循环即将开始
				if (jGlobal.faultDiag.typeName == "自定义收集") {
					jGlobal.faultDiag.collectStatus = 'done';
				}
				
				if (jGlobal.faultDiag.curStatus != 'collect') {
					return;
				}
				jGlobal.faultDiag.curStatus = jGlobal.changeDevStatus(jGlobal.faultDiag.curStatus, 'connected');

				//自定义循环收集,收到collectEnd表示收集完成1次
				count++;				
				console.log('!!!!!!!in collectEnd, count:', count, ' cycleNum + 1:', jGlobal.faultDiag.cycleNum + 1);
				if (count < (jGlobal.faultDiag.cycleNum + 1)) {
					jGlobal.faultDiag.tmpCollectPercent = 0;
					record += percent;
					console.log('!!!!!!!in self collectEnd, count:', count, ' cycleNum + 1:', jGlobal.faultDiag.cycleNum + 1, 'record:', record);
					return;
				}

				global.tftpOperateInstance.changeDirName(jGlobal.faultDiag.collectDevName[0]);
				/* 更新步骤进度 */
				$(".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');
				/* 显示收集完成 */
				$(".collectResult").show();
				/* 更新收集进度条 */
				$("#collect_progress").text('100%');
				$("#collect_progressBar").css('width', '100%');
				$("#cancelCollect").text("完成");
				$("#cancelCollect").removeClass("btn-force-cancel");
				$("#cancelCollect").addClass("btn-complete");
				/* 显示收集时长 */
				$("#collectResultText").text("收集完成.");
				jGlobal.faultDiag.endTime_collect = global.moment();
				jGlobal.showTime(jGlobal.faultDiag.startTime_collect, jGlobal.faultDiag.endTime_collect, "#min_time_collect", "#sec_time_collect");
				$("#collectTime").show();
				$("#collectResultText").show();

				var uploadParam = {};
				uploadParam.diagnoseId = jGlobal.faultDiag.diagnoseId;
				uploadParam.dataType = "faultCollect";
				uploadParam.curAction = "collect";
				uploadParam.actionResult = "";
				uploadParam.duration = parseInt((jGlobal.faultDiag.endTime_collect - jGlobal.faultDiag.startTime_collect) / 1000);
				uploadParam.isResolved = "NA";
				jGlobal.uploadInfoToCloud(uploadParam);
			});

			var collCurCmd = "";
			var collCmdHistory = [];
			global.tftpOperateInstance.on('collectProcess', function(data) {
				collCurCmd = "当前收集的命令:" + '<span>' + data.runningCmd + '</span>';
				$("#txtCollCurCmd").html(collCurCmd);
				$("#txtCollCmdHistory").html(collCmdHistory.join('<br>'));
				collCmdHistory.unshift(data.runningCmd);
			});
			global.tftpOperateInstance.on("collectEnd", function(res) {
				$("#txtCollCmdHistory").html(collCmdHistory.join('<br>'));
				$("#txtCollCurCmd").html("当前收集的命令:<span>无</span>");
			});
			//			global.tftpOperateInstance.on('collectFullInfo',function(datas) {
			//			    $("#txtCollAllCmd").html(datas.cmdList.join('<br>'));
			//			});
		}

		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 {
					if(jGlobal.faultDiag.isLoadFromDiag == true) {
						//自服务率对话框
						$('#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;
					} else {
						return true;
					}
				}
			}
		}
	}

	exports.init = init;
});