client.page.js
24.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
/**
* 在线客服客户页
*
* @author: liqi <qi.li@yoho.cn>
* @date: 2016/10/21
*/
'use strict';
var $ = require('yoho-jquery'),
view = require('./view'),
broswer = require('./broswer'),
util = require('./utility'),
send = require('./socket/send'),
edit = require('./socket/edit'),
ClipPaste = require('./clip-paste'),
serviceApi = require('./service-api'),
receive = require('./socket/receive'),
socketChat = require('./socket/chat'),
socketConf = require('./socket/config'),
processInfo = require('./view').processInfo;
var allRTs,
endTime,
originConf,
encryptedUid,
socketConfCM,
assetsPrefix,
$html = $('html'),
$window = $(window),
$document = $(document),
$msgList = $('.msg-list'),
$msgEdit = $('.msg-edit'),
$leaveMsg = $('#leaveMsg'),
$close = $('.header .close'),
$sendOrder = $('.send-order'),
$sendImgInput = $('#sendImg'),
$history = $('.about-his.has-his'),
$msgArea = $('.msg-edit .msg-area'),
$rightHeadTab = $('.right-head .tab'),
$encryptedUid = $('input[name=encryptedUid]'),
$assetsPrefix = $('input[name=assetsPrefix]'),
$panelMainBody = $('.panel-main .main-body');
var tipTpl = require('hbs/service/tip.hbs'),
csTpl = require('hbs/service/cs-msg.hbs'),
cusTpl = require('hbs/service/cus-msg.hbs'),
robotTpl = require('hbs/service/robot-msg.hbs');
require('bootstrap');
require('../common');
require('blueimp-file-upload/js/jquery.iframe-transport');
require('blueimp-file-upload/js/jquery.fileupload');
require('blueimp-file-upload/js/jquery.fileupload-process');
require('blueimp-file-upload/js/jquery.fileupload-validate');
allRTs = socketConf.recType;
encryptedUid = $encryptedUid.val();
assetsPrefix = $assetsPrefix.val();
socketConfCM = socketConf.conversationMessage;
socketConfCM.encryptedUid = encryptedUid;
processInfo.encryptedUid = encryptedUid;
// 原始配置信息用于重新连线
originConf = JSON.parse(JSON.stringify(socketConf));
// 页面初始化
function _loadPage() {
// 客服评价
var evalView = new view.Evaluate();
/**
* 添加新的消息
*/
function msgAppend(dom) {
$msgList.append(dom);
$panelMainBody.scrollTop($panelMainBody[0].scrollHeight);
}
/**
* 系统通知
* @param tip 具体消息
*/
function systemTip(tip) {
var dom;
dom = tipTpl({
content: tip
});
// 添加消息
msgAppend(dom);
}
/**
* 断线重连提醒
*/
function offlineTip(message) {
var tip;
if (!message) {
tip = '您已断线,请重新<a class="red-tip reconnect">连线客服</a>';
return systemTip(tip);
}
message.content = message.content +
'<a class="red-tip reconnect">连线客服</a>';
// 系统通知
systemTip(message.content);
}
/**
* 发送消息前的共通处理
*/
function beforeSendMsg() {
var $countdown = $('.countdown');
$countdown.parents('.list-item').remove();
util.removeBlinkAlert();
}
/**
* 处理发送消息
*/
function sendMessage() {
var $area = $('.msg-area'),
msg = $area.val().trim();
beforeSendMsg();
if (!msg) {
return;
}
send.text(msg);
$area.val('');
}
/**
* 常见问题
*/
function toggleAnswer(e) {
var cTag = $(e.currentTarget),
parent = cTag.parent(),
next = cTag.next();
next.length && next.toggle();
next.length && parent.toggleClass('has-a');
}
/**
* 正在进行人工会话
*/
function csChatting(message) {
// 系统通知
systemTip(message.newContent);
}
/**
* 留言
*/
function leaveMsg() {
var $lm = $('#leaveMsg'),
$ta = $lm.find('textarea');
$lm.find('.leave-msg-tip').addClass('hide');
$ta.val('');
$lm.modal({
show: true
});
}
/**
* 成功进入在线客服
* @param message 消息对象
*/
function enterSuccess(message) {
// 删除重新连线
$msgList.find('.reconnect').parents('.push-tip').remove();
// 系统通知
systemTip(message.content);
processInfo.savedEval = false;
processInfo.manual = false;
// 显示人工客服
edit.setIcons({
'manual-service': true
});
}
/**
* 人工链接
* @param rec 接收对象
* @private
*/
function linkSuccess(rec) {
var OUT_SERVICE = 0, // 0 没上班
LINE_UP = 1, // 1 需要排队
MANUAL_SERVICE = 2, // 2 接入人工
ADMIN_MANUAL_SERVICE = 3; // 3 管理员分配
var message = rec.chatMessage;
var msgType = message.type;
var dom,
tipText;
switch (msgType) {
case OUT_SERVICE:
tipText = receive.leaMsgTip(rec);
dom = tipTpl({
content: tipText
});
break;
case LINE_UP:
tipText = receive.leaMsgTip(rec);
dom = tipTpl({
content: tipText
});
// 隐藏人工
edit.setIcons({
'manual-service': false
});
break;
case MANUAL_SERVICE:
tipText = message.content;
dom = tipTpl({
content: tipText
});
// 接入人工客服需要评价
processInfo.manual = true;
processInfo.savedEval = false;
// 显示评价&隐藏人工
edit.setIcons({
emoji: true,
image: true,
evaluate: true,
'manual-service': false
});
break;
case ADMIN_MANUAL_SERVICE:
tipText = message.content;
dom = tipTpl({
content: tipText
});
processInfo.manual = true;
// 显示评价&隐藏人工
edit.setIcons({
emoji: true,
image: true,
evaluate: true,
'manual-service': false
});
break;
default:
break;
}
// 添加消息
msgAppend(dom);
}
/**
* 人工接入队列中
* @param message 内部消息对象
*/
function inQueue(message) {
systemTip(message.content);
}
/**
* 处理客户消息
* @private
*/
function handleCusMsg(rec, msgType, message) {
var dom,
image;
// 图片添加标签
if (msgType === 2) {
dom = cusTpl({
userHead: rec.userHead,
userName: rec.userName,
sendTimeShort: rec.sendTimeShort,
newContent: message.newContent
});
image = new Image();
image.src = message.content;
image.onload = function() {
msgAppend(dom);
};
} else {
dom = cusTpl({
userHead: rec.userHead,
userName: rec.userName,
sendTimeShort: rec.sendTimeShort,
newContent: message.newContent
});
msgAppend(dom);
}
}
/**
* 链接终端倒计时
* @private
*/
function breakCountdown(message) {
var dom,
tip;
tip = message.content +
'<span class="countdown"></span>';
dom = tipTpl({
content: tip
});
// 消息添加
msgAppend(dom);
}
/**
* 处理客服消息
* @private
*/
function handleCsMsg(rec, msgType, message) {
var dom,
image;
if (msgType === 2) {
dom = csTpl({
csHead: rec.csHead,
csName: rec.csName,
sendTimeShort: rec.sendTimeShort,
newContent: message.newContent
});
image = new Image();
image.src = message.content;
image.onload = function() {
msgAppend(dom);
};
} else {
dom = csTpl({
csHead: rec.csHead,
csName: rec.csName,
sendTimeShort: rec.sendTimeShort,
newContent: message.newContent
});
msgAppend(dom);
}
}
/**
* 处理收到消息
*/
function getMessage(rec) {
var dom,
recType = rec.type,
message = rec.chatMessage,
msgType = message ? message.type : -1,
isHidden = broswer.tabIsHidden(),
allTypes = socketConf.recType;
// 提醒
isHidden && util.addBlinkAlert();
// 预处理
receive.preProcess(rec);
switch (recType) {
case allTypes.ENTER:
enterSuccess(message);
break;
case allTypes.LINK_SUCCESS:
linkSuccess(rec);
break;
case allTypes.IN_QUNEUE:
inQueue(message);
break;
case allTypes.CU_SEND:
handleCusMsg(rec, msgType, message);
break;
case allTypes.BREAK_TIME:
breakCountdown(message);
break;
case allTypes.ROBOT_SEND:
rec.csName = rec.csName || '客服机器人';
dom = robotTpl({
assetsPrefix: assetsPrefix,
csName: rec.csName,
sendTimeShort: rec.sendTimeShort,
newContent: message.newContent
});
break;
case allTypes.CS_SEND:
handleCsMsg(rec, msgType, message);
break;
case allTypes.EVAL_INVITE:
if (!processInfo.savedEval) {
processInfo.promoter = 2;
evalView.open();
}
break;
case allTypes.CS_CHATTING:
csChatting(message);
break;
case allTypes.OP_LEAVE:
socketChat.clear();
edit.setIcons({
emoji: false,
image: false
});
offlineTip(message);
break;
case allTypes.OFFLINE:
socketChat.clear();
edit.setIcons({
emoji: false,
image: false
});
offlineTip(message);
break;
default:
break;
}
// 添加新消息到消息列表
dom && msgAppend(dom);
}
/**
* 连接socket
*/
function connectSocket() {
var $reconnect,
$connectFail = $('.connect-fail'),
// 获取上次会话id
lastSessionId = window.cookie('sessionId');
originConf.conversationMessage.sessionId = lastSessionId || 0;
socketChat.init($.extend(originConf, {
onMessage: function onMessage(e) {
var jsonString = e.data,
received = JSON.parse(jsonString);
socketConfCM.conversationId = received.newConversationId !== 0 ?
received.newConversationId :
received.conversationId;
// 保存会话id
window.setCookie('conversationId', socketConfCM.conversationId, {expires: 60 * 15});
window.setCookie('sessionId', received.sessionId, {expires: 60 * 15});
getMessage(received);
},
onOpen: function() {
edit.setIcons({
evaluate: false,
'manual-service': false
});
},
onClose: function() {
edit.setIcons({
emoji: false,
image: false,
evaluate: false,
'manual-service': false
});
$reconnect = $msgList.find('.list-item')
.last().find('.reconnect');
if (!$reconnect.length) {
socketChat.clear();
offlineTip();
}
},
connectFailCb: function() {
$connectFail.fadeIn();
},
socketClosedCb: function() {
socketChat.clear();
offlineTip();
}
}));
}
/**
* 消息解析
* @param msgList
*/
function msgResolve(msgList) {
var i,
len,
item,
dom = '',
heightBefore,
heightAfter;
msgList = msgList.reverse();
len = msgList.length;
if (!len || msgList[0] && endTime === msgList[0].sendTime) {
processInfo.hasMore = false;
}
endTime = msgList[0] && msgList[0].sendTime;
if (processInfo.hasMore) {
for (i = 0; i < len; i++) {
item = msgList[i];
receive.preProcess(item);
switch (item.type) {
case allRTs.CU_SEND:
dom += cusTpl({
userHead: item.userHead,
userName: item.userName,
sendTimeShort: item.sendTimeLong,
newContent: item.chatMessage.newContent
});
break;
case allRTs.ROBOT_SEND:
item.csName = item.csName || '客服机器人';
dom += robotTpl({
assetsPrefix: assetsPrefix,
csName: item.csName,
sendTimeShort: item.sendTimeLong,
newContent: item.chatMessage.newContent
});
break;
case allRTs.CS_SEND:
dom += csTpl({
csHead: item.csHead,
csName: item.csName,
sendTimeShort: item.sendTimeLong,
newContent: item.chatMessage.newContent
});
break;
default:
break;
}
}
heightBefore = $msgList.height();
$msgList.prepend(dom);
heightAfter = $msgList.height();
$panelMainBody.scrollTop(heightAfter - heightBefore);
processInfo.loadingHistory = false;
}
}
/**
* 获取历史聊天记录
*/
function fetchHistoryMsg() {
var msgList = [];
var data = {
encryptedUid: encryptedUid
};
if (processInfo.loadingHistory) {
return;
}
processInfo.loadingHistory = true;
if (endTime) {
data.endTime = endTime;
}
serviceApi.history(data)
.done(function(res) {
if (res && res.code === 401) {
window.onbeforeunload = null;
return location.href = '//www.yohobuy.com/signin.html?refer=' + // eslint-disable-line
encodeURIComponent(location.href);
}
if (res && res.code === 200) {
if (processInfo.hasMore) {
msgList = res.data.records || [];
msgResolve(msgList);
}
$history.hide();
processInfo.scrollLoad = true;
} else {
processInfo.loadingHistory = false;
}
})
.fail(function() {
processInfo.loadingHistory = false;
});
}
// 用户信息获取并初始化socket连接
(function() {
var param = {
return_type: 'jsonp',
method: 'open.passport.get'
};
$.getJSON('//www.yohobuy.com/common/passport/?callback=?', param, function(jsonData) {
if (jsonData.code !== 200) {
location.href = '//www.yohobuy.com/signin.html?refer=' + encodeURIComponent(location.href);
return;
}
// 点击刷新提示
window.onbeforeunload = function() {
return '';
};
if (jsonData && jsonData.data && jsonData.data.result !== -1) {
socketConfCM.userHead = jsonData.data.headIco || '';
socketConfCM.userName = decodeURIComponent(window.getUser()[0]);
// 原始配置信息用于重新连线
originConf = JSON.parse(JSON.stringify(socketConf));
// 连接
connectSocket();
}
});
}());
// 剪切板粘贴发送图片
new ClipPaste('.msg-area', function(path) {
send.image(path);
});
// tab页title重置
broswer.tabVisible(util.removeBlinkAlert);
// 校验留言输入内容
$leaveMsg.find('textarea').bind('change', function() {
var $lm = $('#leaveMsg'),
val = $(this).val();
if (val === '') {
$lm.find('.leave-msg-tip').removeClass('hide');
} else {
$lm.find('.leave-msg-tip').addClass('hide');
}
});
// 提交留言
$leaveMsg.find('.submit').click(function() {
var lMsg = $('#leaveMsg'),
val = lMsg.find('textarea').val().trim();
if (val === '') {
lMsg.find('.leave-msg-tip').removeClass('hide');
return false;
}
serviceApi.leaveMsg({
content: val,
encryptedUid: encryptedUid,
conversationId: socketConfCM.conversationId
})
.done(function(res) {
if (res && res.code === 401) {
window.onbeforeunload = null;
return location.href = '//www.yohobuy.com/signin.html?refer=' + // eslint-disable-line
encodeURIComponent(location.href);
}
})
.always(function() {
lMsg.modal('hide');
});
});
// 根节点高度设置
$html.css({
height: '100%'
});
// enter提交 ctrl+enter换行
$msgArea.on('keydown', function(e) {
broswer.ctrlEnter(e, sendMessage);
});
// 常见问题
$('.qa-list .q').on('click', toggleAnswer);
// 发送订单信息
$sendOrder.on('click', function() {
var tag = $(this),
no = tag.data('no'),
nm = tag.data('nm'),
time = tag.data('time'),
status = tag.data('status');
var msgContent = ['单号:', no, '金额:', '¥' + nm, '下单时间:', time, '状态:', status];
send.order(msgContent);
});
// 发送图片
$sendImgInput.fileupload({
dataType: 'json',
acceptFileTypes: /(\.|\/)(bmp|gif|jpe?g|png)$/i,
maxFileSize: 5000000, // 5M
url: gDomains.imCs + '/fileManage/uploadFile', // eslint-disable-line
progressall: function(e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$('.progress-bar').css('width', progress + '%');
},
done: function(e, res) {
res = res.result;
if (res && res.code === 200) {
// 共通处理
beforeSendMsg();
// 上传成功后发送图片消息
send.image(util.autoProtocol(res.data.filePath));
}
setTimeout(function() {
$('.progress-bar').fadeOut();
}, 500);
},
error: function() {
$('.progress-bar').css('width', 0);
$('.upload-tip').text('上传失败,请稍后重试').fadeIn();
setTimeout(function() {
$('.upload-tip').fadeOut().text('');
}, 2000);
}
}).on('fileuploadprocessalways', function(e, data) {
var $tip = $('.upload-tip'),
currentFile = data.files[data.index];
if (data.files.error && currentFile.error) {
switch (currentFile.error) {
case 'File type not allowed':
$tip.text('您上传的图片格式不正确').fadeIn();
break;
case 'File is too large':
$tip.text('请上传5M以内的图片').fadeIn();
break;
default:
break;
}
setTimeout(function() {
$tip.fadeOut().text('');
}, 2000);
}
});
// 订单信息、常见问题
$rightHeadTab.on('click', function() {
var $el = $(this),
$siblings = $el.siblings(),
$panRight = $('.panel-right'),
order = $el.hasClass('order'),
active = $el.hasClass('active'),
$qaUse = $panRight.find('.qa-use'),
$orderUse = $panRight.find('.order-use');
if (active) {
return;
}
$el.addClass('active');
$siblings.removeClass('active');
if (order) {
$qaUse.hide();
$orderUse.show();
} else {
$qaUse.show();
$orderUse.hide();
}
});
// 留言
$msgList.on('click', '.leave-msg', leaveMsg);
// 消息编辑框功能区
$msgEdit.find('.util .icon').on('click', function(e) {
var cTa = $(this),
index = cTa.index(),
comp = $('.emoji-component');
var utilMap = {
0: function() {
var isNone,
compHeight,
topPo = cTa.offset().top,
leftPo = cTa.offset().left,
cTaHeight = cTa.height();
isNone = comp.css('display') === 'none';
comp.css({display: 'inline-block'});
compHeight = comp.height();
isNone && comp.css({
top: topPo - cTaHeight - compHeight - 5,
left: leftPo
});
!isNone && comp.hide();
},
2: function() {
evalView.open();
},
3: function() {
send.manual();
}
};
if (index === 1) {
return;
}
utilMap[index](e);
});
// 设置表情
$document.on('click', '.emoji-component .emoji', edit.setEmoji);
// 表情组件隐藏
$document.on('click', function(e) {
var $t = $(e.target),
comp = $('.emoji-component');
if (!$t.hasClass('emoji') && !$t.hasClass('emoji-component')) {
comp.hide();
}
});
// 重新连线
$document.on('click', '.reconnect', function() {
$('.connect-fail').hide();
// 共通处理
beforeSendMsg();
connectSocket();
});
// 发送
$msgEdit.find('.send').on('click', sendMessage);
// 关闭聊天窗口
$close.click(function() {
if (processInfo.manual && !processInfo.savedEval) {
evalView.open(true);
} else {
window.close();
}
});
// 失去焦点更新鼠标位置
$msgArea.on('blur', function() {
$(this).recordCursor();
});
// 消息图片放大显示
$msgList.on('click', '.msg-bubble img', function(e) {
var $et = $(e.target),
$zoom = $('.img-zoom-in'),
$img = $zoom.find('img'),
maxH = $window.height() - 100;
if ($et.attr('src') === '') {
return false;
}
$img.css('max-height', maxH);
$img.attr('src', $et.attr('src'));
$zoom.fadeIn();
});
$document.on('click', '.img-zoom-in', function() {
$(this).fadeOut();
});
// 显示历史记录
$history.click(fetchHistoryMsg);
// 滚动加载更多
$panelMainBody.scroll(function() {
var isLoadingArea = $panelMainBody.scrollTop() < 100;
isLoadingArea &&
processInfo.scrollLoad &&
!processInfo.loadingHistory &&
processInfo.hasMore &&
fetchHistoryMsg();
});
}
// 检查支持性
if (util.isSupport()) {
socketConf.servers.push(gDomains.imSocket); // eslint-disable-line
_loadPage();
} else {
$('.un-support').show();
}