$(function(){
//Socket.IO 连接
var socket = io.connect('http://'+document.domain+':9010',{
"transports":['websocket', 'polling']
});
var uuid = '';
function insert_client_html(msg){
var time = dateFormat();
if(msg.time){
time = dateFormat("yyyy-MM-dd hh:mm:ss",new Date(msg.time));
}
if(!msg.chat_type){
msg.chat_type = 'text';
}
var tpl = '
'+
'
'+
'
' + time + ' 我' + '
';
if(msg.chat_type == "text"){
tpl += '
'+
'
'+
'
' + msg.content + '
'+
'
'+
'
';
}else if(msg.chat_type == "image"){
tpl += '
';
}
tpl += '
'+
'
';
$(".msg-container").append(tpl);
}
function insert_agent_html(msg){
var time = dateFormat();
if(msg.time){
time = dateFormat("yyyy-MM-dd hh:mm:ss",new Date(msg.time));
}
if(!msg.chat_type){
msg.chat_type = 'text';
}
var tpl = ''+
'
'+
'
'+
'

'+
'
'+
'
' + time + ' 客服' + '
';
if(msg.chat_type == "text"){
tpl += '
';
}else if(msg.chat_type == "image"){
tpl += '
';
}
tpl += '
'+
'
';
$(tpl).appendTo(".msg-container").find('.text').html(msg.content.replace(/\n/g,"
"));
}
//聊天窗口自动滚到底
function scrollToBottom() {
var div = document.getElementById('msg-container');
div.scrollTop = div.scrollHeight;
}
//获取最新的五条数据
function get_message(uid) {
$.get('/message?uid='+uid,function (data) {
if(data.code == 200){
data.data.reverse().forEach(function (msg) {
if(msg.from_uid == uid){
insert_client_html(msg);
}else{
insert_agent_html(msg);
}
scrollToBottom();
});
}
});
}
const gongHao = 10001;
$("#btnSend").click(function(){
var msg = $("#textarea").val();
if(msg){
var msg_sender = {
"type":'private',
"uid":gongHao,
"content":msg,
"from_uid":uuid,
"chat_type":'text'
};
socket.emit('message', msg_sender);
insert_client_html(msg_sender);
scrollToBottom();
$("#textarea").val('');
}
});
$(".emoji-list li").click(function () {
var content = $("#textarea").val();
$("#textarea").val(content + " " +$(this).html()+ " " );
$(".emoji-list").toggle();
});
$(".emoji-send").click(function () {
$(".emoji-list").toggle();
});
//连接服务器
socket.on('connect', function () {
//uuid = 'chat'+ guid();
let uuid_store_key = 'kf_c_uuid';
uuid = localStorage.getItem(uuid_store_key);
if(!uuid){
uuid = (new Fingerprint()).get();
localStorage.setItem(uuid_store_key,uuid);//save uuid to ls
}
console.log('连接成功...'+uuid);
var ip = $("#keleyivisitorip").text();
var msg = {
"uid" : uuid,
"ip" : ip,
kefu_id:gongHao,
type:'customer'
};
socket.emit('login', msg);
get_message(uuid);
});
// /* 后端推送来消息时
// msg:
// type 消息类型 image,text
// content 消息
// */
socket.on('message', function(msg){
insert_agent_html(msg);
scrollToBottom();
});
socket.on('log',function (msg) {
console.log(msg);
})
});