<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="zh-cmn-Hans">
<head>
   <meta charset="utf-8">
   <title></title>
   <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0">

   <link rel="stylesheet" href="${httpServletRequest.getContextPath()}/weui/css/weui.css"/>
   <link rel="stylesheet" href="${httpServletRequest.getContextPath()}/weui/css/weuix.css"/>
   <link rel="stylesheet" href="${httpServletRequest.getContextPath()}/weui/css/chat.css"/>
   <script src="${httpServletRequest.getContextPath()}/weui/js/zepto.min.js"></script>
   <script src="${httpServletRequest.getContextPath()}/weui/js/zepto.weui.js"></script>
   <script src="${httpServletRequest.getContextPath()}/weui/js/lrz.min.js"></script>
   <script src="${httpServletRequest.getContextPath()}/weui/js/xss.min.js"></script>
    <script src="${httpServletRequest.getContextPath()}/audio/HZRecorder.js"></script>
    <script src="${httpServletRequest.getContextPath()}/audio/voiceEncoder.js"></script>
    <script src="${httpServletRequest.getContextPath()}/audio/queue.js"></script>
   <script type="text/javascript">
     var path="${httpServletRequest.getContextPath()}";
     $(function(){
    	 
    	//防止页面后退
         history.pushState(null, null, document.URL);
         window.addEventListener('popstate', function () {
             history.pushState(null, null, document.URL);
         });
    	 
            $('#tb').tab({
                defaultIndex: 0,
                activeClass: 'weui-bar__item_on',
                onToggle: function (index) {
                    //$("#chat"+index).show();
                }
            });
            
            $('.tab-bottom').on('click','.p-btn',function(){
    			if(canSend==false) return;
    			if(null==$("#chatMsg").val()||""==$("#chatMsg").val().trim()){
    				return;
    			}
    			sendMsg($("#userChatCode").html(),3,$("#chatMsg").val());
    			reply(userCode,userName,$("#chatMsg").val(),'','1月27日 11:33',1);
    			$("#chatMsg").val('');
    			scrollToBottom();
    		})
    		$("#chatMsg").blur(function(){
    			setSendBtn();
    		});
    		//reply(11,'系统','你好工工工工工','','1月27日 11:33',0);
    		scrollToBottom();
    		
    		//底部切换
    		$('.weui-tabbar__item').on('click', function () {
                $(this).addClass('weui-bar__item_on').siblings('.weui-bar__item_on').removeClass('weui-bar__item_on');
            });
    		
    		navigator.mediaDevices.enumerateDevices().then(gotDevices).catch(handleError);
        });
     var timSendStart;//推送定时器
     var timSendEnd;//推送定时器
   //用户编号
     var userCode="${userCode}";
     var userName="${userName}";
     var tryLink=0;//尝试连接服务器次数
     var ws;
     var WebSocketFunc = {};
     WebSocketFunc.init = function(uri,token) {//ws开始
     ws = new WebSocket("wss://"+uri+"/ws");
     //ws = new WebSocket("ws://"+"192.168.0.103:8086"+"/ws");
     ws.onopen = function(){  
        //console.log("open");
        //初始化绑定信息
        var bindMsg = {};
        var from={};
        
        bindMsg.cmd="1";
        from.userCode=userCode;
        from.userName=userName;
        bindMsg.from=from;
        bindMsg.msg=token;
        //console.log("登录");
        ws.send(JSON.stringify(bindMsg));
     };

     ws.onmessage = function(evt){
       //console.log(evt.data);
       if("pong"==evt.data){
     	  return;
       }else if("Heartbeat"==evt.data){
        ws.send("Heartbeat");
     	return;  
       }
       //console.log(eval("("+evt.data+")"));
       var message=eval("("+evt.data+")");
       if("-1"==message.cmd){//退出
     	  $.toast(message.msg, 'text');
     	  window.location.href="${httpServletRequest.getContextPath()}/user/logOut";
     	  return false;
        }else if("1"==message.cmd){//登录成功
     	   getOldUserCode();
        }else if("2"==message.cmd){//广播
        	if(message.from.userCode==$("#userChatCode").html()){
        		reply(message.from.userCode,message.from.userName,message.msg,'','1月27日 11:33',0);
        		scrollToBottom();
        	}
        
        	if($("#chatNewMsg"+message.from.userCode).length<1){
                $("#chat0").append(getOldUserCodeHmtl(message.from.userCode,message.from.userName));
        	}   
        
        	$("#chatNewMsg"+message.from.userCode).html(message.msg);
        	
        }else if("3"==message.cmd){//获取单聊
        	var isImage=false;
        	if(message.from.userCode==$("#userChatCode").html()){
        		var base64Img=loadImage(message.msg);
        		if(""!=base64Img){
        			message.msg=base64Img;
        			isImage=true;
        		}
        		reply(message.from.userCode,message.from.userName,message.msg,'','1月27日 11:33',0);
        		scrollToBottom();
        	}
        	
        	if(isImage || message.msg.startsWith('<img src="/')){
        		message.msg="有图片过来...";
        	}
        
        	if($("#chatNewMsg"+message.from.userCode).length<1){
                $("#chat0").append(getOldUserCodeHmtl(message.from.userCode,message.from.userName));
        	}   
        	
        	$("#chatNewMsg"+message.from.userCode).html(message.msg);
        	
        }else if("5"==message.cmd){//获取在线的用户信息
      	  var currentUser=message.chatSet;
    	  $("#onlineUser").html("");
    	  for(var i = 0; i < currentUser.length; i++){
             $("#onlineUser").append(viewOnlineUser(currentUser[i].userCode,currentUser[i].userName,3));
    	  }
        }else if("9"==message.cmd){//获取历史聊天信息
        	var currentUser=message.oldMsg;
      	    for(var message of currentUser){//单聊
      	    	var base64Img=loadImage(message.msg);
        		if(""!=base64Img){
        			message.msg=base64Img;
        		}
      		  if("3"==message.cmd){
      			if(userCode!=message.from.userCode){
      				reply(message.from.userCode,message.from.userName,message.msg,'','1月27日 11:33',0);
      				scrollToBottom();
      			}else{
      				reply(message.from.userCode,message.from.userName,message.msg,'','1月27日 11:33',1);
      				scrollToBottom();
      			}
      		  }else if("4"==message.cmd){//群聊
      			  
      		  }
      	    }
        }else if("10"==message.cmd){//获取历史聊天用户
      	  var currentUser=message.chatSet;
    	  $("#chat0").html("");
    	  for(var i = 0; i < currentUser.length; i++){
              $("#chat0").append(getOldUserCodeHmtl(currentUser[i].userCode,currentUser[i].userName));
    	  }
        }else if("14"==message.cmd){//request refuse accept
      	  if("accept"==message.msg){
      		star();
      		timSendEnd=setInterval(sendVoice ,800,message.from.userCode);
      		 $.modal({
                 title: "语音中",
                 text: userCode+"~~~~"+message.from.userCode,
                 buttons: [
                     { text: "取消", className: "default", onClick: function(){ 
                    	  sendMsg(message.from.userCode,14,"close");
                    	  stop();
        		          clearInterval(timSendStart);
     		              clearInterval(timSendEnd);} },
                 ]
             });
    	  }else if("request"==message.msg){
    		  $.confirm("是否接收语音通话?", "", function() {
    	    		 sendMsg(message.from.userCode,14,"accept");
    	    		 
    	    		 $.modal({
    	                 title: "语音中",
    	                 text: userCode+"~~~~"+message.from.userCode,
    	                 buttons: [
    	                     { text: "取消", className: "default", onClick: function(){ 
    	                    	 sendMsg(message.from.userCode,14,"close");
    	                    	 stop();
    	        		         clearInterval(timSendStart);
    	     		             clearInterval(timSendEnd);	 
    	                     } },
    	                 ]
    	             });
    	    		 
    	    		 star();
    	    		 timSendStart=setInterval(sendVoice ,800,message.from.userCode);
    	    		 
    	         }, function() {
    	        	 sendMsg(message.from.userCode,14,"refuse");
    	         });
    	  }else if("refuse"==message.msg){
    		  $.toast('对方拒绝。。。', "cancel");
    	  }else if("close"==message.msg){
    		  stop();
    		  clearInterval(timSendStart);
    		  clearInterval(timSendEnd);
    		  $.closeModal();
    		  $.toast('聊天结束。。。','text');
    	  }else{//接收的语音信息
    		  remotePlay(message.msg);
    	  }
      }
     };
     
     function loadImage(msg){
    	 if(msg.startsWith('<img src="/')){
     		var fileName=msg.substring(11);
     		    fileName=fileName.substring(0,fileName.indexOf('"'));
     		    console.log("imageName:"+fileName);
     	    var base64=getImage(fileName);
     	    if(""!=base64){
     	    	return '<img src="'+base64+'" onclick="view(this)" height="150px" width="180px">';
     	    }
     	}
    	return "";
     }
     
     ws.onerror = function(evt){
    	  stop();
    	  clearInterval(timSendStart);
		  clearInterval(timSendEnd);
    	  console.log("WebSocketError!");
     };
    
     ws.onclose = function(evt){
    	 stop();
    	 clearInterval(timSendStart);
		 clearInterval(timSendEnd);
       //这里三次重试机会
      for(;tryLink<5;tryLink++){
    	  $.toast('连接中断获取服务地址['+(tryLink+1)+']次!', 1000); 
     	  sleep(2000); //当前方法暂停1秒
     	  var tryLogin=false;
     	  $.ajax({
     		    url:"${httpServletRequest.getContextPath()}/user/server-list",
     		    type:"Post",
     		    async:false,//同步
     		    dataType:"json",
     		    success:function(data){
     		    	var nettyServer=data.nettyServer;
     		    	//console.log("获取server:"+nettyServer);
     		    	if(null!=nettyServer && ""!=nettyServer){
     		    		 WebSocketFunc.init(nettyServer,data.loginToken);
     		    		 tryLogin=true;
     		    		console.log("获取成功。。。");
     		    	}else{
     		    		console.log("获取失败。。。");
     		    		nettyServer=false;
     		    	}
     		    },
     		     error:function(data){
     		     console.log("获取服务器失败...");
     		     nettyServer=false;
     		    }
     		});
     	  
     	  if(tryLogin){
     		  return;
     	  }
       }
     	
       console.log("WebSocketClosed!");
       clearSchedule();
       $.toast('连接中断...稍后请刷新!', 'text'); 
     };
     }//ws结束
     
     function sleep(d){
    	  for(var t = Date.now();Date.now() - t <= d;);
     }
     //取消掉定时任务
     function clearSchedule(){
     	  clearInterval(getUserT);
     	  clearInterval(getGroupUserT);
     	  clearInterval(timSendStart);
		  clearInterval(timSendEnd);
     	  //clearInterval(getPingT);
     	  //clearInterval(getOldUserCodeT);
     	  //clearInterval(getAudioLiveUserCodeT);
     }

     //websocket初始化
     WebSocketFunc.init("${nettyServer}","${loginToken}");
     
     
     //直接方式发送数据
     function sendMsg(name,cmd,message){
     		var bindMsg = {};
     		var from ={};
     		var accept={};
     		var group={};
     	    from.userCode=userCode;
     	    bindMsg.cmd=cmd;
     	    bindMsg.from=from;
     	    
     	    accept.userCode=name;
         	bindMsg.accept=accept;
         	
         	if("12"==cmd){//直播
         		group.groupCode=name;
         		bindMsg.group=group;
         	}
         	
     		bindMsg.msg=HTMLEncode(message);
     		console.log(bindMsg);
     	    ws.send(JSON.stringify(bindMsg));
     };
     
     
   //5.获取用户信息 6获取群组用户信息
     function getAllUser(cmd,groupCode){
     	 var bindMsg = {};
     	 var from={};
     	 bindMsg.cmd=cmd;
     	 from.userCode=userCode;
     	 bindMsg.from=from;
     	 
          if("7"==cmd || "8"==cmd){
         	 var group={};
         	 group.groupCode=groupCode;
         	 bindMsg.group=group;
          }	 
     	 ws.send(JSON.stringify(bindMsg));
     }
     //setInterval(getAllUser ,5000); 
     var getUserT = setInterval(function(){getAllUser(5,"");},5000);
     var getGroupUserT = setInterval(function(){getAllUser(6,"");},5000);
     
     //获取旧聊天用户信息
     function getOldUserCode(){
         sendMsg("",10,"");
     }
     //var getOldUserCodeT = setInterval(getOldUserCode ,5000);
     
   //历史聊天用户信息
     function getOldUserCodeHmtl(toUserCode,toUserName,message){
	     if(null==message){
	    	 message="...";
	     }
	     var name=toUserName.charAt(0);
	     
    	 var oldHtml='<div class="weui-cells demo_badge_cells" id="chat'+toUserCode+'">'+
                       '<div class="weui-cell weui-cell_active" onclick=\'viewChat(\"'+toUserCode+'\",\"'+toUserName+'\",\"chatFull\");\'>'+
                          '<div class="weui-cell__hd">'+
                            //'<img src="${httpServletRequest.getContextPath()}/weui/images/pic_160.png">'+
                            '<div class="head-container"><span class="head-content">'+name+'</span></div>'+
                            '<span class="weui-badge">8</span>'+
                          '</div>'+
                          '<div class="weui-cell__bd">'+
                            '<p>'+toUserName+'</p>'+
                            '<p class="demo_badge_desc" id="chatNewMsg'+toUserCode+'">'+message+'</p>'+
                          '</div>'+
                       '</div>'+
                      '</div>';
         return oldHtml;
     }
   
     function viewOnlineUser(toUserCode,toUserName,type){
    	 var name=toUserName.charAt(0); 
    	 var onlineUserHtml='<div class="weui-cell weui-cell_active" onclick=\'viewChat(\"'+toUserCode+'\",\"'+toUserName+'\",\"chatFull\");\'>'+
                            '<div class="weui-cell__hd">'+
                            '<div class="head-container"><span class="head-content">'+name+'</span></div>'+
                            '</div>'+
                            '<div class="weui-cell__bd">'+
                            '<p>'+toUserName+'</p>'+
                            '</div>'+
                            '</div>';
         return onlineUserHtml;
     }
     
     //展示聊天信息
     function viewChat(toUserCode,toUserName,showID){
    	 //清空
    	 $("#userChat").html("");
    	 $("#userChatName").html(toUserName);
    	 $("#userChatCode").html(toUserCode);
    	 $("#chatMsg").val('');
    	 sendMsg(toUserCode,9,"");//获取历史聊天信息
    	 $("#"+showID).popup();
     }
     
   //清空聊天信息
     function closeViewChat(showID){
    	 //清空
    	 $("#userChat").html("");
    	 $("#userChatName").html("");
    	 $("#userChatCode").html("");
    	 $("#chatMsg").val('');
    	 //$("#"+showID).closePopup();
     }
     
     function setSendBtn(){
 		var pbtn = $(".p-btn");
 		if($("#chatMsg").val().length>0){
 			pbtn.css('background','#114F8E').prop('disabled',true);
 			canSend=true;
 		}else{
 			canSend=false;
 			pbtn.css('background','#ddd').prop('disabled',false);
 		}
 	}
     
     function reply(id,name,msg,img,time,reply){
    	var icon = name=='系统'?'icon-40 f-red f11':'icon-120 f-green';
 		var img = img==''?'${httpServletRequest.getContextPath()}/weui/images/favicon.png':img;
 		var headName=name.charAt(0);
 		//msg=HTMLEncode(msg);
 		var html='<div class="weui-cells reply'+reply+'" id="reply'+id+'">'+
 			'<div class="weui-cell">'+
 				'<div class="weui-cell__hd" style="position: relative;">'+
 					//'<img src="'+img+'" class="" style="width: 50px;display: block">'+
 					 '<div class="head-container"><span class="head-content">'+headName+'</span></div>'+
 				'</div>'+
 				'<div class="weui-cell__bd">'+
 					'<p>'+name+' <span class="icon '+icon+'"></span> <font>'+time+'</font></p>'+
 					'<div class="message">'+msg+'</div>'+
 				'</div>'+
 			'</div>'+
 		'</div>';
 		$("#userChat").append(html);
 		//$(".weui-tab__panel").trigger("create");
 		//自己的消息 改变头像位置
 		if(reply==1){
 			var cell_hd = $("#reply"+id+" .weui-cell__hd");
 			var a = cell_hd.prop("outerHTML");
 					cell_hd.remove();
 			$("#reply"+id+" .weui-cell__bd").after(a);
 		}
 	}

