define(function(require, exports, module) {
	var global = require("../../js/global");
	var mock = false;
	var encoding="utf8";
	var countDowmInterval = null;//声明倒计时定时器
	function buffer2string(resp, encoding) {
        if (encoding == 'utf8') {
            return resp.toString();
        }
        var iconv = window.require('iconv-lite');
        return iconv.decode(resp, encoding);
    }
	function openWrite(infodata,CurTimeStr){				
				
				//建立连接的函数
				function netConnet(){
					client=new global.linkParser();
						if(infodata['device']['protocol']=="telnet"){
							//$("client").unbind("keyup");
							client.connect({
								protocal: infodata['device']['protocol'],							
								port:  infodata['proxyPort'],
								host:  infodata['proxyHost'],
								workMode: 'link',
							});
						}else if(infodata['device']['protocol']=="SSH"){
						
								client.connect({
									
									protocal: infodata['device']['protocol'],
									username:  infodata['device']['deviceUserName'],
									password:  infodata['device']['devicePwd'],
									port:  infodata['proxyPort'],
									host:  infodata['proxyHost'],
									workMode: 'link',
									/*
									port:  infodata['device']['proxyPort'],
									host:  infodata['device']['proxyHost'],
										//protocal: 'telnet',//telnet不需要用户名，密码
										protocal: 'SSH',
										username: 'adm2',
										password: 'adm2',
										port: "22",
										host: "192.168.23.191",
										//host: "172.18.157.148",
										
										//port: "23",
										workMode: 'link',
										*/
										
								});
						}else{
							alert(undefined,"连接失败！");
						}
					client.on('data', callback);				
					client.on('close',function(){});
					client.on('error',errorBack);
				
				}
				
				//键盘输入触发事件函数
				function fnINput(event){
						if(event.shiftKey&&event.keyCode==51){
							
						}
						 if(loginTag==0){
							$("#divInline").val($("#divInline").val().replace(/#/g,''));
							$("#divInline").val($("#divInline").val().replace(/"/g,''));
						 }
						if(event.keyCode == 13){
							if(openTag==1){
								var str = '0d';
								try {
									var $inputVal=$("#divInline").val();
									$("#divInline").val("");
									client.send($inputVal);
							
									client.send(Buffer(str, 'hex'));
								} catch(e) {
									
								}
							}else{
								$("#textTitle span").css("color","green");
								$("#textTitle span").text("已建立连接....");
								
								$("#divInline").siblings().empty();
								openTag=1;
								loginTag=0;
								$("#buttonDiv").empty();
								$("#buttonDiv").show();
								BottunClick(data);
								netConnet();
							}
							
						}else{
							
						}						
				}
				//登陆成功后隐藏按键、把返回内容写入文件
				function loginSuccess(){
					//返回数据中如果有"#",就是登录成功
							if(/#/.test($data)==true){
								$("#buttonDiv").empty();
								$("#buttonDiv").hide();
								//$("#clickInput").hide();
								loginTag=1;
							}//获得成功标志loginTag==1后，对文件进行写入
							if(loginTag==1){
								console.log("....e.e.e.e.e."+CurTimeStr);
								fso.open(global.nwPath.join(global.jsUtil.getDataPath(), '/assistantLogs/', CurTimeStr + '.txt'), 'a', function opened(err, fd) {
										if (err) { throw err; }
										var writeBuffer = new Buffer($dataWrite),
										bufferPosition = 0,
										bufferLength = writeBuffer.length, 
										filePosition = null;
										fso.write( fd,
											writeBuffer,
											bufferPosition,
											bufferLength,
											filePosition,
											function wrote(err, written) {
											   if (err) {
												   throw err; 
											   }else{ 
												   fso.close(fd);
												}
											  
											});
									});
								$("#logCheckButton").show();//显示点击查看日志按钮
							}

				}
				
				//发送数据后的回调函数
				function callback(data){
					var $data = buffer2string(data,encoding);
					var $dataWrite = buffer2string(data, encoding);
					//var $data = data.toString();	infodata['device']['encoding']	
									//infodata['device']['encoding']
					//var $dataWrite = data.toString();					
					$("#divInline").val("");
					//点击输入账号、密码成功后返回回车键的执行（说明已经登录成功）
					if(ioTag==1&&/\n/.test($data)==true){	
						//loginTag=1;//判断是否登录成功的标志,只有为1时，才会把返回数据写入txt文件
						ioTag=0;
							//返回数据中如果有"#",就是登录成功
							if(/#/.test($data)==true){
								$("#buttonDiv").empty();
								$("#buttonDiv").hide();
								loginTag=1;
							}//获得成功标志loginTag==1后，对文件进行写入
							//'../../../data/toolkit/assistantLogs/'+CurTimeStr+'.txt'
							if(loginTag==1){
								
								fso.open(global.nwPath.join(global.jsUtil.getDataPath(), '/assistantLogs/', CurTimeStr + '.txt'), 'a', function opened(err, fd) {
										if (err) { throw err; }
										var writeBuffer = new Buffer($dataWrite),
										bufferPosition = 0,
										bufferLength = writeBuffer.length, filePosition = null;
										fso.write( 
											fd,
											writeBuffer,
											bufferPosition,
											bufferLength,
											filePosition,
											function wrote(err, written) {
											   if (err) {
												   console.log("写文件操作失败");
												   throw err; 
											   }else{ 
												   console.log("写文件操作成功");
												   //console.log("...332.e.e.e.e.e."+CurTimeStr);
												   fso.close(fd);
												}
											  
											});
									});
								$("#logCheckButton").show();//显示点击查看日志按钮
		
							}
						var $data=$data.replace(/\r/g,"");
						
							if(loginTag==0){
								var strMark="";
								//console.log("查看data查看data字符串数据数据："+$data);
								for(var i=0;i<$data.length;i++){
									
									if($data[i]=='"'){
										quotMark=!(quotMark);
									}
									if(quotMark){										
										strMark=strMark+$data[i];
									}
									
									
									
								}
								if(strMark){
									var $data=$data.replace(strMark,"***");
								}
								if(/.*>/.test($dataWrite)){
									client.send("en",function(){});
									client.send(Buffer('0d', 'hex'),function(){});
								}
							}
						var data2=$data.split('\n');
						var $data1=data2[0].replace(/./g,"*");
						var $data2="";
						for(var i=1;i<data2.length;i++){
							//var $data2=$data2+"<br>"+data2[i];
							var $data2=$data2+"<br>"+data2[i];
						}
						
						var $data=$data1+$data2;
						var $spanWrite=$("<span></span>");
								$spanWrite.append($data);
								$("#divInline").before($spanWrite);
								$("#writeText").scrollTop(9999);
								$("#divInline").unbind("focus");
								$("#divInline").focus();
								$("#divInline").unbind("keyup");
								$("#divInline").keyup(fnINput);
						
					}else if(ioTag==1&&/\n/.test($data)==false){
						//点击输入账号后的执行（没有获得回车）
						var $data=$data.replace(/./g,"*");						
						var $spanWrite=$("<span></span>");
								$spanWrite.append($data);
								$("#divInline").before($spanWrite);
								$("#writeText").scrollTop(9999);
								$("#divInline").unbind("focus");
								$("#divInline").focus();
								$("#divInline").unbind("keyup");
								$("#divInline").keyup(fnINput);
					}
					else{
							//返回数据中如果有"#",就是登录成功
							if(/#/.test($data)==true){
								$("#buttonDiv").empty();
								$("#buttonDiv").hide();
								loginTag=1;
							}//获得成功标志loginTag==1后，对文件进行写入
							if(loginTag==1){
								//global.jsUtil.ensureFS(global.nwPath.join(global.jsUtil.getDataPath(), '/assistantLogs/'));CurTimeStr
								fso.open(global.nwPath.join(global.jsUtil.getDataPath(), '/assistantLogs/', CurTimeStr + '.txt'), 'a', function opened(err, fd) {
										if (err) { throw err; }
										var writeBuffer = new Buffer($dataWrite),
										bufferPosition = 0,
										bufferLength = writeBuffer.length, filePosition = null;
										fso.write( 
											fd,
											writeBuffer,
											bufferPosition,
											bufferLength,
											filePosition,
											function wrote(err, written) {
											   if (err) {
												   console.log("写文件操作失败");
												   throw err; 
											   }else{ 
												   console.log("写文件操作成功");
												   fso.close(fd);
												}
											  
											});
									});
								$("#logCheckButton").show();//显示点击查看日志按钮
		
							}
							if(loginTag==0){
								var strMark="";
								//console.log("查看data字符串数据："+$data);
								for(var i=0;i<$data.length;i++){
										if($data[i]=='"'){
										quotMark=!(quotMark);
									}
									if(quotMark){
										strMark=strMark+$data[i];
									}
								
									
									
								}
								if(strMark){
									//console.log("测试调换字符串:"+strMark);
									var $data=$data.replace(strMark,"***");
								}
								if(/.*>/.test($dataWrite)){
									client.send("en",function(){});
									client.send(Buffer('0d', 'hex'),function(){});
								}
							}
						var $data=$data.replace(/\r/g,"");
						var $data=$data.replace(/\n/g,"<br>");
						var $spanWrite=$("<span></span>");
						$spanWrite.append($data);
						$("#divInline").before($spanWrite);						
						$("#writeText").scrollTop(9999);
						$("#divInline").unbind("focus");
						$("#divInline").focus();
						$("#divInline").unbind("keyup");
						$("#divInline").keyup(fnINput);
					}
				}
				
				//接受错误后的回调函数
				function errorBack(){
					
					client.on('close',function(){
						openTag=0;
						$("#textTitle span").css("color","red");
						$("#textTitle span").text("已断开连接...");
						$("#divInline").before($("<br>"));
						var $spanWrite=$("<span></span>");
						$spanWrite.append("已经断开连接，请<span  style='color:red;'>按回车键</span >重新连接！");
						$("#divInline").before($spanWrite);	
						$("#writeText").scrollTop(19999);
						$("#divInline").unbind("focus");
						$("#divInline").focus();
						$("#divInline").unbind("keyup");
						$("#divInline").keyup(fnINput);
					});
					client.end();						

				}
				
				//正常流块
				$("#divInline").siblings().empty();
				$('#connectModalAssistTunnel').modal('hide');
				$("#win").show();
				$("#back").show();
				$('#selectEncode').change(function(){
					encoding=$(this).children('option:selected').val();//selected的值 
				});
				$("#buttonDiv").empty();
				$("#buttonDiv").show();
				$("#logCheckButton").hide();//隐藏日志按钮
				$("#textTitle span").css("color","green");
				$("#textTitle span").text("已建立连接....")
				$("#divInline").unbind("focus");
				$("#divInline").focus();
				//$("#clickInput").val("用户名输入");
				var ioTag=0;//判断是否是点击输入账号密码，1是，0否
				var loginTag=0;//判断是否登录成功的标志0否，1YES
				var quotMark=false;//判断是否遇到引号的标志，0没遇到或双数次遇到，1单数次遇到，
				var fso=global.fs;
				$("#writeText").unbind("click");
				$("#writeText").click(function(){
						$("#divInline").focus();
					});					
				var openTag=1;//判断是否连接上服务器的标志，是1，否0
				var client={};
				netConnet();

					//var data={userName:"ruijie",passWord:"ruijie",enPassWord:"ruijie"};
					//var data={userName:"adm",passWord:"adm"};
					//var data={userName:"adm2",passWord:"adm2",enPassWord:"admin"};
					
					var data={userName:infodata['device']['deviceUserName'],passWord: infodata['device']['devicePwd'],enPassWord:infodata['device']['deviceEnablePwd'] };//infodata.deviceEnablePwd
					//var data={enPassWord:"admin"};
					BottunClick(data);
					function BottunClick(data){
							var data=data;
							
							for(var key in data){
								
								if(data[key]!=''){
									var $inputCre=$("<input type='button' class='btn btn-default' style='background-color:#366ff5;margin-right:2px;color: #fff;'></input>");
									$inputCre.val(getValueName(key));
									$("#buttonDiv").append($inputCre);
									$inputCre.unbind("click");
									(function(n){  
										$inputCre.click(function(){
											ioTag=1;
											$("client").unbind("send");
											client.send(data[n],function(){});
											client.send(Buffer('0d', 'hex'),function(){});
											
										}); 																			  
									})(key) 
								}
								
							}

							//通过key值把对应中文按钮名返回给按钮的value值
							function getValueName(name){
								var name=name; 
								if(name=="userName"){
									return "用户名输入";
								}else if(name=="passWord"){
									return "密码输入";
								}else if(name=="enPassWord"){
									return "en密码输入";
								}
							}
				}
													
				$("#closeWrite").unbind("click");
				$("#closeWrite").click(function(){
					$("#logCheckButton").hide();
					$("#win").hide();
					$("#back").hide();
					clearInterval(countDowmInterval);
					global.remoteAssistant.reportCloseConnection(undefined,mock); 
					try {
						console.log("关闭连接成功！");
						client.end();						
					} catch(e) {
						console.log("关闭连接失败！")
					}
					
					});
				$("#logCheckButton").unbind("click");
				$("#logCheckButton").click(function(){
					//var path='../../../data/toolkit/assistantLogs';
					//global.nwPath.join(global.jsUtil.getDataPath(), '/assistantLogs/')
					var path = global.nwPath.join(global.jsUtil.getDataPath(), '/assistantLogs/');
					console.log("路径："+path);
					global.jsUtil.openDir(path);
				})

	}
	
/*
	//获取文件夹中的文件
	function explorer(path){
			global.fs.readdir(path, function(err, files){
				//err 为错误 , files 文件名列表包含文件夹与文件
				if(err){
					console.log('error:\n' + err);
					return;
				}

				files.forEach(function(file){

					fs.stat(path + '/' + file, function(err, stat){
						if(err){console.log(err); return;}
						if(stat.isDirectory()){					
							// 如果是文件夹遍历
							explorer(path + '/' + file);
						}else{
							// 读出所有的文件
							console.log('文件名:' + path + '/' + file);
						}				
					});
					
				});

			});
	}
*/
	
	//设置倒计时函数
	function countDowm(time){
		var time=time*60;//转换成秒
		countDowmInterval=setInterval(function(){
			time--;
			$("#closeAssistanceTime").text(formTime(time));
			if(time==0){
				clearInterval(countDowmInterval)				
				$("#closeAssistanceTime").text("00时00分00秒");
						
			}
		},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 init() {
		initvariable();
		initWrite();
		initGlobalEvent();

		function initvariable() {
			countDowmInterval = null;
		}
		function initWrite(){
			var CurTimeStr;//文件夹的命名
			$("#okConnet").click(function(){			
				var infodata={};//建立连接后，返回的设备信息
				var checkOutCode=$("#checkOutCode").val().trim();//获取链接码
				$('#connectModalAssistTunnel').modal('show');
				global.remoteAssistant.getTunnelInfo(checkOutCode,function(err,data){
					if (err == null) {
							if(data['code']==0){
									infodata=data;	//建立连接后，返回的设备信息
									console.log("12312332000:"+JSON.stringify(data));
									/*	protocal: infodata['device']['protocol'],							
										port:  infodata['proxyPort'],
										host:  infodata['proxyHost'],
										userName:infodata['device']['deviceUserName'],
										passWord: infodata['device']['devicePwd'],
										enPassWord:infodata['device']['deviceEnablePwd']
									*/
									$('#connectModalAssistTunnel').modal('hide');
									$("#remindContent table tbody tr:eq(0) td:eq(1)").text(infodata['proxyHost']);
									$("#remindContent table tbody tr:eq(1) td:eq(1)").text(infodata['proxyPort']);
									$("#remindContent table tbody tr:eq(2) td:eq(1)").text(infodata['device']['protocol']);
									$("#remindContent table tbody tr:eq(3) td:eq(1)").text(infodata['device']['deviceUserName']!=''?infodata['device']['deviceUserName']:"无");
									$("#remindContent table tbody tr:eq(4) td:eq(1)").text(infodata['device']['devicePwd']!=''?infodata['device']['devicePwd']:"无");
									$("#remindContent table tbody tr:eq(5) td:eq(1)").text(infodata['device']['deviceEnablePwd']!=''?infodata['device']['deviceEnablePwd']:"无");
/*
									$("#remindContent div:eq(0) span:eq(1)").text(infodata['proxyHost']);
									$("#remindContent div:eq(1) span:eq(1)").text(infodata['proxyPort']);
									$("#remindContent div:eq(2) span:eq(1)").text(infodata['device']['protocol']);
									$("#remindContent div:eq(3) span:eq(1)").text(infodata['device']['deviceUserName']!=''?infodata['device']['deviceUserName']:"无");
									$("#remindContent div:eq(4) span:eq(1)").text(infodata['device']['devicePwd']!=''?infodata['device']['devicePwd']:"无");
									$("#remindContent div:eq(5) span:eq(1)").text(infodata['device']['deviceEnablePwd']!=''?infodata['device']['deviceEnablePwd']:"无");
*/									
									$("#remindRecom").modal('show');
									$("#closeRemindRecom").click(function(){
										global.remoteAssistant.reportCloseConnection(undefined,mock);
										$("#remindRecom").modal('hide');
									});
									$("#okContentConnet").click(function(){
										$("#remindRecom").modal('hide');
										countDowm(infodata['timeoutMinite']);//设置倒计时
										global.jsUtil.ensureFS(global.nwPath.join(global.jsUtil.getDataPath(), '/assistantLogs/'));
										//global.jsUtil.ensureFS('../../../data/toolkit/assistantLogs');
										CurTimeStr=global.jsUtil.getCurTimeStr() + checkOutCode;
										openWrite(infodata,CurTimeStr);
									})
									
							}else{
									$('#connectModalAssistTunnel').modal('hide');
									alert(undefined,data['msg']);
							}
					} else {
							$('#connectModalAssistTunnel').modal('hide');
							alert(undefined, "建立协助连接失败！");
								
					}	
				},undefined,mock);
				
			});
						
		}
		
		function initGlobalEvent() {
			global.exitPageCallback.exitFun = function () {				
				return true;
			}
		}
	}
	exports.init = init;
});