var uinfo = {
id: 'KF' + uid,
username: uname,
avatar: avatar,
group: group
};
var wsUrl = socket_server;
var ws;//websocket实例
var lockReconnect = false;//避免重复连接
// 确定用户收到消息
var user_receive_msg = false;
// 当前对话用户的信息
var user_info_tmp = {};
// 是否占线
var repetition_line = false;
// // 1console.log("service/mylink");
// var id_payment = (new Date()).valueOf();
// 返回结果如果为true的话那么就创建新链接反之不创建
checkSocketLogin(uid, token, wsUrl);
var check_line = false;
setTimeout(function () {
check_line = sessionStorage.getItem('kf_check_line_' + uid);
// console.log(check_line);
if (check_line) {
sessionStorage.removeItem('kf_check_line_' + uid);
createWebSocket(wsUrl);
}
}, 500);
// 创建一个Socket实例
function createWebSocket(url) {
try {
ws = new WebSocket(url);
eventHandle();
} catch (e) {
reconnect(url);
}
}
function eventHandle() {
ws.onclose = function () {
userStatus(2);
setTimeout(function () {
reconnect(wsUrl);
}, 2000);
};
ws.onerror = function () {
layer.alert('连接失败,正在尝试重连...', { icon: 2, title: '错误提示' });
userStatus(2);
reconnect(wsUrl);
};
ws.onopen = function () {
layui.use(['layer'], function () {
var layer = layui.layer;
layer.ready(function () {
userStatus(1);
//layer.msg('链接成功', { time: 1000 });
});
});
// 登录
var login_data = '{"path":"api\/init","param":{"type":"kf","group_id" : ' + uinfo.group + '},"access_token" : "' + token + '"}';
// console.log(login_data);
ws.send(login_data);
//心跳检测重置
heartCheck.reset().start();
};
ws.onmessage = function (res) {
var data = eval("(" + res.data + ")");
// console.log(data);
user_receive_msg = false;
switch (data['message_type']) {
// 服务端ping客户端
case 'ping':
ws.send('{"type":"ping"}');
break;
// 添加用户
case 'connect':
var timerId = sessionStorage.getItem('timerid_' + uinfo.id + '_' + data.data.user_info.id)
// 1console.log(timerId)
if (timerId !== null) {
clearTimeout(timerId)
sessionStorage.removeItem('timerid_' + uinfo.id + '_' + data.data.user_info.id)
onlineOrOffIdent(data.data.user_info.id, 1);
} else {
// 1console.log(data.data.user_info.id);
onlineOrOffIdent(data.data.user_info.id, 1);
addUser(data.data.user_info, data.data.qrcode);
// 离线用户切换为在线用户
var checkuser = 'f-' + data.data.user_info.id;
$("#offline_user_list li").each(function () {
if ($(this).attr('id') == checkuser) {
delOffUser(data.data.user_info);
}
});
// 如果 在线用户tab为折叠状态,则tab上显示新消息提醒
showTabNotice('on');
}
break;
// 移除访客到主面板
case 'delUser':
var timerId = setTimeout(function () {
delUser(data.data);
$("#on_span").attr('class', 'fold');
sessionStorage.removeItem('timerid_' + uinfo.id + '_' + data.data.id)
// }, 1000);
}, 3 * 60 * 1000);
sessionStorage.setItem('timerid_' + uinfo.id + '_' + data.data.id, timerId)
systemHint(data.data.userinfo.uid, `系统提示: ${data.data.userinfo.name} 已离线!`);
onlineOrOffIdent(data.data.userinfo.uid, 2);
// layer.msg('用户:' + data.data.userinfo.name + '已离线!');
break;
// 监测聊天数据
case 'text':
var chekc_msg = checkMsgIsRepeat(user_info_tmp.u_id, data.data.msg_id);
if (chekc_msg) return;
showUserMessage(data.data, data.data.content);
break;
case 'img':
// 1console.log("收到用户消息");
var chekc_msg = checkMsgIsRepeat(user_info_tmp.u_id, data.data.msg_id);
if (chekc_msg) return;
showUserMessage(data.data, data.data.content);
break;
// 处理转接结果通知
case 'changeGroupResult':
var chekc_msg = checkMsgIsRepeat(user_info_tmp.u_id, data.data.msg_id);
if (chekc_msg) return;
// 转接成功
if (data.data.status) {
// 将该会员从我的会话中移除
var id = $("#active-user").attr('data-id');
delUser({ id: id });
}
// 提示结果信息
layer.msg(data.data.content);
break;
// 提示信息
case 'alert':
var chekc_msg = checkMsgIsRepeat(user_info_tmp.u_id, data.data.msg_id);
if (chekc_msg) return;
layer.msg(data.data.content);
break;
// 确定用户收到发送的消息
case 'received':
// user_receive_msg = true;
// 消息状态
sessionStorage.setItem('send_time_receive_msg_' + uinfo.id + '_' + user_info_tmp.u_id + '_' + data.data.msg_id, true);
// 清除定时器
var send_time = sessionStorage.getItem('send_time_' + uinfo.id + '_' + user_info_tmp.u_id + '_' + data.data.msg_id);
// // 1console.log(send_time);
clearTimeout(send_time);
// 移除重发消息次数
reSendMsgNum(data.data.msg_id, 'del');
// 1console.log("对方已成功接收到客服发送的信息");
// 1console.log(data);
break;
// 自动回复
case 'auto_reply':
var chekc_msg = checkMsgIsRepeat(user_info_tmp.u_id, data.data.msg_id);
if (chekc_msg) return;
id_payment = (new Date()).valueOf();
// sendMessage(data.data.content)
var msg = data.data.content;
var msg_id = uuid();
if (data.data.payment != "" && data.data.payment != null) {
sessionStorage.setItem("data", JSON.stringify(data.data));
var payment = data.data.payment;
switch (payment) {
case 'wexin':
var msg = "img[" + "/static/service/images/payment/ic_bg_payment1.png" + "]"
break;
case 'alipay':
var msg = "img[" + "/static/service/images/payment/ic_bg_payment.png" + "]"
break;
case 'huabei':
var msg = "img[" + "/static/service/images/payment/ic_bg_payment34.png" + "]"
break;
case 'credit':
var msg = "img[" + "/static/service/images/payment/ic_bg_payment6.png" + "]"
break;
case 'bank':
var msg = "img[" + "/static/service/images/payment/ic_bg_payment2.png" + "]"
break;
default:
break;
}
}
var word = msgFactory(msg, 'mine', uinfo, payment, msg_id);
// var uid = $("#active-user").attr('data-id');
// var uname = $("#active-user").attr('data-name');
var uid = data.data.data.to_id;
var uname = data.data.data.to_name;
//微信缓存
if (data.data.payment != "" && data.data.payment != null && data.data.payment == 'wexin') {
sessionStorage.setItem("payment_wexin", JSON.stringify(data.data));
}
//支付宝缓存
if (data.data.payment != "" && data.data.payment != null && data.data.payment == 'alipay') {
sessionStorage.setItem("payment_alipay", JSON.stringify(data.data));
}
//花呗缓存
if (data.data.payment != "" && data.data.payment != null && data.data.payment == 'huabei') {
sessionStorage.setItem("payment_huabei", JSON.stringify(data.data));
}
//信用卡缓存
if (data.data.payment != "" && data.data.payment != null && data.data.payment == 'credit') {
sessionStorage.setItem("payment_credit", JSON.stringify(data.data));
}
//银行卡缓存
if (data.data.payment != "" && data.data.payment != null && data.data.payment == 'bank') {
sessionStorage.setItem("payment_bank", JSON.stringify(data.data));
}
if (data.data.payment != '' && data.data.payment != null) {
var payment_type = data.data.payment
if (payment_type == 'wexin') {
var wexin = sessionStorage.payment_wexin;
var wexin = JSON.parse(wexin).payment;
$("#" + id_payment).attr("payment", wexin)
} else if (payment_type == 'alipay') {
var alipay = sessionStorage.payment_alipay;
var alipay = JSON.parse(alipay).payment;
$("#" + id_payment).attr("payment", alipay)
} else if (payment_type == 'huabei') {
var huabei = sessionStorage.payment_huabei;
var huabei = JSON.parse(huabei).payment;
$("#" + id_payment).attr("payment", huabei)
} else if (payment_type == 'credit') {
var credit = sessionStorage.payment_credit;
var credit = JSON.parse(credit).payment;
$("#" + id_payment).attr("payment", credit)
} else if (payment_type == 'bank') {
var bank = sessionStorage.payment_bank;
var bank = JSON.parse(bank).payment;
$("#" + id_payment).attr("payment", bank)
}
}
ws.send(JSON.stringify({
path: 'api\/chat',
param: {
type: 'kf', payment: data.data.payment, data: data.data.data, to_id: uid, to_name: uname, content: data.data.content, from_name: uinfo.username,
from_id: uinfo.id, from_avatar: uinfo.avatar, msg_id: msg_id,
},
access_token: token
}));
$("#u-" + uid).append(word);
$(".msg-area").val('');
// var uid = $("#active-user").attr('data-id');
// var uname = $("#active-user").attr('data-name');
// var time = getTime();
var time = data.data.time;
var key = uinfo.id + '-' + uid;
if (typeof (Storage) !== "undefined") {
var localMsg = msgQueueCheck(getCache(key));
if (localMsg == null || localMsg.length == 0) {
localMsg = [];
}
localMsg.push({ type: 'mine', from_id: uinfo.id, from_name: uinfo.username, time_line: time, to_name: uname, to_id: uid, img_id: id_payment, payment: data.data.payment, data: data.data.data, content: data.data.content, from_avatar: uinfo.avatar, msg: msg, msg_id: msg_id });
cacheChat({ key: key, data: localMsg });
}
clickpayment();
// 滚动条自动定位到最底端
wordBottom();
checkUserReceiveMsg(`${msg_id}`, 2);
break;
case 'repetition_line':
repetition_line = true;
// layer.msg('账号重复登录链接已断开');
layer.alert('该账号已在别处登录, 请重新登录!', { title: false, closeBtn: 0 }, function () {
userStatus(2);
window.parent.location.href = '/service/login/loginout';
});
break;
}
//如果获取到消息,心跳检测重置
//拿到任何消息都说明当前连接是正常的
heartCheck.reset().start();
}
}
/**
* 过滤消息队列
* @param {*} msg_list 消息列表
* @param {*} length 长度
*/
function msgQueueCheck(msg_list, length = 50) {
if (typeof msg_list == "undefined" || msg_list == null || msg_list == "") return msg_list;
if (msg_list.length < length) return msg_list;
// $new_list = msg_list.slice(msg_list.length - length, length);
$new_list = msg_list.slice(msg_list.length - length);
return $new_list;
}
/**
* 客服状态
*/
function userStatus(type = 1) {
var color = type == 1 ? '#5dea85' : '#f73939';
setTimeout(function () {
parent.$('#user_status').css('cssText', `background-color: ${color} !important`);
}, 1000);
}
/**
* 系统提示
* @param {*} uid 用户id
* @param {*} content 提示内容
* @date 20190413
*/
function systemHint(uid, content) {
var msg_box = $('#u-' + uid);
if (!msg_box) return false;
var hint_html = `
${content}
`;
msg_box.append(hint_html);
wordBottom();
}
/**
* 用户上线或者下线提示标识
* @param {*} uid 用户id
* @param {*} type 提示类型: 1: 上线, 2: 下线
*/
function onlineOrOffIdent(uid, type) {
var user_dom = $('#f-' + uid);
user_dom.find('.ident').remove();
switch (type) {
case 1:
user_dom.append(``);
break;
case 2:
user_dom.append(``);
break;
}
}
function reconnect(url) {
if (lockReconnect || repetition_line == true) return;
lockReconnect = true;
//没连接上会一直重连,设置延迟避免请求过多
setTimeout(function () {
createWebSocket(url);
lockReconnect = false;
}, 2000);
}
function clickpayment() {
// // 1console.log(6754213423);
// payShowLayer();
// $(".layui-mylink-photos").on('click', function () {
// $(".layui-mylink-photos").on('click', function () {
// });
}
/**
* 支付显示
* @param {*} _this 当前点击对象
*/
function payShowLayer(_this) {
sessionStorage.getItem("payment");
//支付宝
var alipay_data = sessionStorage.payment_alipay;
// 1console.log(this);
if (alipay_data) {
var src = JSON.parse(alipay_data).content
var length = src.length
var img_alipay = src.substring(4, length - 1)
var alipay = JSON.parse(alipay_data).payment
var name = JSON.parse(alipay_data).data.name
var account_num = JSON.parse(alipay_data).data.account_num
} else {
var alipay = ''
}
//微信
var wexin = sessionStorage.payment_wexin;
if (wexin) {
var src = JSON.parse(wexin).content
var length = src.length
var img_wexin = src.substring(4, length - 1)
var wexin = JSON.parse(wexin).payment
} else {
var wexin = ''
}
//花呗
var huabei = sessionStorage.payment_huabei;
if (huabei) {
var src = JSON.parse(huabei).content
var length = src.length
var img_huabei = src.substring(4, length - 1)
var huabei = JSON.parse(huabei).payment
} else {
var huabei = ''
}
//信用卡
var credit = sessionStorage.payment_credit;
if (credit) {
var src = JSON.parse(credit).content
var length = src.length
var img_credit = src.substring(4, length - 1)
var credit = JSON.parse(credit).payment
} else {
var credit = ''
}
//银行卡
var bank_data = sessionStorage.payment_bank;
if (bank_data) {
var bank = JSON.parse(bank_data).payment
var name = JSON.parse(bank_data).data.name
var account_num = JSON.parse(bank_data).data.account_num
var branch_bank = JSON.parse(bank_data).data.branch_bank
var open_bank = JSON.parse(bank_data).data.open_bank
} else {
var bank = ''
}
var data = sessionStorage.data;
if (data) {
var src = JSON.parse(data).content
var length = src.length
var img = src.substring(4, length - 1)
} else {
var src = ''
}
if ($(_this).attr('payment') == '' && $(_this).attr('payment') == 'undefined') {
// // showBigPic();
} else {
if (wexin == $(_this).attr('payment')) {
var _html = "";
_html += ""
_html += "
" + ' ' + "微信二维码收款
"
_html += "
保存二维码到相册,微信|扫一扫|付钱
"
_html += "

"
layer.open({
title: false,
content: _html,
btn: false,
skin: "wexin",
isOutAnim: false
});
} else if (alipay == $(_this).attr('payment')) {
var _html = "";
_html += ""
_html += "
" + ' ' + "支付宝二维码收款
"
_html += "
保存二维码到相册,支付宝|扫一扫|付钱
"
_html += "

"
_html += "
"
_html += "
" + ' ' + "支付宝账号转账
"
_html += "
可用支付宝,支付宝[转账]付钱
"
_html += "
支付宝账号 | " + name + " |
"
_html += "支付宝姓名 | " + account_num + " |
"
layer.open({
title: false,
content: _html,
auto: ['500px', '500px'],
btn: false,
skin: "alipay",
isOutAnim: false
});
} else if (huabei == $(_this).attr('payment')) {
var _html = "";
_html += ""
_html += "
" + ' ' + "蚂蚁花呗二维码收款
"
_html += "
保存二维码到相册,支付宝|扫一扫|付钱
"
_html += "

"
_html += "
"
_html += "
" + ' ' + "温馨提示
"
_html += "
**花呗充值会收取手续费,详情请咨询专业**
"
_html += "
为避免扫码失败,使用支付宝扫码之前,请关闭wifi,用手机流量来扫码支付
"
_html += "
"
layer.open({
title: false,
content: _html,
auto: ['500px', '500px'],
btn: false,
skin: "huabei",
isOutAnim: false
});
} else if (credit == $(_this).attr('payment')) {
var _html = "";
_html += ""
_html += "
" + ' ' + "信用卡二维码收款
"
_html += "
保存二维码到相册,支付宝|扫一扫|付钱
"
_html += "

"
_html += "
"
_html += "
" + ' ' + "温馨提示
"
_html += "
**信用卡充值会收取手续费,详情请咨询专业**
"
_html += "
同时支持支付宝与微信扫码
"
_html += "
为避免扫码失败,使用支付宝扫码之前,请关闭wifi,用手机流量来扫码支付
"
_html += "
若进行大额支付,使用微信扫码会比支付宝成功率高哦~
"
_html += "
"
layer.open({
title: false,
content: _html,
auto: ['500px', '500px'],
btn: false,
skin: "credit",
isOutAnim: false
});
} else if (bank == $(_this).attr('payment')) {
var _html = "";
_html += ""
_html += "
" + ' ' + "银行卡收款
"
_html += "
可用支付宝,微信[转账到银行卡]功能付钱
"
_html += "
银行卡姓名 | " + name + " |
"
_html += "银行卡号 | " + account_num + " |
"
_html += "开户银行 | " + open_bank + " |
"
_html += "开户支行 | " + branch_bank + " |
"
_html += "
"
_html += "
" + ' ' + "温馨提示
"
_html += "
**信用卡充值会收取手续费,详情请咨询专业**
"
_html += "
同时支持支付宝与微信扫码
"
_html += "
为避免扫码失败,使用支付宝扫码之前,请关闭wifi,用手机流量来扫码支付
"
_html += "
若进行大额支付,使用微信扫码会比支付宝成功率高哦~
"
_html += "
"
layer.open({
title: false,
content: _html,
auto: ['500px', '500px'],
btn: false,
skin: "credit",
isOutAnim: false
});
}
}
}
//心跳检测
var heartCheck = {
timeout: 30000,//10秒
timeoutObj: null,
serverTimeoutObj: null,
reset: function () {
clearTimeout(this.timeoutObj);
clearTimeout(this.serverTimeoutObj);
return this;
},
start: function () {
var self = this;
this.timeoutObj = setTimeout(function () {
//这里发送一个心跳,后端收到后,返回一个心跳消息,
//onmessage拿到返回的心跳就说明连接正常
ws.send(JSON.stringify({
path: 'ping',
param: { 'type': 'kf' }
}));
self.serverTimeoutObj = setTimeout(function () {//如果超过一定时间还没重置,说明后端主动断开了
ws.close();//如果onclose会执行reconnect,我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次
}, self.timeout);
}, this.timeout);
}
};
/**
* 缓存用户数据
* @param data
*/
function cacheUserData(data) {
var uid = data.id;
// 1console.log(uid + '用户数据:');
//存储订单数据
// sessionStorage.setItem("f-"+uid, JSON.stringify(data.data));
}
/**
* 商品与订单模板渲染
* @param id
*/
function order_view(id, type) {
// 1console.log('order_view');
// layui.use('laytpl', function(){
// var laytpl = layui.laytpl;
// var data = sessionStorage.getItem('f-'+id);
// if(!data) return false;
// data = JSON.parse(data);
// //渲染模版
// var getTpl = $('#'+data.type+'_tpl').html();
// laytpl(getTpl).render(data[data.type], function(html){
// if(type == 'del') html = '';
// $('#order_list').html(html);
// });
// };
// });
}
$(function () {
// 获取服务用户列表(在线用户)
$.getJSON('/service/index/getUserList', function (res) {
// 1console.log('----');
// 1console.log(res);
// 1console.log('------');
if (1 == res.code) {
if (res.data.length > 0) {
// 如果有在线用户则展开tab
$("#on_span").attr('class', 'unfold');
// 添加用户
$.each(res.data, function (k, v) {
addUser(v, v.qrcode);
});
var id = $(".layui-unselect").find('li').eq(0).data('id');
var name = $(".layui-unselect").find('li').eq(0).data('name');
var avatar = $(".layui-unselect").find('li').eq(0).data('avatar');
var ip = $(".layui-unselect").find('li').eq(0).data('ip');
// 默认设置第一个用户为当前对话的用户
$("#active-user").attr('data-id', id).attr('data-name', name).attr('data-avatar', avatar).attr('data-ip', ip);
$(".all_user_list").find('li').eq(0).addClass('active').find('span:eq(1)').removeClass('layui-badge').text('');
$("#f-user").val(name);
$("#f-user-id").val(id);
$("#coin_uid").val(id);
$("#f-ip").val(ip);
// 储存用户信息
user_info_tmp = {
u_id: id,
u_name: name,
u_avatar: avatar,
u_ip: ip,
}
$.getJSON('/service/index/getCity', { ip: ip }, function (res) {
$("#f-area").val(res.data);
});
// 拉取和这个人的聊天记录
// 1console.log("拉取这个人的聊天记录");
$("#u-" + id).addClass('show-chat-detail');
getChatLog(id, 1);
// 渲染首个订单模板
order_view(id);
}
}
});
$.getJSON('/service/index/getOfflineUserList', function (res) {
// 1console.log('----');
// 1console.log(res);
// 1console.log('------');
if (res.code == 1) {
if (res.data.length > 0) {
// console.log(res.data);
$.each(res.data, function (k, v) {
// 重置离线状态缓存
sessionStorage.removeItem('timerid_' + uinfo.id + '_' + v.id);
addOffLineUser(v, 1);
});
// 添加提示
// var offline_hint_html = `温馨提示: 仅显示最近3天, 更多请到会话记录查询
`;
// var offline_html = offline_hint_html + $('#offline_user_list').html();
// $('#offline_user_list').html(offline_html);
/**
* 初始化不需要加载离线用户数据
*/
// var id = $(".layui-unselect").find('li').eq(0).data('id');
// var name = $(".layui-unselect").find('li').eq(0).data('name');
// var avatar = $(".layui-unselect").find('li').eq(0).data('avatar');
// var ip = $(".layui-unselect").find('li').eq(0).data('ip');
// 默认设置第一个用户为当前对话的用户
// $("#active-user").attr('data-id', id).attr('data-name', name).attr('data-avatar', avatar).attr('data-ip', ip);
// $(".all_user_list").find('li').eq(0).addClass('active').find('span:eq(1)').removeClass('layui-badge').text('');
// $("#f-user").val(name);
// $("#f-user-id").val(id);
// $("#f-ip").val(ip);
// $.getJSON('/service/index/getCity', {ip: ip}, function(res){
// $("#f-area").val(res.data);
// });
//
// // 拉取和这个人的聊天记录
// // 1console.log("拉取这个人的聊天记录");
// $("#u-" + id).addClass('show-chat-detail');
// getChatLog(id, 1);
// //渲染首个订单模板
// order_view(id);
}
}
});
// 监听快捷键发送
document.getElementById('msg-area').addEventListener('keydown', function (e) {
// if (e.keyCode != 13) return;
if (event.keyCode == 13) {
e.preventDefault(); // 取消事件的默认动作
sendMessage();
}
});
// 点击表情
var index;
$("#face").click(function (e) {
e.stopPropagation();
layui.use(['layer'], function () {
var layer = layui.layer;
var isShow = $(".layui-mylink-face").css('display');
if ('block' == isShow) {
layer.close(index);
return;
}
var height = $(".chat-box").height() - 110;
layer.ready(function () {
index = layer.open({
type: 1,
offset: [height + 'px', $(".layui-side").width() + 'px'],
shade: false,
title: false,
closeBtn: 0,
area: '395px',
content: showFaces()
});
});
});
});
$(document).click(function (e) {
layui.use(['layer'], function () {
var layer = layui.layer;
if (isShow) {
layer.close(index);
return false;
}
});
});
// 发送消息
$("#send").click(function () {
sendMessage();
});
// hover用户
$(".layui-unselect li").hover(function () {
$(this).find('i').show();
}, function () {
$(this).find('i').hide();
});
// 关闭用户
$('.close').click(function () {
var uid = $(this).parent().data('id');
$(this).parent().remove(); // 清除左侧的用户列表
$('#u-' + uid).remove(); // 清除右侧的聊天详情
});
// 检测滚动,异步加载更多聊天数据
$(".chat-box").scroll(function () {
var top = $(".chat-box").scrollTop();
});
// 会员转接
$("#scroll-link").click(function () {
return false;
var id = $("#active-user").attr('data-id');
var name = $("#active-user").attr('data-name');
var avatar = $("#active-user").attr('data-avatar');
var ip = $("#active-user").attr('data-ip');
if (id == '' || name == '') {
layer.msg("请选择要转接的会员");
}
// 二次确认
var layerIndex = null;
layerIndex = layer.confirm('确定转接', {
title: '转接提示',
closeBtn: 0,
icon: 3,
btn: ['确定', '取消'] // 按钮
}, function () {
layer.close(layerIndex);
layerIndex = layer.open({
title: '',
type: 1,
area: ['30%', '40%'],
content: $("#change-box")
});
// 监听选择
layui.use(['form'], function () {
var form = layui.form;
form.on('select(group)', function (data) {
if (uinfo.group == data.value) {
layer.msg("已经在该分组,不需要转接!");
} else {
layer.close(layerIndex);
var group = data.value; // 分组
// 交换分组
var change_data = '{' +
'"path":"api/changeGroup", ' +
'"param":{"type":"kf", "uer_id":"' + id + '", "user_name" : "' + name + '", "avatar" : "' + avatar + '", "group_id": ' + group + ', "ip" : "' + ip + '"},' +
'"access_token" : "' + token + '"}';
// 1console.log(change_data);
ws.send(change_data);
// layer.msg('转接成功');
}
});
});
}, function () {
});
});
//账号选择
$("#change-account").click(function () {
var id = $("#active-user").attr('data-id');
var name = $("#active-user").attr('data-name');
var avatar = $("#active-user").attr('data-avatar');
var ip = $("#active-user").attr('data-ip');
// if(id == '' || name == ''){
// layer.msg("请选择要转接的会员");
// }
// 二次确认
var layerIndex = null;
// layerIndex = layer.confirm('确定更换支付账号?', {
// title: '转接提示',
// closeBtn: 0,
// icon: 3,
// btn: ['确定', '取消'] // 按钮
// }, function(){
// layer.close(layerIndex);
// layerIndex = layer.open({
// title: '',
// type: 1,
// area: ['30%', '40%'],
// content: $("#account-box")
// });
layer.open({
title: '选择账号',
type: 2,
content: '/service/dialogue/selectAccount',
// content: $("#account-box"),
area: ['600px', '400px']
});
return;
// 监听选择
layui.use(['form'], function () {
var form = layui.form;
form.on('select(type)', function (data) {
$.getJSON('/service/index/changeType', { id: data.value }, function (res) {
var option = '';
option += '';
$("#payment").html();
$.each(res.data, function (key, val) {
if (val.id == 0) {
option += ''
$("#payment").html(option)
form.render('select')
} else {
if (val.is_use == 1 && val.status == 1) {
option += ''
} else {
option += ''
}
$("#payment").html(option)
form.render('select')
}
})
$("#payment").get(0).selectIndex = 0
});
})
form.on('submit(changePayment)', function (data) {
$.getJSON('/service/index/changeAccount', { id: data.field.payment, type: data.field.type }, function (res) {
// // 1console.log(res);
if (1 == res.code) {
layer.closeAll();
layer.msg('更换成功,请刷新页面!');
} else if (0 == res.code) {
layer.msg(res.msg);
}
});
// layer.close(layerIndex);
});
});
// }, function(){
// });
});
});
/**
* 支付选择账号
*/
function paySelect() {
// 1console.log(1111);
layer.open({
title: '选择账号',
type: 2,
content: '/service/dialogue/selectAccount',
// content: $("#account-box"),
area: ['600px', '400px'],
// 检测关闭层
cancel: function (index, layero) {
if (select_pay_type) {
// // console.log(select_pay_type);return;
window.location.reload();
}
}
});
}
function send_qrcode() {
var qrcode = $('#payment_img').attr('src');
var payment_type = $('#payment_type').val()
var payment_name = $('#payment_name').val()
var payment_num = $('#payment_num').val()
var payment_bank = $('#payment_bank').val()
var payment_open = $('#payment_open').val()
// // console.log(qrcode);
// if (!payment_type) {
// layer.msg('支付账号不能为空');
// return;
// }
if (qrcode != undefined) {
// if (qrcode != undefined && qrcode) {
// 1console.log('发送的二维码url:' + qrcode);
sendMessage('img[' + qrcode + ']');
} else {
var content = "支付方式:" + payment_type + '\n' + "银行卡姓名:" + payment_name + "\n" + "银行卡号:" + payment_num + "\n" + "开户银行:" + payment_bank + "\n" + "开户支行:" + payment_open
// 1console.log('发送的内容:' + content)
sendMessage(content)
}
}
var isShow = false;
layui.use(['element', 'form'], function () {
var element = layui.element;
var form = layui.form;
});
// 图片 文件上传
layui.use(['upload', 'layer'], function () {
var upload = layui.upload;
var layer = layui.layer;
// 执行实例
var uploadInstImg = upload.render({
elem: '#image' // 绑定元素
, accept: 'images'
, exts: 'jpg|jpeg|png|gif'
, url: '/service/upload/uploadImg' // 上传接口
, done: function (res) {
sendMessage('img[' + res.data.src + ']');
// showBigPic();
}
, error: function () {
// 请求异常回调
}
});
var uploadInstFile = upload.render({
elem: '#file' // 绑定元素
, accept: 'file'
, exts: 'zip|rar'
, url: '/service/upload/uploadFile' // 上传接口
, done: function (res) {
sendMessage('file(' + res.data.src + ')[' + res.msg + ']');
}
, error: function () {
// 请求异常回调
}
});
});
// 展示表情数据
function showFaces() {
isShow = true;
var alt = getFacesIcon();
var _html = '';
layui.each(alt, function (index, item) {
_html += '
';
});
_html += '
';
return _html;
}
// 选择表情
function checkFace(obj) {
var word = $(".msg-area").val() + ' face' + $(obj).attr('title') + ' ';
// 1console.log('word')
// 1console.log(word)
// 1console.log('word')
$(".msg-area").val(word).focus();
}
// 发送消息
function sendMessage(sendMsg) {
var msg = (typeof (sendMsg) == 'undefined') ? $(".msg-area").val() : sendMsg;
var msg_id = uuid();
if ('' == msg) {
layui.use(['layer'], function () {
var layer = layui.layer;
return layer.msg('请输入回复内容', { time: 1000 });
});
return false;
}
if (repetition_line == true || !check_line) {
return layer.msg('当前链接已断线');
}
// 1console.log('msg')
// 1console.log(msg)
// 1console.log('msg')
var word = msgFactory(msg, 'mine', uinfo, null, msg_id);
var uid = $("#active-user").attr('data-id');
var uname = $("#active-user").attr('data-name');
var time = getTime();
// 1console.log('我是消息');
if (!uid) {
layui.use(['layer'], function () {
var layer = layui.layer;
return layer.msg('请先选择要发送的用户', { time: 1000 });
});
return false;
}
ws.send(JSON.stringify({
path: 'api\/chat',
param: {
type: 'kf', to_id: uid, to_name: uname, content: msg, from_name: uinfo.username, msg_id: msg_id,
from_id: uinfo.id, from_avatar: uinfo.avatar
},
access_token: token
}));
//本地缓存
var key = uinfo.id + '-' + uid;
if (typeof (Storage) !== "undefined") {
var localMsg = msgQueueCheck(getCache(key));
if (localMsg == null || localMsg.length == 0) {
localMsg = [];
}
// localMsg = { type: 'mine', from_id: uinfo.id, from_name: uinfo.username, time_line: time, msg_id: msg_id, to_name: uname, to_id: uid, img_id: '', payment: '', content: msg, from_avatar: uinfo.avatar, msg: msg };
localMsg.push({ type: 'mine', from_id: uinfo.id, from_name: uinfo.username, time_line: time, msg_id: msg_id, to_name: uname, to_id: uid, img_id: '', payment: '', content: msg, from_avatar: uinfo.avatar, msg: msg });
cacheChat({ key: key, data: localMsg });
}
// 1console.log("开始添加")
$("#u-" + uid).append(word);
$(".msg-area").val('');
// 滚动条自动定位到最底端
wordBottom();
// 检测是否发送成功
checkUserReceiveMsg(`${msg_id}`);
}
// 缓存聊天记录到本地
function cacheChat(obj) {
if (typeof (Storage) !== "undefined") {
// setTimeout(function () {
// f1的任务代码
localStorage.setItem(obj.key, JSON.stringify(obj.data));
// }, 100);
}
}
// 从本地缓存中,拿出数据
function getCache(key) {
return JSON.parse(localStorage.getItem(key));
}
// 缓存未读消息数 key: 'unread-' + kf_id + '-' + uid, number : 数量
function cacheUnread(key, number) {
if (typeof (Storage) !== "undefined") {
if (number) {
localStorage.setItem(key, parseInt(number));
} else {
localStorage.removeItem(key); // 传过来的数量为空则删除该缓存
}
}
}
// 从本地获取未读消息数
function getUnread(key) {
var result = localStorage.getItem(key) ? parseInt(localStorage.getItem(key)) : 0;
return result;
}
//获取时间
function getTime() {
var myDate = new Date();
var year = myDate.getFullYear();
var month = myDate.getMonth() + 1;
var date = myDate.getDate();
var hour = myDate.getHours();
var minute = myDate.getMinutes();
var s = myDate.getSeconds();
if (date < 10) date = '0' + date;
if (month < 10) month = '0' + month;
if (hour < 10) hour = '0' + hour;
if (minute < 10) minute = '0' + minute;
if (s < 10) s = '0' + s;
return year + '-' + month + "-" + date + " " + hour + ':' + minute + ':' + s;
}
// 展示用户发送来的消息
function showUserMessage(userInfo, content) {
// 1console.log("成功收到对方消息,开始发送确认收到的回执消息");
var msg_id = uuid();
ws.send(JSON.stringify({
path: 'api\/sendReceiptMsg',
param: { type: 'kf', msg_id: userInfo.msg_id },
access_token: token
}));
//消息提示音
sendWarnAudio('msg');
//添加用户到用户列表
if ($('#f-' + userInfo.id).length == 0) {
addUser(userInfo, userInfo.qrcode);
//存储订单数据
// sessionStorage.setItem("f-"+userInfo.id, JSON.stringify(userInfo.data));
order_view(userInfo.id);
}
// 如果 在线用户tab为折叠状态,则tab上显示新消息提醒
showTabNotice('on');
// 未读条数计数
if (!$('#f-' + userInfo.id).hasClass('active')) {
var num = $('#f-' + userInfo.id).find('span:eq(1)').text();
if (num == 'new' || !num) {
num = 1;
} else {
num = parseInt(num) + 1;
}
cacheUnread(makeUnreadKey(uid, userInfo.id), num);
$('#f-' + userInfo.id).find('span:eq(1)').removeClass('layui-badge').addClass('layui-badge').text(num);
}
var word = msgFactory(content, 'user', userInfo, null, userInfo.msg_id);
// setTimeout(function () {
$("#u-" + userInfo.id).append(word);
// 滚动条自动定位到最底端
wordBottom();
// $(document).on("click", ".layui-mylink-photos", function () {
// var value = $(this).attr('payment');
// if (value == 123) {
// // showBigPic();
// } else {
// clickpayment()
// }
// })
// showBigPic();
// }, 200);
// var time = getTime();
var time = userInfo.time;
//本地存储
var key = 'KF' + uid + '-' + userInfo.id
if (typeof (Storage) !== "undefined" && typeof (flag) == "undefined") {
var localMsg = msgQueueCheck(getCache(key));
if (localMsg == null || localMsg.length == 0) {
localMsg = [];
}
localMsg.push({ type: 'user', from_id: userInfo.id, from_name: userInfo.name, time_line: time, to_name: uname, to_id: uid, img_id: '', payment: '', content: content, from_avatar: userInfo.avatar, msg: '' });
// console.log(localMsg);
cacheChat({ key: key, data: localMsg });
}
}
// 消息发送工厂
function msgFactory(content, type, uinfo, payment, msg_id = '') {
if (payment != "" && payment != null) {
var payment = payment
width = '120px'
height = '50px'
} else {
width = '110px'
height = '100px'
}
var id_payment = id_payment
var _html = '';
if ('mine' == type) {
_html += '';
} else {
_html += '';
}
_html += '';
_html += '

';
if ('mine' == type) {
_html += '
' + getDate() + '' + uinfo.username + '';
} else {
_html += '
' + uinfo.name + '' + getDate() + '';
}
_html += '
' + replaceContent(content, id_payment, payment, width, height) + '
';
_html += '';
return _html;
}
// 获取日期
function getDate() {
var d = new Date(new Date());
return d.getFullYear() + '-' + digit(d.getMonth() + 1) + '-' + digit(d.getDate())
+ ' ' + digit(d.getHours()) + ':' + digit(d.getMinutes()) + ':' + digit(d.getSeconds());
}
//补齐数位
var digit = function (num) {
return num < 10 ? '0' + (num | 0) : num;
};
// 滚动条自动定位到最底端
function wordBottom() {
var box = $(".chat-box");
box.scrollTop(box[0].scrollHeight);
}
// 切换在线用户
function changeUserTab(obj) {
$("#user_list li").removeClass('active');
$("#offline_user_list li").removeClass('active');
obj.addClass('active').siblings().removeClass('active');
wordBottom();
}
// 添加在线用户到面板
function addUser(data) {
//缓存用户数据
cacheUserData(data);
if (!$('#user_list').find(`#f-${data.id}`).html()) {
var _html = '';
_html += '
';
_html += '' + data.name + '';
_html += 'new';
_html += 'ဇ';
_html += '';
// 添加左侧列表
$("#user_list").append(_html);
}
// 如果没有选中人,选中第一个
// var hasActive = 0;
// $("#all_user_list li").each(function(){
// if($(this).hasClass('active')){
// hasActive = 1;
// }
// });
if (!document.getElementById(`u-${data.id}`)) {
var _html2 = '';
_html2 += '';
// 添加主聊天面板
$('.chat-box').append(_html2);
}
// if(0 == hasActive){
// $("#all_user_list").find('li').eq(0).addClass('active').find('span:eq(1)').removeClass('layui-badge').text('');
// $("#u-" + data.id).addClass('show-chat-detail');
// var id = $(".layui-unselect").find('li').eq(0).data('id');
// var name = $(".layui-unselect").find('li').eq(0).data('name');
// var ip = $(".layui-unselect").find('li').eq(0).data('ip');
// var avatar = $(".layui-unselect").find('li').eq(0).data('avatar');
// // 设置当前会话用户
// $("#active-user").attr('data-id', id).attr('data-name', name).attr('data-avatar', avatar).attr('data-ip', ip);
// $("#f-user").val(name);
// $("#f-user-id").val(id);
// $("#coin_uid").val(id);
// $("#f-ip").val(ip);
// $.getJSON('/service/index/getCity', {ip: ip}, function(res){
// $("#f-area").val(res.data);
// });
// //第一个用户默认展示
// order_view(data.id);
// }
if ($("#user_list").prop('hidden') == false) {
// getChatLog(data.id, 1);
checkUser();
} else {
checkUser();
}
}
/**
* 拼接本地缓存未读消息key
* @param kfId 客服id
* @param userId 用户id
*/
function makeUnreadKey(kfId, userId) {
return 'unread-' + kfId + '-' + userId;
}
/**
* 显示在线、离线未读提示
* @param type 在线、离线类型
*/
function showTabNotice(type) {
if ($('#' + type + '_span').hasClass('fold')) {
$('#' + type + 'line_user .layui-badge').show();
}
}
/**
* 添加离线用户到面板
* @param data
* @param type 添加类型:1 初始加载; 2 在线转离线
*/
function addOffLineUser(data, type) {
// if (type == 2) {
// var calss_c = "layui-nav-item active";
// } else {
// var calss_c = "layui-nav-item";
// }
//缓存用户数据
// 1console.log(111);
cacheUserData(data);
// 1console.log(data);
let unread = type == 1 ? $("#user_list #f-" + data.id).find('span:eq(1)').text() : 0;
let _html = '';
_html += '
';
_html += '' + data.name + '';
// 初始加载离线用户列表
if (type == 1) {
let old_unread = getUnread(makeUnreadKey(uid, data.id));
// 1console.log(old_unread);
unread = old_unread + parseInt(data.unread);
if (unread) {
cacheUnread(makeUnreadKey(uid, data.id), unread); // 存未读消息
// 如果 离线tab折叠,则显示 离线未读提示
showTabNotice('off');
}
}
if (!unread) {
_html += '';
} else {
_html += '' + unread + '';
}
_html += 'x';
// _html += 'ဇ';
_html += '';
// 1console.log(111);
// 添加左侧列表
$("#offline_user_list").append(_html);
// 如果没有选中人,选中第一个
// var hasActive = 0;
// $("#all_user_list li").each(function(){
// if($(this).hasClass('active')){
// hasActive = 1;
// }
// });
if (!document.getElementById(`u-${data.id}`)) {
let _html2 = '';
_html2 += '';
//添加主聊天面板
$('.chat-box').append(_html2);
}
// if(0 == hasActive){
// $("#all_user_list").find('li').eq(0).addClass('active').find('span:eq(1)').removeClass('layui-badge').text('');
// $("#u-" + data.id).addClass('show-chat-detail');
// var id = $(".layui-unselect").find('li').eq(0).data('id');
// var name = $(".layui-unselect").find('li').eq(0).data('name');
// var ip = $(".layui-unselect").find('li').eq(0).data('ip');
// var avatar = $(".layui-unselect").find('li').eq(0).data('avatar');
// // 设置当前会话用户
// $("#active-user").attr('data-id', id).attr('data-name', name).attr('data-avatar', avatar).attr('data-ip', ip);
// $("#f-user").val(name);
// $("#f-user-id").val(id);
// $("#f-ip").val(ip);
// $.getJSON('/service/index/getCity', {ip: ip}, function(res){
// $("#f-area").val(res.data);
// });
// //第一个用户默认展示
// // order_view(data.id);
// }
if ($("#offline_user_list").prop('hidden') == false) {
// getChatLog(data.id, 1);
checkUser();
} else {
checkUser();
}
}
//删除离线用户
function offline_user_del(userId, e) {
// 阻止点击事件冒泡
window.event ? window.event.cancelBubble = true : e.stopPropagation();
$.getJSON('/service/index/delOfflineUser?user_id=' + userId, function (res) {
if (1 == res.code) {
layer.msg('删除成功');
var key = 'KF' + uid + '-' + userId;
localStorage.removeItem(key);//清除客服对离线用户的本地缓存
sessionStorage.removeItem('timerid_' + uid + '_' + userId)
$("#offline_user_list #f-" + userId).remove(); // 清除左侧的用户列表
$('#u-' + userId).remove(); // 清除右侧的聊天详情
// 清除右侧的访客信息
$('#f-user').val('');
$("#coin_uid").val('');
$('#f-ip').val('');
$('#f-area').val('');
} else {
layer.msg(res.msg);
return;
}
});
}
function user_over(data) {
data.css('background-color', 'red');
}
function user_out(data) {
data.css('background-color', '#aaa');
}
// 操作新连接用户的 dom操作
function checkUser() {
$("#all_user_list").find('li').unbind("click"); // 防止事件叠加
// 切换用户
$(".layui-unselect").find('li').bind('click', function () {
if ($(this).attr('class') == 'layui-nav-item active') {
return;
}
changeUserTab($(this));
// 1console.log($(this).data('name'));
var userId = $(this).data('id');
var avatar = $(this).data('avatar');
var name = $(this).data('name');
var ip = $(this).data('ip');
// 展示相应的对话信息
$('.chat-box ul').each(function () {
if ('u-' + userId == $(this).attr('id')) {
$(this).addClass('show-chat-detail').siblings().removeClass('show-chat-detail');
}
});
// 去除消息提示
$(this).find('span:eq(1)').removeClass('layui-badge').text('');
// 清除本地未读消息缓存 makeUnreadKey(parseInt(uid), userId)
cacheUnread(makeUnreadKey(uid, userId), 0);
// 设置当前会话的用户
$("#active-user").attr('data-id', userId).attr('data-name', name).attr('data-avatar', avatar).attr('data-ip', ip);
// 储存用户信息
user_info_tmp = {
u_id: userId,
u_name: name,
u_avatar: avatar,
u_ip: ip,
}
// 右侧展示详情
$("#f-user").val(name);
$("#f-user-id").val(userId);
$("#coin_uid").val(userId);
$("#f-ip").val(ip);
$.getJSON('/service/index/getCity', { ip: ip }, function (res) {
$("#f-area").val(res.data);
});
//重新渲染商品订单模板
order_view(userId);
// 1console.log("点击更换了");
getChatLog(userId, 1);
wordBottom();
});
}
// 删除离线用户聊天面板(离线转换成在线)
function delOffUser(data) {
// 获取 该用户是否为当前聊天用户
let active = $("#offline_user_list #f-" + data.id).hasClass('active');
$("#offline_user_list #f-" + data.id).remove(); // 清除左侧的用户列表
// $('#u-' + data.id).remove(); // 清除右侧的聊天详情
if ($("#offline_user_list li").length == 0) {
$("#off_span").attr('class', 'fold');
}
// 清除右侧的访客信息
$('#f-user').val('');
$('#f-user-id').val('');
$("#coin_uid").val('');
$('#f-ip').val('');
$('#f-area').val('');
// 如果该用户为当前聊天用户
if (active) {
$("#on_span").attr('class', 'unfold'); // 展开在线用户tab
$("#user_list").prop('hidden', false); // 显示在线用户列表
$("#off_span").attr('class', 'fold'); // 折叠离线用户tab
$("#offline_user_list").prop('hidden', true); // 隐藏离线用户列表
$('#user_list #f-' + data.id).click();
}
}
// 删除在线用户聊天面板
function delUser(data) {
addOffLineUser(data.userinfo, 2);
// 查看在线tab是否折叠,如果折叠则查看是否有未读的在线消息,有则不消除tab上的消息提醒
if ($('#on_span').hasClass('fold')) {
$('#user_list li').each(function () {
if ($(this).find('span:eq(1)').text()) {
// 1console.log($(this).find('span:eq(1)').text());
// 隐藏消息提示
$('#online_user .layui-badge').hide();
return false;
}
});
}
$("#user_list #f-" + data.id).remove(); // 清除左侧的用户列表
// $('#u-' + data.id).remove(); // 清除右侧的聊天详情
// // 清除右侧的访客信息
$('#f-user').val('');
$('#f-user-id').val('');
$("#coin_uid").val('');
$('#f-ip').val('');
$('#f-area').val('');
layer.msg('用户:' + data.userinfo.name + '已离线!');
//重新渲染商品订单模板
// order_view(data.uid,'del');
}
// 发送快捷语句
function sendWord(obj) {
var msg = $(obj).data('word');
sendMessage(msg);
}
// 获取聊天记录
function getChatLog(uid, page, flag, width, height) {
var chatLog = getCache(uinfo.id + "-" + uid);
if (chatLog == 'undefined' || chatLog == null || chatLog.length < 1) {
chatLog = [];
}
// 1console.log("------------获取本地数据-----------------")
// 1console.log(chatLog)
// 1console.log("------------获取本地数据-----------------")
$.ajax({
url: '/service/index/getOfflineMsg?uid=' + uid + '&page=' + page,
type: "get",
async: false,
dataType: "json",
success: function (res) {
// console.log("------------获取离线数据 start-----------------")
// console.log(res.data)
// console.log("------------获取离线数据 end-----------------")
if (res.data.length == 0) {
return;
}
for (var i = 0; i <= res.data.length - 1; i++) {
if (res.data[i].type != 'user') {
continue;
}
chatLog.push(res.data[i]);
// // 1console.log(res.data);return;
var tkey = uinfo.id + '-' + uid;
if (typeof (Storage) !== "undefined") {
var localMsg = msgQueueCheck(getCache(tkey));
if (localMsg == null || localMsg.length == 0) {
localMsg = [];
}
localMsg.push(res.data[i]);
cacheChat({ key: tkey, data: localMsg });
}
}
// 1console.log("------------获取离线数据-----------------")
}
})
// 1console.log("------------获取所有数据-----------------")
// 1console.log(chatLog)
// 1console.log("------------获取所有数据-----------------")
// if (chatLog == null || chatLog.length == 0) {
// return;
// }
var _html = ''
var len = chatLog.length;
for (var i = 0; i < len; i++) {
var v = chatLog[i];
if (v.payment != null && v.payment != '') {
var content = v.msg
width = '120px'
height = '50px'
} else {
var content = v.content
width = '110px'
height = '100px'
}
if ('mine' == v.type) {
_html += '';
} else {
_html += '';
}
_html += '';
_html += '

';
if ('mine' == v.type) {
_html += '
' + v.time_line + '' + v.from_name + '';
} else {
_html += '
' + v.from_name + '' + v.time_line + '';
}
_html += '
' + replaceContent(content, v.img_id, v.payment, width, height) + '
';
_html += '';
}
setTimeout(function () {
// 滚动条自动定位到最底端
if (typeof flag == 'undefined') {
$("#u-" + uid).html(_html);
wordBottom();
} else {
$("#u-" + uid).prepend(_html);
}
// console.log(chatLog, flag);
// $(document).on("click", ".layui-mylink-photos", function () {
// var value = $(this).attr('payment');
// if (value == 123) {
// // showBigPic();
// } else {
// clickpayment()
// }
// })
}, 100);
}
// function removeLocalStorage111(uid, page, flag) {
// $.getJSON('/service/index/getChatLog', { uid: uid, page: page }, function (res) {
// if (1 == res.code && res.data.length > 0) {
// if (res.msg == res.total) {
// var _html = '没有更多了
';
// } else {
// var _html = '';
// }
// var len = res.data.length;
// for (var i = 0; i < len; i++) {
// var v = res.data[len - i - 1];
// if ('mine' == v.type) {
// _html += '';
// } else {
// _html += '';
// }
// _html += '';
// _html += '

';
// if ('mine' == v.type) {
// _html += '
' + v.time_line + '' + v.from_name + '';
// } else {
// _html += '
' + v.from_name + '' + v.time_line + '';
// }
// _html += '
' + replaceContent(v.content) + '
';
// _html += '';
// }
// setTimeout(function () {
// // 滚动条自动定位到最底端
// if (typeof flag == 'undefined') {
// $("#u-" + uid).html(_html);
// wordBottom();
// } else {
// $("#u-" + uid).prepend(_html);
// }
// // showBigPic();
// }, 100);
// }
// });
// }
$(".layui-mylink-photos").on('click', function (obj) {
var value = $(this).attr('payment');
var src = this.src;
if (value == 123) {
layer.photos({
photos: {
data: [{
"alt": "大图模式",
"src": src
}]
}
, shade: 0.5
, closeBtn: 2
, anim: 0
, resize: false
, success: function (layero, index) {
}
});
}
});
// 显示大图
function showBigPic(obj) {
// console.log(obj);
var src = obj.src;
layer.photos({
photos: {
data: [{
"alt": "大图模式",
"src": src
}]
}
, shade: 0.5
, closeBtn: 2
, anim: 0
, resize: false
, success: function (layero, index) {
}
});
}
// 获取更多的的记录
function getMore(obj) {
$(obj).remove();
var page = $(obj).attr('data-page');
var uid = $(".layui-unselect").find('li').eq(0).data('id');
getChatLog(uid, page, 1);
}
// 删除历史聊天记录
function removeLocalStorage(key) {
localStorage.removeItem(key);
}
function sendWarnAudio(type) {
var turnAudio = document.getElementById("myWarnAudio");
if (!turnAudio) {
// 1console.log('初始化');
turnAudio = document.createElement("audio");
document.body.appendChild(turnAudio);
turnAudio.id = "myWarnAudio";
turnAudio.controls = false;
turnAudio.loop = false;
turnAudio.hidden = true;
}
if (type == 'msg') {
turnAudio.src = "/static/common/mp3/msn.mp3";
}
turnAudio.play();
}
/**
* 生成uuid
* @param {*} prefix 前缀
*/
function uuid(prefix = '') {
// 生成随机值
function S4() {
return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}
var id = prefix + (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
return id;
}
/**
* 检测消息是否发送成功
* @param {*} msg_id 消息id
* @param {*} type 消息类型, 1: 常规消息, 2: 自动回复,支付消息
*/
function checkUserReceiveMsg(msg_id, type = 1) {
// 定时1秒是否有返回成功接收消息
sessionStorage.setItem('send_time_receive_msg_' + uinfo.id + '_' + user_info_tmp.u_id + '_' + msg_id, false);
var send_time = setTimeout(function () {
var user_receive_msg = sessionStorage.getItem('send_time_receive_msg_' + uinfo.id + '_' + user_info_tmp.u_id + '_' + msg_id);
if (user_receive_msg == true) {
sessionStorage.removeItem('send_time_receive_msg_' + uinfo.id + '_' + user_info_tmp.u_id + '_' + msg_id);
return true;
}
// 第一次进行自动重发
var re_send_msg_num = reSendMsgNum(msg_id, 'get');
if (!re_send_msg_num || re_send_msg_num < 1) {
autoReSendMsg(msg_id, type);
return;
}
// 用户没有接收到, 进行提示
sessionStorage.removeItem('send_time_' + uinfo.id + '_' + user_info_tmp.u_id + '_' + msg_id);
$('#' + msg_id).find('.mylink-chat-text').append(`发送失败
`);
// systemHint(user_info_tmp.u_id, '消息发送失败, 请重新发送!');
// 1console.log('自动发送消息失败, 显示重新发送');
}, 4000);
// 消息入队
sessionStorage.setItem('send_time_' + uinfo.id + '_' + user_info_tmp.u_id + '_' + msg_id, send_time);
}
/**
* 重新发送消息
* @param {*} msg_id 消息id
* @param {*} type 消息类型, 1: 常规消息, 2: 自动回复,支付消息
*/
function reSendMsg(msg_id, _this = null, type) {
layer.confirm('确定重新发送吗?', {
title: false,
btn: ['确定', '取消'] //按钮
}, function (ind) {
layer.close(ind);
// 获取本地数据
var key = uinfo.id + '-' + user_info_tmp.u_id;
var msg_list = msgQueueCheck(getCache(key));
if (msg_list == null || msg_list.length == 0) return false;
// 找出发送的数据
var msg_data = null;
msg_list.forEach(vo => {
if (vo.msg_id == msg_id) {
msg_data = vo;
}
});
if (!msg_data) return false;
// socket再次推送并检测是否发送成功
switch (type) {
case 1:
ws.send(JSON.stringify({
path: 'api\/chat',
param: {
type: 'kf', to_id: user_info_tmp.u_id, to_name: user_info_tmp.u_name, content: msg_data.msg, from_name: uinfo.username, msg_id: msg_data.msg_id,
from_id: uinfo.id, from_avatar: uinfo.avatar
},
access_token: token
}));
break;
case 2:
ws.send(JSON.stringify({
path: 'api\/chat',
param: {
type: 'kf', payment: msg_data.payment, data: msg_data.data, to_id: msg_data.to_id, to_name: msg_data.to_name, content: msg_data.content, from_name: msg_data.from_name,
from_id: msg_data.from_id, from_avatar: msg_data.from_avatar, msg_id: msg_data.msg_id,
},
access_token: token
}));
break;
}
if (_this != null) $(_this).parent().remove();
checkUserReceiveMsg(`${msg_id}`, type);
}, function (inds) {
layer.close(inds);
});
}
/**
* 自动重新发送消息
* @param {*} msg_id 消息id
* @param {*} type 消息类型, 1: 常规, 2: 支付
*/
function autoReSendMsg(msg_id, type) {
// 获取本地数据
var key = uinfo.id + '-' + user_info_tmp.u_id;
var msg_list = msgQueueCheck(getCache(key));
if (msg_list == null || msg_list.length == 0) return false;
// 找出发送的数据
var msg_data = null;
msg_list.forEach(vo => {
if (vo.msg_id == msg_id) {
msg_data = vo;
}
});
if (!msg_data) return false;
// socket再次推送并检测是否发送成功
switch (type) {
case 1:
ws.send(JSON.stringify({
path: 'api\/chat',
param: {
type: 'kf', to_id: user_info_tmp.u_id, to_name: user_info_tmp.u_name, content: msg_data.msg, from_name: uinfo.username, msg_id: msg_data.msg_id,
from_id: uinfo.id, from_avatar: uinfo.avatar
},
access_token: token
}));
break;
case 2:
ws.send(JSON.stringify({
path: 'api\/chat',
param: {
type: 'kf', payment: msg_data.payment, data: msg_data.data, to_id: msg_data.to_id, to_name: msg_data.to_name, content: msg_data.content, from_name: msg_data.from_name,
from_id: msg_data.from_id, from_avatar: msg_data.from_avatar, msg_id: msg_data.msg_id,
},
access_token: token
}));
break;
}
// 更新发送次数
reSendMsgNum(msg_id, 'update');
checkUserReceiveMsg(`${msg_id}`, type);
// 1console.log('发送消息失败, 正在自动重新发送');
}
/**
* 重新发送消息次数操作
* @param {*} msg_id 消息id
* @param {*} type 操作类型, get: 获取操作次数, update(更新或新建), del: 删除
*/
function reSendMsgNum(msg_id, type = 'get') {
if (!msg_id) return false;
switch (type) {
case 'get':
return sessionStorage.getItem('re_send_msg_num_' + uinfo.id + '_' + user_info_tmp.u_id + '_' + msg_id);
break;
case 'update':
var re_send_msg_num = sessionStorage.getItem('re_send_msg_num_' + uinfo.id + '_' + user_info_tmp.u_id + '_' + msg_id);
if (!re_send_msg_num) {
var save = sessionStorage.setItem('re_send_msg_num_' + uinfo.id + '_' + user_info_tmp.u_id + '_' + msg_id, 1);
} else {
var save = sessionStorage.setItem('re_send_msg_num_' + uinfo.id + '_' + user_info_tmp.u_id + '_' + msg_id, re_send_msg_num + 1);
}
return save;
break;
case 'del':
return sessionStorage.removeItem('re_send_msg_num_' + uinfo.id + '_' + user_info_tmp.u_id + '_' + msg_id);
break;
default:
return false;
break;
}
}
/**
* 检测消息是否重复
* @param {*} uid 用户id
* @param {*} msg_id 消息id
*/
function checkMsgIsRepeat(uid, msg_id) {
if (!uid || !msg_id) return false;
var dom = $('u-' + uid).find('#' + msg_id);
if (!dom || dom.length == 0) return false;
return true;
}