//---------------语音开始--------------------------    
     //语音聊天请求
     function onLineVoice(){
    	 $.confirm("是否发起语音通话?", "", function() {
    		//成功操作
    		 sendMsg($("#userChatCode").html(),14,"request");
    		
    		 $.showLoading();
             setTimeout(function() {
                 $.hideLoading();
             }, 3000);
         }, function() {
             //取消操作
         });
     }
     
     var recorder;
     var audio;
     function star(){
    	    audio=document.querySelector('#audio_from');
    	    playLoad();
    		$('#audio_from').attr('src',"");
    		HZRecorder.get(function (rec) {
    	        recorder = rec;
    	        recorder.start();
    	    }, {
    	            sampleBits: 8,
    	            sampleRate: 16000
    	        });
    		
    		/*  const constraints = {
    				 audio: {
    					 deviceId: {
    					  // deviceInfo.deviceId
    					  exact: audioSelect.value
    					  }
    					}
    			    }; */
    		 //navigator.mediaDevices.enumerateDevices().then(gotDevices).catch(handleError);
    		/* navigator.mediaDevices
            .getUserMedia(constraints)
    	    .then(gotDevices)
    	    .catch(handleError); */
    }
	function stop(){
	  //recorder.stop();
	  recorder.end();
	  i=0;
	  audioIndex=0;
	  voiceArray=[];
	  playVoicee=false;
	}
	
    function paly(){
	 recorder.play(audio);
    }
    
  //绑定摄像头列表到下拉框
    //var audioSelect;
    function gotDevices(deviceInfos) {
    	console.log("设备查找:"+deviceInfos);  
	    if(deviceInfos===undefined){
            return
        }
	    audioSelect = document.querySelector('select#audioSource');
	    $("#audioSource").empty();
	    console.log("所有设备:"+deviceInfos.length);
        for (let i = 0; i !== deviceInfos.length; ++i) {
            const deviceInfo = deviceInfos[i];
            const option = document.createElement('option');
            option.value = deviceInfo.deviceId;
            option.text = deviceInfo.kind+"||"+deviceInfo.label || 'device ' + (audioSelect.length + 1);
        	audioSelect.appendChild(option);
        }
    }
    function handleError(error) {
        console.log('navigator.MediaDevices.getUserMedia error: ', error.message, error.name);
    }
    
    var blobChunk;
    var CHUNK_SIZE = 1024*2;
    var start = 0;
    var end = CHUNK_SIZE;
	function sendVoice(toUserCode){
	     if(null==toUserCode||""==toUserCode){
	    	 toUserCode=$("#userChatCode").html();
	     }
	     
	     if(null==toUserCode||""==toUserCode){
	    	 console.log("接收方没找到用户名称");
	    	 return;
	     }
	     recorder.start();
	     var voiceBase64=recorder.getPcm();
	     recorder.clear();
	     if(null==voiceBase64 || ""==voiceBase64){
	    	 return;
	     }
	     sendMsg(toUserCode,14,voiceBase64);
	}
	var i=0;
	var audioIndex=0;
    var voiceArray=[];
    var playVoicee=false;
    var voiceQueue=new ArrayQueue();
    
	async function  remotePlay(blobVoice){
	  console.log(i++);
      console.log("unZip1:"+blobVoice.length);
      //voiceArray.push(blobVoice);
	  //const devices = navigator.mediaDevices.enumerateDevices();
	  //const audioDevices = devices.filter(device => device.kind === 'audiooutput');
	  //console.log("扬声器:"+audioDevices.length);
	  //audio.setSinkId(audioDevices[0].deviceId);
	  //console.log('Audio is being played on ' + audio.sinkId);
	  if(!playVoicee){
	   var buffer=stringToUint8Array(blobVoice);
	   var fileResult =addWavHeader(buffer, '16000', '8', '1');//解析数据转码wav
	   audio.src = (window.URL||webkitURL).createObjectURL(fileResult);
	   audio.volume = 1;//outside the range [0, 1]
	   audio.loop =false;
	   audio.play();
       audioIndex++;
       playVoicee=true;
	  }else{
		  voiceQueue.push(blobVoice);
	  }
	  /* audioContext.decodeAudioData(fileResult, function(buffer) {
			   _visualize(audioContext,buffer);//播放
			}); */
	}
	
	function playLoad(){
		audio.addEventListener('ended', function () {
			try {
	    	   //console.log("audioIndex:"+audioIndex);
	    	   console.log("voiceQueue:"+voiceQueue.size());
				if(voiceQueue.size()>0){
					  //var buffer=stringToUint8Array(voiceArray[audioIndex]);
					  var buffer=stringToUint8Array(voiceQueue.pop());
					  var fileResult =addWavHeader(buffer, '16000', '8', '1');//解析数据转码wav
					   audio.src = (window.URL||webkitURL).createObjectURL(fileResult);;
					   audio.volume = 1;//outside the range [0, 1]
					   audio.loop =false;
				       audio.play();
				       audioIndex++;
					  }else{
						  playVoicee=false;
					  }
			} catch (error) {
				  console.error(error);
			 }
			}, false);
	}
	
	
	function stringToUint8Array(str){
		  var arr = [];
		  for (var i = 0, j = str.length; i < j; ++i) {
		    arr.push(str.charCodeAt(i));
		  }
		 
		  var tmpUint8Array = new Uint8Array(arr);
		  return tmpUint8Array
    }  
