Events.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895
  1. <?php
  2. /**
  3. * This file is part of workerman.
  4. *
  5. * Licensed under The MIT License
  6. * For full copyright and license information, please see the MIT-LICENSE.txt
  7. * Redistributions of files must retain the above copyright notice.
  8. *
  9. * @author walkor<walkor@workerman.net>
  10. * @copyright walkor<walkor@workerman.net>
  11. * @link http://www.workerman.net/
  12. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  13. */
  14. /**
  15. * 用于检测业务代码死循环或者长时间阻塞等问题
  16. * 如果发现业务卡死,可以将下面declare打开(去掉//注释),并执行php start.php reload
  17. * 然后观察一段时间workerman.log看是否有process_timeout异常
  18. */
  19. //declare(ticks=1);
  20. use \GatewayWorker\Lib\Gateway;
  21. use Workerman\Lib\Timer;
  22. /**
  23. * 主逻辑
  24. * 主要是处理 onConnect onMessage onClose 三个方法
  25. * onConnect 和 onClose 如果不需要可以不用实现并删除
  26. */
  27. class Events
  28. {
  29. /**
  30. * 新建一个类的静态成员,用来保存数据库实例
  31. */
  32. public static $db = null;
  33. public static $global = null;
  34. /**
  35. * 进程启动后初始化数据库连接
  36. */
  37. public static function onWorkerStart($worker)
  38. {
  39. if (empty(self::$db)) {
  40. self::$db = new \Workerman\MySQL\Connection('192.168.2.186', '3306', 'root', '', 'customer_service');
  41. }
  42. if (empty(self::$global)) {
  43. self::$global = new \GlobalData\Client('127.0.0.1:2207');
  44. // 客服列表
  45. if(is_null(self::$global->kfList)){
  46. self::$global->kfList = [];
  47. }
  48. // 会员列表[动态的,这里面只是目前未被分配的会员信息]
  49. if(is_null(self::$global->userList)){
  50. self::$global->userList = [];
  51. }
  52. // 会员以 uid 为key的信息简表,只有在用户退出的时候,才去执行修改
  53. if(is_null(self::$global->uidSimpleList)){
  54. self::$global->uidSimpleList = [];
  55. }
  56. // 当天的累积接入值
  57. $key = date('Ymd') . 'total_in';
  58. if(is_null(self::$global->$key)){
  59. self::$global->$key = 0;
  60. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  61. unset(self::$global->$oldKey);
  62. unset($oldKey, $key);
  63. }
  64. // 成功接入值
  65. $key = date('Ymd') . 'success_in';
  66. if(is_null(self::$global->$key)){
  67. self::$global->$key = 0;
  68. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  69. unset(self::$global->$oldKey);
  70. unset($oldKey, $key);
  71. }
  72. }
  73. // 定时统计数据
  74. if(0 === $worker->id){
  75. // 1分钟统计一次实时数据
  76. Timer::add(60 * 1, function(){
  77. self::writeLog(1);
  78. });
  79. // 40分钟写一次当前日期点数的log数据
  80. Timer::add(60 * 40, function(){
  81. self::writeLog(2);
  82. });
  83. }
  84. }
  85. /**
  86. * 当客户端连接时触发
  87. * 如果业务不需此回调可以删除onConnect
  88. *
  89. * @param int $client_id 连接id
  90. */
  91. public static function onConnect($client_id)
  92. {
  93. }
  94. /**
  95. * 当客户端发来消息时触发
  96. * @param int $client_id 连接id
  97. * @param mixed $message 具体消息
  98. */
  99. public static function onMessage($client_id, $message)
  100. {
  101. if ($message=='{"type":"ping"}'){
  102. Gateway::sendToCurrentClient('{"type":"pong"}');
  103. return;
  104. }else{
  105. echo "onMessage: ".$message."\r\n";
  106. print_r([self::$global->kfList,self::$global->userList, self::$global->uidSimpleList]);
  107. }
  108. $message = json_decode($message, true);
  109. switch ($message['type']) {
  110. // 客服初始化
  111. case 'init':
  112. $kfList = self::$global->kfList;
  113. // 如果该客服未在内存中记录则记录
  114. if(!isset($kfList[$message['group']]) || !array_key_exists($message['uid'], $kfList[$message['group']])){
  115. do{
  116. $newKfList = $kfList;
  117. $newKfList[$message['group']][$message['uid']] = [
  118. 'id' => $message['uid'],
  119. 'name' => $message['name'],
  120. 'avatar' => $message['avatar'],
  121. 'client_id' => $client_id,
  122. 'task' => 0,
  123. 'user_info' => []
  124. ];
  125. }while(!self::$global->cas('kfList', $kfList, $newKfList));
  126. unset($newKfList, $kfList);
  127. }else if(isset($kfList[$message['group']][$message['uid']])){
  128. do{
  129. $newKfList = $kfList;
  130. $newKfList[$message['group']][$message['uid']]['client_id'] = $client_id;
  131. }while(!self::$global->cas('kfList', $kfList, $newKfList));
  132. unset($newKfList, $kfList);
  133. }
  134. // 绑定 client_id 和 uid
  135. Gateway::bindUid($client_id, $message['uid']);
  136. // TODO 尝试拉取用户来服务 [二期规划]
  137. break;
  138. // 顾客初始化
  139. case 'userInit';
  140. $userList = self::$global->userList;
  141. // 如果该顾客未在内存中记录则记录
  142. if(!array_key_exists($message['uid'], $userList)){
  143. do{
  144. $NewUserList = $userList;
  145. $NewUserList[$message['uid']] = [
  146. 'id' => $message['uid'],
  147. 'name' => $message['name'],
  148. 'avatar' => $message['avatar'],
  149. 'website' => $_SESSION['origin'],//$_SERVER['HTTP_ORIGIN'],
  150. 'browse' => Gateway::browse_info(),
  151. 'system' => Gateway::get_os(),
  152. 'ip' => isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '',
  153. 'group' => $message['group'],
  154. 'client_id' => $client_id
  155. ];
  156. }while(!self::$global->cas('userList', $userList, $NewUserList));
  157. unset($NewUserList, $userList);
  158. // 维护 UID对应的client_id 数组
  159. do{
  160. $old = $newList = self::$global->uidSimpleList;
  161. $newList[$message['uid']] = [
  162. $client_id,
  163. $message['group']
  164. ];
  165. }while(!self::$global->cas('uidSimpleList', $old, $newList));
  166. unset($old, $newList);
  167. // 写入接入值
  168. $key = date('Ymd') . 'total_in';
  169. self::$global->$key = 0;
  170. do{
  171. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  172. unset(self::$global->$oldKey);
  173. }while(!self::$global->increment($key));
  174. unset($key);
  175. }
  176. // 绑定 client_id 和 uid
  177. Gateway::bindUid($client_id, $message['uid']);
  178. // 尝试分配新会员进入服务
  179. self::userOnlineTask($client_id, $message['group']);
  180. break;
  181. // 聊天
  182. case 'chatMessage':
  183. $client = Gateway::getClientIdByUid($message['data']['to_id']);
  184. if(!empty($client)){
  185. $chat_message = [
  186. 'message_type' => 'chatMessage',
  187. 'data' => [
  188. 'name' => $message['data']['from_name'],
  189. 'avatar' => $message['data']['from_avatar'],
  190. 'id' => $message['data']['from_id'],
  191. 'time' => date('H:i'),
  192. 'content' => htmlspecialchars($message['data']['content']),
  193. ]
  194. ];
  195. Gateway::sendToClient($client['0'], json_encode($chat_message));
  196. unset($chat_message);
  197. // 聊天信息入库
  198. $serviceLog = [
  199. 'from_id' => $message['data']['from_id'],
  200. 'from_name' => $message['data']['from_name'],
  201. 'from_avatar' => $message['data']['from_avatar'],
  202. 'to_id' => $message['data']['to_id'],
  203. 'to_name' => $message['data']['to_name'],
  204. 'content' => $message['data']['content'],
  205. 'time_line' => time()
  206. ];
  207. self::$db->insert('ws_chat_log')->cols($serviceLog)->query();
  208. unset($serviceLog);
  209. }
  210. break;
  211. // 转接
  212. case 'changeGroup':
  213. // 通知客户端转接中
  214. $simpleList = self::$global->uidSimpleList;
  215. if(!isset($simpleList[$message['uid']])){ // 客户已经退出
  216. return ;
  217. }
  218. $userClient = $simpleList[$message['uid']]['0'];
  219. $userGroup = $simpleList[$message['uid']]['1']; // 会员原来的分组也是客服的分组
  220. $reLink = [
  221. 'message_type' => 'relinkMessage'
  222. ];
  223. Gateway::sendToClient($userClient, json_encode($reLink));
  224. unset($reLink);
  225. // 记录该客服与该会员的服务结束
  226. self::$db->query("update `ws_service_log` set `end_time` = " . time() . " where `client_id`= '" . $userClient . "'");
  227. // 从当前客服的服务表中删除这个会员
  228. $old = $kfList = self::$global->kfList;
  229. if(!isset($kfList[$userGroup])){
  230. $waitMsg = '暂时没有相关客服上班,请稍后再咨询。';
  231. // 逐一通知
  232. foreach(self::$global->userList as $vo){
  233. $waitMessage = [
  234. 'message_type' => 'wait',
  235. 'data' => [
  236. 'content' => $waitMsg,
  237. ]
  238. ];
  239. Gateway::sendToClient($userClient, json_encode($waitMessage));
  240. unset($waitMessage);
  241. }
  242. return ;
  243. }
  244. $myList = $kfList[$userGroup]; // 该客服分组数组
  245. foreach($myList as $key=>$vo){
  246. if(in_array($userClient, $vo['user_info'])){
  247. // 维护现在的该客服的服务信息
  248. $kfList[$userGroup][$key]['task'] -= 1; // 当前服务的人数 -1
  249. foreach($vo['user_info'] as $k=>$v){
  250. if($userClient == $v){
  251. unset($kfList[$userGroup][$key]['user_info'][$k]);
  252. break;
  253. }
  254. }
  255. break;
  256. }
  257. }
  258. while(!self::$global->cas('kfList', $old, $kfList)){}; // 刷新内存中客服的服务列表
  259. unset($old, $kfList, $myList);
  260. // 将会员加入队列中
  261. $userList = self::$global->userList;
  262. do{
  263. $NewUserList = $userList;
  264. $NewUserList[$message['uid']] = [
  265. 'id' => $message['uid'],
  266. 'name' => $message['name'],
  267. 'avatar' => $message['avatar'],
  268. 'ip' => $message['ip'],
  269. 'group' => $message['group'], // 指定要链接的分组
  270. 'client_id' => $userClient
  271. ];
  272. }while(!self::$global->cas('userList', $userList, $NewUserList));
  273. unset($NewUserList, $userList);
  274. // 执行会员分配通知双方
  275. self::userOnlineTask($userClient, $message['group']);
  276. unset($userClient, $userGroup);
  277. break;
  278. case 'closeUser':
  279. $userInfo = self::$global->uidSimpleList;
  280. if(isset($userInfo[$message['uid']])){
  281. $waitMessage = [
  282. 'message_type' => 'wait',
  283. 'data' => [
  284. 'content' => '暂时没有客服上班,请稍后再咨询。',
  285. ]
  286. ];
  287. Gateway::sendToClient($userInfo[$message['uid']]['0'], json_encode($waitMessage));
  288. unset($waitMessage);
  289. }
  290. unset($userInfo);
  291. break;
  292. // 机器人问答.
  293. case 'toRobot':
  294. self::toRobot($client_id, $message);
  295. break;
  296. // 评价.
  297. case 'evaluate':
  298. self::evaluate($client_id, $message);
  299. break;
  300. // 关闭会话.
  301. case 'closeUser':
  302. $client = Gateway::getClientIdByUid($message['data']['to_id']);
  303. if(!empty($client)){
  304. self::onClose($client['0']);
  305. }
  306. break;
  307. }
  308. }
  309. /**
  310. * 当用户断开连接时触发
  311. * @param int $client_id 连接id
  312. *
  313. * tips: 当服务端主动退出的时候,会出现 exit status 9.原因是:服务端主动断开之后,连接的客户端会走这个方法,而短时间内进程
  314. * 需要处理这多的逻辑,又有cas操作,导致进程退出会超时,然后会被内核杀死,从而报出错误 9.实际对真正的业务没有任何的影响。
  315. */
  316. public static function onClose($client_id)
  317. {
  318. print_r([$client_id,self::$global->uidSimpleList,self::$global->userList]);
  319. $isServiceUserOut = false;
  320. // 将会员服务信息,从客服的服务列表中移除
  321. $old = $kfList = self::$global->kfList;
  322. foreach($kfList as $k=>$v){
  323. foreach($v as $key=>$vo){
  324. if(in_array($client_id, $vo['user_info'])){
  325. $isServiceUserOut = true;
  326. // 根据client id 去更新这个会员离线的一些信息
  327. self::$db->query("update `ws_service_log` set `end_time` = " . time() . " , `status` = '2' where `client_id`= '" . $client_id . "'");
  328. // 从会员的内存表中检索出该会员的信息,并更新内存
  329. $oldSimple = $simpleList = self::$global->uidSimpleList;
  330. $outUser = [];
  331. foreach($simpleList as $u=>$c){
  332. if($c['0'] == $client_id){
  333. $outUser[] = [
  334. 'user_id' => $u,
  335. 'group_id' => $c['1']
  336. ];
  337. unset($simpleList[$u]);
  338. break;
  339. }
  340. }
  341. while(!self::$global->cas('uidSimpleList', $oldSimple, $simpleList)){};
  342. unset($oldSimple, $simpleList);
  343. //$outUser = self::$db->query("select `user_id`,`group_id` from `ws_service_log` where `client_id`= '" . $client_id . "'");
  344. // 通知 客服删除退出的用户
  345. if(!empty($outUser)){
  346. $del_message = [
  347. 'message_type' => 'delUser',
  348. 'data' => [
  349. 'id' => $outUser['0']['user_id']
  350. ]
  351. ];
  352. Gateway::sendToClient($vo['client_id'], json_encode($del_message));
  353. unset($del_message);
  354. // 尝试分配新会员进入服务
  355. self::userOfflineTask($outUser['0']['group_id']);
  356. }
  357. unset($outUser);
  358. // 维护现在的该客服的服务信息
  359. $kfList[$k][$key]['task'] -= 1; // 当前服务的人数 -1
  360. foreach($vo['user_info'] as $m=>$l){
  361. if($client_id == $l){
  362. unset($kfList[$k][$key]['user_info'][$m]);
  363. break;
  364. }
  365. }
  366. // 刷新内存中客服的服务列表
  367. while(!self::$global->cas('kfList', $old, $kfList)){};
  368. unset($old, $kfList);
  369. break;
  370. }
  371. }
  372. if($isServiceUserOut) break;
  373. }
  374. // 尝试从排队的用户中删除退出的客户端
  375. if(false == $isServiceUserOut){
  376. $old = $userList = self::$global->userList;
  377. foreach(self::$global->userList as $key=>$vo){
  378. if($client_id == $vo['client_id']){
  379. $isServiceUserOut = true;
  380. unset($userList[$key]);
  381. break;
  382. }
  383. }
  384. while(!self::$global->cas('userList', $old, $userList)){};
  385. // 从会员的内存表中检索出该会员的信息,并更新内存
  386. $oldSimple = $simpleList = self::$global->uidSimpleList;
  387. foreach($simpleList as $u=>$c){
  388. if($c['0'] == $client_id){
  389. unset($simpleList[$u]);
  390. break;
  391. }
  392. }
  393. while(!self::$global->cas('uidSimpleList', $oldSimple, $simpleList)){};
  394. unset($oldSimple, $simpleList);
  395. }
  396. // 尝试是否是客服退出
  397. if(false == $isServiceUserOut){
  398. $old = $kfList = self::$global->kfList;
  399. foreach(self::$global->kfList as $k=>$v){
  400. foreach($v as $key=>$vo){
  401. // 客服服务列表中无数据,才去删除客服内存信息
  402. if($client_id == $vo['client_id'] && (0 == count($vo['user_info']))){
  403. unset($kfList[$k][$key]);
  404. break;
  405. }
  406. }
  407. }
  408. while(!self::$global->cas('kfList', $old, $kfList)){};
  409. }
  410. }
  411. /**
  412. * 有人退出
  413. * @param $group
  414. */
  415. private static function userOfflineTask($group)
  416. {
  417. // TODO 此处查询最大的可服务人数,后面可以用其他的方式,存储这个数值,让其更高效的访问
  418. $maxNumber = self::getMaxServiceNum();
  419. $res = self::assignmentTask(self::$global->kfList, self::$global->userList, $group, $maxNumber);
  420. unset($maxNumber);
  421. if(1 == $res['code']){
  422. while(!self::$global->cas('kfList', self::$global->kfList, $res['data']['4'])){}; // 更新客服数据
  423. while(!self::$global->cas('userList', self::$global->userList, $res['data']['5'])){}; // 更新会员数据
  424. // 通知会员发送信息绑定客服的id
  425. $noticeUser = [
  426. 'message_type' => 'connect',
  427. 'data' => [
  428. 'kf_id' => $res['data']['0'],
  429. 'kf_name' => $res['data']['1']
  430. ]
  431. ];
  432. Gateway::sendToClient($res['data']['3']['client_id'], json_encode($noticeUser));
  433. unset($noticeUser);
  434. // 通知客服端绑定会员的信息
  435. $noticeKf = [
  436. 'message_type' => 'connect',
  437. 'data' => [
  438. 'user_info' => $res['data']['3']
  439. ]
  440. ];
  441. Gateway::sendToClient($res['data']['2'], json_encode($noticeKf));
  442. unset($noticeKf);
  443. // 逐一通知
  444. $number = 1;
  445. foreach(self::$global->userList as $vo){
  446. $waitMsg = '您前面还有 ' . $number . ' 位会员在等待。';
  447. $waitMessage = [
  448. 'message_type' => 'wait',
  449. 'data' => [
  450. 'content' => $waitMsg,
  451. ]
  452. ];
  453. Gateway::sendToClient($vo['client_id'], json_encode($waitMessage));
  454. $number++;
  455. }
  456. unset($waitMessage, $number);
  457. // 写入接入值
  458. $key = date('Ymd') . 'success_in';
  459. self::$global->$key = 0;
  460. do{
  461. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  462. unset(self::$global->$oldKey);
  463. }while(!self::$global->increment($key));
  464. unset($key);
  465. }else{
  466. switch ($res['code']){
  467. case -1:
  468. $waitMsg = '暂时没有客服上班,请稍后再咨询。';
  469. // 逐一通知
  470. foreach(self::$global->userList as $vo){
  471. $waitMessage = [
  472. 'message_type' => 'wait',
  473. 'data' => [
  474. 'content' => $waitMsg,
  475. ]
  476. ];
  477. Gateway::sendToClient($vo['client_id'], json_encode($waitMessage));
  478. }
  479. break;
  480. case -2:
  481. break;
  482. case -3:
  483. break;
  484. case -4:
  485. // 逐一通知
  486. $number = 1;
  487. foreach(self::$global->userList as $vo){
  488. $waitMsg = '您前面还有 ' . $number . ' 位会员在等待。';
  489. $waitMessage = [
  490. 'message_type' => 'wait',
  491. 'data' => [
  492. 'content' => $waitMsg,
  493. ]
  494. ];
  495. Gateway::sendToClient($vo['client_id'], json_encode($waitMessage));
  496. $number++;
  497. }
  498. break;
  499. }
  500. unset($waitMessage, $number);
  501. }
  502. }
  503. /**
  504. * 有人进入执行分配
  505. * @param $client_id
  506. * @param $group
  507. */
  508. private static function userOnlineTask($client_id, $group)
  509. {
  510. // TODO 此处查询最大的可服务人数,后面可以用其他的方式,存储这个数值,让其更高效的访问
  511. $maxNumber = self::getMaxServiceNum();
  512. $res = self::assignmentTask(self::$global->kfList, self::$global->userList, $group, $maxNumber);
  513. unset($maxNumber);
  514. if(1 == $res['code']){
  515. while(!self::$global->cas('kfList', self::$global->kfList, $res['data']['4'])){}; // 更新客服数据
  516. while(!self::$global->cas('userList', self::$global->userList, $res['data']['5'])){}; // 更新会员数据
  517. // 通知会员发送信息绑定客服的id
  518. $noticeUser = [
  519. 'message_type' => 'connect',
  520. 'data' => [
  521. 'kf_id' => $res['data']['0'],
  522. 'kf_name' => $res['data']['1']
  523. ]
  524. ];
  525. Gateway::sendToClient($client_id, json_encode($noticeUser));
  526. unset($noticeUser);
  527. // 检测是否开启自动应答
  528. $sayHello = self::$db->query('select `word`,`status` from `ws_reply` where `id` = 1');
  529. if(!empty($sayHello) && 1 == $sayHello['0']['status']){
  530. $hello = [
  531. 'message_type' => 'helloMessage',
  532. 'data' => [
  533. 'name' => $res['data']['1'],
  534. 'avatar' => '',
  535. 'id' => $res['data']['0'],
  536. 'time' => date('H:i'),
  537. 'content' => htmlspecialchars($sayHello['0']['word'])
  538. ]
  539. ];
  540. Gateway::sendToClient($client_id, json_encode($hello));
  541. unset($hello);
  542. }
  543. unset($sayHello);
  544. // 通知客服端绑定会员的信息
  545. $noticeKf = [
  546. 'message_type' => 'connect',
  547. 'data' => [
  548. 'user_info' => $res['data']['3']
  549. ]
  550. ];
  551. Gateway::sendToClient($res['data']['2'], json_encode($noticeKf));
  552. unset($noticeKf);
  553. // 服务信息入库
  554. $serviceLog = [
  555. 'user_id' => $res['data']['3']['id'],
  556. 'client_id' => $res['data']['3']['client_id'],
  557. 'user_name' => $res['data']['3']['name'],
  558. 'user_ip' => $res['data']['3']['ip'],
  559. 'user_avatar' => $res['data']['3']['avatar'],
  560. 'kf_id' => intval(ltrim($res['data']['0'], 'KF')),
  561. 'start_time' => time(),
  562. 'group_id' => $group,
  563. 'website' => $res['data']['3']['website'],
  564. 'system' => $res['data']['3']['system'],
  565. 'browse' => $res['data']['3']['browse'],
  566. 'status' => 1,
  567. 'end_time' => 0
  568. ];
  569. self::$db->insert('ws_service_log')->cols($serviceLog)->query();
  570. unset($serviceLog);
  571. // 写入接入值
  572. $key = date('Ymd') . 'success_in';
  573. self::$global->$key = 0;
  574. do{
  575. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  576. unset(self::$global->$oldKey);
  577. }while(!self::$global->increment($key));
  578. unset($key);
  579. }else{
  580. $waitMsg = '';
  581. switch ($res['code']){
  582. case -1:
  583. $waitMsg = '暂时没有客服上班,请稍后再咨询。';
  584. break;
  585. case -2:
  586. break;
  587. case -3:
  588. break;
  589. case -4:
  590. $number = count(self::$global->userList);
  591. $waitMsg = '您前面还有 ' . $number . ' 位会员在等待。';
  592. break;
  593. }
  594. $waitMessage = [
  595. 'message_type' => 'wait',
  596. 'data' => [
  597. 'content' => $waitMsg,
  598. ]
  599. ];
  600. Gateway::sendToClient($client_id, json_encode($waitMessage));
  601. unset($waitMessage);
  602. }
  603. }
  604. /**
  605. * 给客服分配会员【均分策略】
  606. * @param $kfList
  607. * @param $userList
  608. * @param $group
  609. * @param $total
  610. */
  611. private static function assignmentTask($kfList, $userList, $group, $total)
  612. {
  613. // 没有客服上线
  614. if(empty($kfList) || empty($kfList[$group])){
  615. return ['code' => -1];
  616. }
  617. // 没有待分配的会员
  618. if(empty($userList)){
  619. return ['code' => -2];
  620. }
  621. // 未设置每个客服可以服务多少人
  622. if(0 == $total){
  623. return ['code' => -3];
  624. }
  625. // 查看该组的客服是否在线
  626. if(!isset($kfList[$group])){
  627. return ['code' => -1];
  628. }
  629. $kf = $kfList[$group];
  630. $user = array_shift($userList);
  631. $kf = array_shift($kf);
  632. $min = $kf['task'];
  633. $flag = $kf['id'];
  634. foreach($kfList[$group] as $key=>$vo){
  635. if($vo['task'] < $min){
  636. $min = $vo['task'];
  637. $flag = $key;
  638. }
  639. }
  640. unset($kf);
  641. // 需要排队了
  642. if($kfList[$group][$flag]['task'] == $total){
  643. return ['code' => -4];
  644. }
  645. $kfList[$group][$flag]['task'] += 1;
  646. array_push($kfList[$group][$flag]['user_info'], $user['client_id']); // 被分配的用户信息
  647. return [
  648. 'code' => 1,
  649. 'data' => [
  650. $kfList[$group][$flag]['id'],
  651. $kfList[$group][$flag]['name'],
  652. $kfList[$group][$flag]['client_id'],
  653. $user,
  654. $kfList,
  655. $userList
  656. ]
  657. ];
  658. }
  659. /**
  660. * 获取最大的服务人数
  661. * @return int
  662. */
  663. private static function getMaxServiceNum()
  664. {
  665. $maxNumber = self::$db->query('select `max_service` from `ws_kf_config` where `id` = 1');
  666. if(!empty($maxNumber)){
  667. $maxNumber = 5;
  668. }else{
  669. $maxNumber = $maxNumber['0']['max_service'];
  670. }
  671. return $maxNumber;
  672. }
  673. /**
  674. * 将内存中的数据写入统计表
  675. * @param int $flag
  676. */
  677. private static function writeLog($flag = 1)
  678. {
  679. // 上午 8点 到 22 点开始统计
  680. if(date('H') < 8 || date('H') > 22){
  681. return ;
  682. }
  683. // 当前正在接入的人 和 在线客服数
  684. $kfList = self::$global->kfList;
  685. $nowTalking = 0;
  686. $onlineKf = 0;
  687. if(!empty($kfList)){
  688. foreach($kfList as $key=>$vo){
  689. $onlineKf += count($vo);
  690. foreach($vo as $k=>$v){
  691. $nowTalking += count($v['user_info']);
  692. }
  693. }
  694. }
  695. // 在队列中的用户
  696. $inQueue = count(self::$global->userList);
  697. $key = date('Ymd') . 'total_in';
  698. $key2 = date('Ymd') . 'success_in';
  699. $param = [
  700. 'is_talking' => $nowTalking,
  701. 'in_queue' => $inQueue,
  702. 'online_kf' => $onlineKf,
  703. 'success_in' => self::$global->$key2,
  704. 'total_in' => self::$global->$key,
  705. 'now_date' => date('Y-m-d')
  706. ];
  707. self::$db->update('ws_now_data')->cols($param)->where('id=1')->query();
  708. if(2 == $flag){
  709. $param = [
  710. 'is_talking' => $nowTalking,
  711. 'in_queue' => $inQueue,
  712. 'online_kf' => $onlineKf,
  713. 'success_in' => self::$global->$key2,
  714. 'total_in' => self::$global->$key,
  715. 'add_date' => date('Y-m-d'),
  716. 'add_hour' => date('H'),
  717. 'add_minute' => date('i'),
  718. ];
  719. self::$db->insert('ws_service_data')->cols($param)->query();
  720. }
  721. unset($kfList, $nowTalking, $inQueue, $onlineKf, $key, $key2, $param);
  722. }
  723. /**
  724. * 机器人问答
  725. * @param $client_id 服务ID
  726. * @param $message 数据
  727. */
  728. private static function toRobot($client_id, $message)
  729. {
  730. $groups_id = $message['data']['groups_id'];
  731. $robot_name = $message['data']['robot_name'];
  732. $robotgroups_id = $message['data']['robotgroups_id'];
  733. // 查询问题.
  734. $getRobot = self::$db->query("select `robot_content` from `ws_robot` where `robot_status`= 1 and `groups_id`= '" . $groups_id . "' and `robot_name`= '" . $robot_name . "' and `robotgroups_id`= '" . $robotgroups_id . "'");
  735. $chat_message = [
  736. 'message_type' => 'chatMessage',
  737. 'data' => [
  738. 'name' => '智能助手',
  739. 'time' => date('H:i'),
  740. 'content' => $getRobot ? htmlspecialchars($getRobot[0]['robot_content']) : 'error',
  741. ]
  742. ];
  743. Gateway::sendToClient($client_id, json_encode($chat_message));
  744. }
  745. /**
  746. * 评价
  747. * @param $client_id 服务ID
  748. * @param $message 数据
  749. */
  750. private static function evaluate($client_id, $message)
  751. {
  752. // 查询问题.
  753. $evaluate_id = $message['data']['evaluate_id'];
  754. $result = self::$db->query("UPDATE `ws_service_log` SET `evaluate_id` = '" . $evaluate_id . "' WHERE `client_id`='" . $client_id . "'");
  755. if ($result) {
  756. $chat_message = [
  757. 'message_type' => 'evaluate',
  758. 'data' => [
  759. 'status' => 1,
  760. 'time' => date('H:i'),
  761. ]
  762. ];
  763. } else {
  764. $chat_message = [
  765. 'message_type' => 'evaluate',
  766. 'data' => [
  767. 'status' => 2,
  768. 'time' => date('H:i'),
  769. ]
  770. ];
  771. }
  772. Gateway::sendToClient($client_id, json_encode($chat_message));
  773. }
  774. //踢掉同一用户的旧用户
  775. private static function tickOlduser($uid){
  776. }
  777. }