define(function(require, exports, module) {
	var global = require("../../js/global");
	var jGlobal = require("../../faultDiagMenu/js/faultDiagGlobal");
	var deviceManage = require("../../deviceManage/js/deviceManage");
	var mock = false;
	//获取设备的基本信息函数
	function getAndShowDevInfo() {
	    function queryDevInfoCallback(error, result) {
	        if (error == null) {
	            addDevInfoToTable(result);
	        } else {
	            alert(undefined, "读取设备数据失败！");
	        }
	    }
	    global.devicesIns.getDeviceConfigInfoAll(queryDevInfoCallback);
	}
	//把设备的基本信息在表格上显示
	function addDevInfoToTable(devInfo) {
		//console.log(devInfo);
	    for (var i = 0; i < devInfo.length; ++i) {	        
	        if (devInfo[i].protocal == "serial") {
	            devInfo[i].conne_type = devInfo[i].protocal;
	            devInfo[i].host_com = devInfo[i].comNum;
	            devInfo[i].port = devInfo[i].baudrate;
	        } else {
	            devInfo[i].conne_type = devInfo[i].protocal;
	            devInfo[i].host_com = devInfo[i].host;
	            devInfo[i].port = devInfo[i].port;
	        }	        
	        if (devInfo[i].groupName === null || devInfo[i].groupName === undefined || devInfo[i].groupName === '') {
	            devInfo[i].groupName = "未分组";
	        }
	    }	    
		$('#selectDeviceTable').bootstrapTable('load', devInfo);
	    return;
	}
	//创建连接按钮
	function operateStyle(value) {
	    return '<div class="table-btn connect" style="width: 75px;">请求协助</div>';
	}
	
	
	
	
	function init() {		
		var assistanceStatus="init";//定义连接状态init -> connecting -> connected -> closing -> init
		var assistCollectDevName=[];//设备名参数
		var assistCollectDevInfo={};//被选到的设备信息对象
				
		initWindowEvent();
		initPageStatistic();
		removeGlobalEvent();
		initTable();
		initEvent();
		initDom();
		resize();
		requireAssistance();
		initGlobalEvent();		
				
		//请求协助的大函数
		function requireAssistance(){
			
			okButtonClick();
			var countDowmInterval;//声明倒计时定时器
			var timeNubmer;//倒计时
			var paramsData={};//接收准备建立通道的返回参数
			var plink1;
			$("#setAssistanceTime").keyup(function(event){
				timeNubmer=$("#setAssistanceTime").val();
				var timeNubmer = parseInt(timeNubmer);
				//如果要带小数点只需[\d.]
				if(!isNaN(timeNubmer)&&parseInt(timeNubmer)>0&&parseInt(timeNubmer)<25){
					$("#promptText").text("");
					
				}else{
					$("#setAssistanceTime").val("");
					$("#promptText").text("");
					$("#promptText").text("请输入整数[1-24]");
					return false;
				}
				return (/[\d]/g.test(String.fromCharCode(event.keyCode)));

			});
			
			
			//点击ok启动协助
			function okButtonClick(){
				var AssistanceKey="";//接收连接码的参数
				
				//var plink;
				$("#okButton").click(function(){
					$("#openModalAssistTunnel").modal("show");
					timeNubmer = parseInt($("#setAssistanceTime").val());
					
					if(!isNaN(timeNubmer)&&timeNubmer!=null && timeNubmer!=""&&parseInt(timeNubmer)>0&&parseInt(timeNubmer)<25){
						
						//断开以设备的连接
						if (assistanceStatus == "connected") {
							
							console.log("断开设备的连接。。。");
							assistanceStatus = 'init';
							global.devicesIns.closeDeviceLink(assistCollectDevName[0]);
						}
						
						
						// var linkMgrIns=global.devicesIns;
						var userMgrIns=global.userMgrIns;
						//获取准备建立通道所需的参数
						global.remoteAssistant.prepareTunnel(assistCollectDevName[0],timeNubmer, global.devicesIns, userMgrIns,function(err,data){
							 if (err == null) {
								 
								paramsData=data;//获得所需参数
								var openTunnelParams={
									host:paramsData['proxyHost'],
									port:paramsData['proxyPort'],
									userName:paramsData['authName'],
									password:paramsData['authKey'],
									deviceIp:assistCollectDevInfo['host'],
									devicePort:assistCollectDevInfo['port']
								};
						
								global.remoteAssistant.openTunnel(openTunnelParams,buildCallback,closeCallback);								
																
							} else {
								$("#openModalAssistTunnel").modal("hide");
								alert(undefined, "获取服务器信息失败！err:" + err);
								global.remoteAssistant.reportBuildTunnelFailure(paramsData['tunnelId'], undefined, mock);
						
							}											
						},undefined,mock);
						
						
						// params:{host:'', port:1, userName:'', password:'', deviceIp: '', devicePort:2}
						/* groupId: 12,
						  deviceName: '172.18.157.113',
						  protocal: 'telnet',
						  enablePassword: 'ruijie',
						  comNum: 'COMx',
						  baudrate: 0,
						  host: '172.18.157.113',
						  port: 23,
						  username: 'ruijie',
						  password: 'ruijie',
						  status: '未管理',
						  seriaNo: '4658FH7240013',
						  deviceType: 'Wireless',
						  deviceModel: 'WS5708',
						  softVer: 'AC_RGOS 11.1(5)B80P2',
						  hardVer: '1.02',
						  encoding: 'utf8',
						  isQuitBeforeLogin: true,
						  systemSoftwareNumber: '',
						  releaseId: '',
						  flag: true }*/
						
						
						
					}else{
						$("#setAssistanceTime").val("2");
						$("#promptText").text("");
						$("#promptText").text("请输入整数[1-24]");
						return false;
					}
				});
				//建立通道，反馈的相关信息
				function buildCallback(err, msg, plink){
					plink1=plink;
					if (err == null) {
							//获取链接码
							global.remoteAssistant.getConnectCode(paramsData['tunnelId'],function(err, code){
								if (err == null) {
										AssistanceKey=code["verifyCode"];	//返回的验证码
										$("#openModalAssistTunnel").modal("hide");
										$("#stopAssistance").modal('show');
										$("#AssistanceTime").text(""+timeNubmer+"时00分00秒");
										//$("#setAssistanceTime").val("");
										countDowm(timeNubmer);//设置倒计时
										$("#AssistanceKey").text(AssistanceKey)//设置显示链接码
										
								} else {
										alert(undefined, "获取连接码失败！,err:", err);
										$("#openModalAssistTunnel").modal("hide");
										global.remoteAssistant.reportBuildTunnelFailure(paramsData['tunnelId'], undefined, mock);
								}	
							}, undefined ,mock);	
							
					} else {
							//$("#setAssistanceTime").val('');
							$("#AssistanceTime").text("");
							$("#openModalAssistTunnel").modal("hide");
							global.remoteAssistant.reportBuildTunnelFailure(paramsData['tunnelId']);
							if (assistanceStatus == "connected") {
								assistanceStatus = 'init';
								global.devicesIns.closeDeviceLink(assistCollectDevName[0]);
							}
							alert(undefined, msg);
										
					}		
					
				}
				//关闭通道
				function closeCallback(code, plink){
							plink1=plink;
							//$("#setAssistanceTime").val('');
							$("#AssistanceTime").text("");
							$("#openModalAssistTunnel").modal("hide");
							if (assistanceStatus == "connected") {
								assistanceStatus = 'init';
								global.devicesIns.closeDeviceLink(assistCollectDevName[0]);
							}
							global.remoteAssistant.reportBuildTunnelFailure(paramsData['tunnelId'], undefined, mock);
							
							alert(undefined, "通道已经关闭");
							clearInterval(countDowmInterval);
							$("#AssistanceTime,#AssistanceKey").text("");
							$("#stopAssistance").modal('hide');
					
				}
				
				
			}
			
			//当设计时间的model关闭、隐藏时触发			
			$('#cancelAssistance,#btnCloseAssistance').on('click', function () {
				//var AssistanceTime;//接收设置的倒计时间
				//AssistanceTime=$("#setAssistanceTime").val();
				$("#setAssistanceTime").val("2");
				$("#promptText").text("");
				
				if (assistanceStatus == "connected") {
						assistanceStatus = 'init';
						global.devicesIns.closeDeviceLink(assistCollectDevName[0]);
				}
				
				
				
			});
			
			//当关闭连接时触发的函数
			$( "#cancelAssistConnect,#stoptAssistConnect").on('click', function () {
						clearInterval(countDowmInterval)
						$("#AssistanceTime,#AssistanceKey").text("");
						if (assistanceStatus == "connected") {
							assistanceStatus = 'init';
							global.devicesIns.closeDeviceLink(assistCollectDevName[0]);
						}
						console.log("323123123aaaa"+plink1);
						global.remoteAssistant.closeTunnel(plink1,paramsData['tunnelId']);
						alert(undefined, "通道已经关闭");
						$("#stopAssistance").modal('hide');
				
			});
			
			//设置倒计时函数
			function countDowm(time){
				var time=time*3600;//转换成秒
				countDowmInterval=setInterval(function(){
					time--;
					$("#AssistanceTime").text(formTime(time));
					if(time==0){
						clearInterval(countDowmInterval)
						$("#AssistanceTime").text("");
					
					}
				},1000);
				
				//将设置时间格式化
				function formTime(time){
					var Otime=time;
					var h=~~(Otime/(60*60)%24);
					var m=~~(Otime/60%60);
					var s=~~(Otime%60);
					var p=""+h+"时"+m+"分"+s+"秒";
					return p;
				}
			
			}
		
		}
		
		//创建连接按钮，并为之注册点击事件
		function initWindowEvent() {
			window.operateStyle = operateStyle;//创建按钮
			window.operateEvents = {
			    'click .connect': function (e, value, row, index) {
			    	collectClick(row, index);//row：设备的全信息，index：行下表
			    }
			};
		}
		
		//点击请求协助，与设备建立或断开连接
		function collectClick(row, index) {	
			//var assistanceStatus=assistanceStatus;
			//设置设备的连接状态为closing
			console.log("打印row:"+row.toString());
			if (assistanceStatus == 'closing') {
				alert(undefined, '正在与设备(' + assistCollectDevName[0] + ')断开连接，请稍等');
				return;
			}
			if (assistanceStatus != 'init') {
				alert(undefined, '正在连接设备(' + assistCollectDevName[0] + ')，请稍等');
				return;
			}
			assistanceStatus ='connecting';
					
			$('#connectDevModalAssist').modal('show');
			assistCollectDevInfo=row;
			assistCollectDevName = [];
			assistCollectDevName.push(row.deviceName);
			//实现与后台设备连接的函数，发送的参数是设备的名称
			global.devicesIns.connectDeviceByDeviceName(assistCollectDevName[0]);

					
		}
		
		//记录当前页面已经进入
		function initPageStatistic() {
			statRecordEle("remoteAssistance#requesAssistance");
		}
		
		//点击连接设备按钮后，去除对设备的一些监听
		function removeGlobalEvent() {
			global.devicesIns.removeAllListeners("deviceConnected");
			global.devicesIns.removeAllListeners("deviceError");
			global.devicesIns.removeAllListeners("deviceDisconnected");
		}
		
		//显示表格的基本信息
		function initTable() {
			$('#selectDeviceTable').bootstrapTable({
		        data: []
		    });
			
			$(".fixed-table-body").addClass('custom-scroll');
			$("#selectDeviceTable").show();
			
			getAndShowDevInfo();
		}
		
		//创建设备分组
		function initEvent() {
			
			$("#selectGroup").change(function() {		    	
		    	var groupId = $('#selectGroup').val();
		    	groupId = groupId.split(':')[0];
		    	if (groupId == "null") {
		    		groupId = null;
		    	}
		    	addDevInfoToTable(deviceManage.searchDeviceByGroupId(groupId));
		    });
			
			
			global.devicesIns.on("deviceConnected", function(devName) {	
				
				console.log("已建立连接。。。。11111");
				if (assistanceStatus != 'connecting') {
					console.log("断开不上连接。11");
		            return;
		        }
				assistanceStatus ='connected';
				
				var groupId = $('#selectGroup').val();
		    	groupId = groupId.split(':')[0];
		    	if (groupId == "null") {
		    		groupId = null;
		    	}
		    	addDevInfoToTable(deviceManage.searchDeviceByGroupId(groupId));
		    	console.log("已建立连接。2222。。22222");
		    	$('#connectDevModalAssist').modal('hide');
				$("#setAssistanceTime").val('2');
				$("#reqAssistance").modal('show');//显示设置连接时间
		    	
			});
			
			global.devicesIns.on("deviceError", function(res) {
				$('#connectDevModalAssist').modal('hide');
				
				if (assistanceStatus == 'closing' || assistanceStatus == 'init') {
		            return;
		        }
				
				assistanceStatus ='closing';				
				global.tftpOperateInstance.changeDirName(assistCollectDevName[0]);
				
		        alert(undefined, '连接设备(' + res.deviceName + ')失败！错误信息: ' + res.errInfo);
		        return;
			});
			
			global.devicesIns.on("deviceDisconnected", function(devName) {
				$('#connectDevModalAssist').modal('hide');
				
				if (assistanceStatus == 'closing' || assistanceStatus == 'init') {
					assistanceStatus = 'init';
		            return;
		        }

		        var msg = '';
		        if (assistanceStatus == 'connecting') {
		            msg = '无法与设备(' + devName + ')建立连接！';
		        } else {
		            msg = '与设备(' + devName + ')连接断开！';
		        }

		        assistanceStatus = 'init';
		        alert(undefined, msg);
			});	
		}
		function initDom() {
			
			//查询当前分组
			var select_id = "selectGroup";
	    	$("#" + select_id).children().remove();
	    	var $option = $("<option>");
	    	$option.val("null:全部分组");
	    	$option.text("全部分组");
	    	$("#" + select_id).append($option);
			global.devicesIns.queryAllSubGroups("selectGroup", deviceManage.queryAllSubGroupsCbk);
		}
		//设置表格的页面的大小
		function resize() {
			var client_h = document.documentElement.clientHeight;
			var head_h = $(".main_menu").height();
			var body_h = client_h - head_h;
			
			$('#selectDeviceTable').bootstrapTable('resetView', {height : body_h - 55});
		}
		
		//离开当前页面，将执行注销当前页面的事件
		function initGlobalEvent() {
			global.exitPageCallback.exitFun = function () {
				removeGlobalEvent();
				return true;
			}
		}
	}
	exports.init = init;
});