//---------------语音结束--------------------------    
    
   //HTML转义
     function HTMLEncode(str) {
	     str=utf16toEntities(str);
         return filterXSS(str);
     };
     
   //表情
   function utf16toEntities(str) { //检测utf16emoji表情 转换为实体字符以供后台存储
       var patt=/[\ud800-\udbff][\udc00-\udfff]/g;
       str = str.replace(patt, function(temp){
         var H, L, code;
         if (temp.length===2) {   //辅助平面字符（我们需要做处理的一类）
           H = temp.charCodeAt(0); // 取出高位
           L = temp.charCodeAt(1); // 取出低位
           code = (H - 0xD800) * 0x400 + 0x10000 + L - 0xDC00; // 转换算法
           return "&#" + code + ";";
         } else {
           return temp;
         }
       });
       return str;
     }
    
     function scrollToBottom(){
 		var scrollHeight = $('.weui-tab__panel').prop("scrollHeight");
 		$('.weui-tab__panel').scrollTo({toT: scrollHeight});
 	}
 	$.fn.scrollTo =function(options){
         var defaults = {
             toT : 0,    //滚动目标位置
             durTime : 100,  //过渡动画时间
             delay : 30,     //定时器时间
             callback:null   //回调函数
         };
         var opts = $.extend(defaults,options),
             timer = null,
             _this = this,
             curTop = _this.scrollTop(),//滚动条当前的位置
             subTop = opts.toT - curTop,    //滚动条目标位置和当前位置的差值
             index = 0,
             dur = Math.round(opts.durTime / opts.delay),
             smoothScroll = function(t){
                 index++;
                 var per = Math.round(subTop/dur);
                 if(index >= dur){
                     _this.scrollTop(t);
                     window.clearInterval(timer);
                     if(opts.callback && typeof opts.callback == 'function'){
                         opts.callback();
                     }
                     return;
                 }else{
                     _this.scrollTop(curTop + index*per);
                 }
             };
         timer = window.setInterval(function(){
             smoothScroll(opts.toT);
         }, opts.delay);
         return _this;
     };
     function previewImages(file) {
         var MAXWIDTH = 1000;
         var MAXHEIGHT = 1200;
         for (var i = 0; i < file.files.length; i++) {
             if (file.files && file.files[i]) {
            	 /* lrz(file.files[i],{quality:1}).then(function(data){
            		    console.log(data.base64);
            		    $.ajax({
            		      url: '${httpServletRequest.getContextPath()}/fileUpload/imageUploadBase64',
            		      type: 'post',
            		      data: {
            		          img: data.base64
            		      },
            		      dataType: 'json',
            		      //timeout: 200000,
            		      success: function (res) {
            		    	  console.log(res);
                              if("0"==res.code){
                            	//console.log($("#userChatCode").html(),3,'<img src="'+res.data.src+'" alt="'+res.data.title+'" id="im_img">');
                                sendMsg($("#userChatCode").html(),3,'<img src="'+res.data.src+'" alt="'+res.data.title+'" id="im_img">');
                              }
            		      },
            		      error: function() {
            		      }
            		    });
            	 }); */
            	 
            	 var formData=new FormData();
            	 formData.append("file",file.files[i]);
            	 $.ajax({
                     url:'${httpServletRequest.getContextPath()}/fileUpload/imageUpload',
                     dataType:'json',
                     type:'POST',
                     data:formData,
                     processData:false,
                     contentType:false,
                     success:function( res ){
                      console.log(res);
                      if("0"==res.code){
                    	//console.log($("#userChatCode").html(),3,'<img src="'+res.data.src+'" alt="'+res.data.title+'" id="im_img">');
                        sendMsg($("#userChatCode").html(),3,'<img src="'+res.data.src+'" alt="'+res.data.title+'" id="im_img">');
                      }
                     }
                 }); 
                 var reader = new FileReader();
                 reader.onload = function (evt) {
                	 reply(userCode,userName,'<img src="'+evt.target.result+'" onclick="view(this)" style="background-image:url('+evt.target.result+');background-repeat:no-repeat;background-position:center center;"height="150px" width="180px"/>','','1月27日 11:33',1);
                	 //reply(userCode,userName,'<span style="width:180px;height:150px;"><li onclick="view(this)" class="weui-uploader__file" height="150px" width="180px" style="background-image:url('+evt.target.result+');background-repeat:no-repeat;background-position:center center;"></li></span>','','1月27日 11:33',1);
                 }
                 reader.readAsDataURL(file.files[i]);
                 //console.log(file.files[i]);
             }
         }
     }
     
     function getImage(fileName){
    	 var base64="";
    	 var formData=new FormData();
    	 formData.append("imageName",fileName);
    	 $.ajax({
             url:'${httpServletRequest.getContextPath()}/fileUpload/imageBase64',
             dataType:'json',
             type:'POST',
             data:formData,
             processData:false,
             contentType:false,
             async:false,//同步
             success:function( res ){
              //console.log(res);
              if("0"==res.code){
            	  base64=res.msg;
              }
             }
         });
    	 return base64;
     }
     
     function view(img){
    	 $(".weui-gallery__img").attr("style", 'background-image:url('+img.getAttribute("src")+');background-repeat:no-repeat;background-position:center center;"');
         $("#weui-gallery").fadeIn(100);
     };
     function hideImgShow(){
    	 $("#weui-gallery").fadeOut(100);
     };
     
</script>
</head>
<body>
 
<div class="page">
  <div class="weui-gallery" id="weui-gallery" onclick="hideImgShow();" style="display: none">
    <span class="weui-gallery__img"></span>
    <div class="weui-gallery__opr">
    </div>
  </div>

   <div style = "display : none">
 <!--   <div> -->
    <!-- 语音聊天 -->
    <select id="audioSource"></select>
    <!--  -->
    <div>
      <audio id="audio_from" type="audio/wav" controls autoplay></audio>
      <audio id="audio_accept" controls autoplay></audio>
    </div>
   </div> 
    <div class="page__bd" style="height: 100%;">
	
	<div id="chatFull" class='weui-popup__container' style="z-index:777;">
    <div class="weui-popup__overlay"></div>
    <div class="weui-popup__modal">
       <div class="weui-header bg-blue" style="position: fixed;top: 0; width: 100%;z-index: 500;"> 
	    <div class="weui-header-left"> <a class="icon icon-109 f-white close-popup" href='javascript:closeViewChat("chatFull");'>返回</a> </div>
	    <h1 class="weui-header-title" id="userChatName"></h1>
	    <h1 class="weui-header-title hide" id="userChatCode"></h1>
	    <div class="weui-header-right">
	     <a class="f-white" href='javascript:onLineVoice();'>语音</a>
	     <a class="f-white">视频</a>
	     <a class="icon icon-83 f-white">更多</a></div> 
       </div>
       <div class="weui-tab__panel" id="userChat">     
	
       </div>
       <div class="weui-grids tab-bottom weui-tabbar" id="sendmsg">
         <div class="weui-grid" style="width: 62%;">
          <p class="weui-grid__label"><input type="text" id="chatMsg" class="weui-form-input" style="width: 96%;" cursor-spacing="140"/></p>
         </div>
         <div class="weui-grid" style="width: 20%;">
          <p class="weui-grid__label p-btn">发送 </p>
         </div>
         <div class="weui-cells weui-cells_form" id="uploader">
         <div class="weui-uploader__input-box" style=" width:45px;height:45px;">
            <input id="uploaderInput" class="weui-uploader__input" accept="image/*" multiple="" type="file" onchange="previewImages(this)">
         </div>
         </div>
       </div>
     </div>
     </div>
	
        <div id='tb' class="weui-tab">
		    <div class="weui-tab__panel">
              <div id="chat0" class="weui-tab__content">
			   <!--信息-->
			  </div>
			  
              <div id="chat1" class="weui-tab__content">
			  <!--在线-->
			   <div class="weui-cells demo_badge_cells" id="onlineUser">
               </div>
			  </div>
              <div id="chat2" class="weui-tab__content">准备中</div>
              <div id="chat3"  class="weui-tab__content">
	             <div class="weui-form-preview__bd">
	               <div class="weui-form-preview__item">
	               <label class="weui-form-preview__label">用户名</label>
	               <span class="weui-form-preview__value">${userName}</span>
	               </div>
	               <div class="weui-form-preview__item">
	               <label class="weui-form-preview__label">昵称</label>
	               <span class="weui-form-preview__value">${userCode}</span>
	               </div>
	               <div class="weui-form-preview__ft">
                    <a class="weui-form-preview__btn weui-form-preview__btn_primary" href="${httpServletRequest.getContextPath()}/user/logOut">退出</a>
                   </div>
                </div>
              </div>
            </div>
		
            <div class="weui-tabbar tab-bottom">
                <div class="weui-tabbar__item weui-bar__item_on">
                    <div style="display: inline-block; position: relative;">
                        <img src="${httpServletRequest.getContextPath()}/weui/images/icon_tabbar.png" alt="" class="weui-tabbar__icon">
                        <span class="weui-badge weui-badge_dot" style="position: absolute; top: 0; right: -6px;"></span>
                    </div>
                    <p class="weui-tabbar__label">信息</p>
                </div>
                <div class="weui-tabbar__item">
                    <img src="${httpServletRequest.getContextPath()}/weui/images/icon_tabbar.png" alt="" class="weui-tabbar__icon">
                    <p class="weui-tabbar__label">在线</p>
                </div>
                <div class="weui-tabbar__item">
                    <div style="display: inline-block; position: relative;">
                        <img src="${httpServletRequest.getContextPath()}/weui/images/icon_tabbar.png" alt="" class="weui-tabbar__icon">
                        <span class="weui-badge weui-badge_dot" style="position: absolute; top: 0; right: -6px;"></span>
                    </div>
                    <p class="weui-tabbar__label">发现</p>
                </div>
                <div class="weui-tabbar__item">
                    <img src="${httpServletRequest.getContextPath()}/weui/images/icon_tabbar.png" alt="" class="weui-tabbar__icon">
                    <p class="weui-tabbar__label">我</p>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
</html>