<?php
/**
 * This file is part of workerman.
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the MIT-LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @author walkor<walkor@workerman.net>
 * @copyright walkor<walkor@workerman.net>
 * @link http://www.workerman.net/
 * @license http://www.opensource.org/licenses/mit-license.php MIT License
 */

/**
 * 用于检测业务代码死循环或者长时间阻塞等问题
 * 如果发现业务卡死，可以将下面declare打开（去掉//注释），并执行php start.php reload
 * 然后观察一段时间workerman.log看是否有process_timeout异常
 */

//declare(ticks=1);
use \GatewayWorker\Lib\Gateway;
use Workerman\Lib\Timer;

/**
 * 主逻辑
 * 主要是处理 onConnect onMessage onClose 三个方法
 * onConnect 和 onClose 如果不需要可以不用实现并删除
 */
class EventsBak
{
    /**
     * 新建一个类的静态成员，用来保存数据库实例
     */
    public static $db = null;
    public static $global = null;

    /**
     * 进程启动后初始化数据库连接
     */
    public static function onWorkerStart($worker)
    {
        if (empty(self::$db)) {
            $mds = DIRECTORY_SEPARATOR;
            if (strtolower(substr(PHP_OS, 0, 3)) == 'win') {
                $dbcfg = realpath(dirname(__FILE__) . $mds . '..' . $mds . '..' . $mds . '..' . $mds . '..') . $mds . 'application' . $mds . 'database.php';
            } else {
                $dbcfg = realpath(dirname(__FILE__) . $mds . '..' . $mds . '..' . $mds . '..' . $mds . '..' . $mds . '..') . $mds . 'application' . $mds . 'database.php';
            }
            $conf = require($dbcfg);
            self::$db = new \Workerman\MySQL\Connection($conf['hostname'], $conf['hostport'], $conf['username'], $conf['password'], $conf['database']);
        }


        if (empty(self::$global)) {
            self::$global = new \GlobalData\Client('127.0.0.1:2207');
            // 客服列表
            if (is_null(self::$global->kfList)) {
                self::$global->kfList = [];
            }
            // 会员列表[动态的，这里面只是目前未被分配的会员信息]
            if (is_null(self::$global->userList)) {
                self::$global->userList = [];
            }
            // 会员以 uid 为key的信息简表,只有在用户退出的时候，才去执行修改
            if (is_null(self::$global->uidSimpleList)) {
                self::$global->uidSimpleList = [];
            }
            // 当天的累积接入值
            $key = date('Ymd') . 'total_in';
            if (is_null(self::$global->$key)) {
                self::$global->$key = 0;

                $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
                unset(self::$global->$oldKey);
                unset($oldKey, $key);
            }
            // 成功接入值
            $key = date('Ymd') . 'success_in';
            if (is_null(self::$global->$key)) {
                self::$global->$key = 0;

                $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
                unset(self::$global->$oldKey);
                unset($oldKey, $key);
            }
        }

        // 定时统计数据
        if (0 == $worker->id) {

            self::writeLogKfStatus(0, 0, 0);

            // 1分钟统计一次实时数据
            Timer::add(60 * 1, function () {
                self::writeLog(1);
            });
            // 40分钟写一次当前日期点数的log数据
            Timer::add(60 * 40, function () {
                self::writeLog(2);
            });

            //每1分钟发一次本组排队数
            Timer::add(60 * 1, function () {
                self::lineup();
            });

            //初始化.....
            self::upsystemconfig();
            //每5分钟更新一次系统配置文件
            Timer::add(60 * 3, function () {
                self::upsystemconfig();
            });

            // 检查对话时效给出.
            Timer::add(6, function () {
                self::overTime();
            });

            // 实时监控.
            Timer::add(60, function () {
                $adminList = self::$global->adminList ?? [];
                if ($adminList) {
                    self::systemMonitoring($adminList);
                }
            });

            self::resetServiceLog();
        }

    }

    /**
     * 每分钟定时向客服发送一次排队情况
     */

    public static function lineup()
    {
        $userlist = self::$global->userList;
        $kflist = self::$global->kfList;

        if (empty($userlist) || empty($kflist)) {
            return;
        }

        $return = [];
        foreach ($userlist as $val) {
            $return[$val['group']] = isset($return[$val['group']]) ? $return[$val['group']] + 1 : 1;
        }

        foreach ($return as $fgroup => $fval) {
            Gateway::sendToGroup('group_' . $fgroup, json_encode(['type' => 'lineupCount', $fval], 256));
        }
        return;
    }


    /**
     * 当客户端连接时触发
     * 如果业务不需此回调可以删除onConnect
     *
     * @param int $client_id 连接id
     */
    public static function onConnect($client_id)
    {
        // 检测是否开启自动应答
        $sayHello = self::$db->query('select `word`,`status` from `ws_reply` where `id` = 1');
        if (!empty($sayHello) && 1 == $sayHello['0']['status']) {

            $hello = [
                'message_type' => 'helloMessage',
                'data' => [
                    'name' => '智能助手',
                    'time' => date('H:i'),
                    'content' => $sayHello['0']['word']
                ]
            ];
            Gateway::sendToClient($client_id, json_encode($hello, 256));
            unset($hello);
        }
        unset($sayHello);
        // 检测是否开启广告
        $advertisement = self::$db->query('select * from `ws_advertisement` where `advertisement_status` = 1');
        if (!empty($advertisement)) {
            $chat_message = [
                'message_type' => 'advertisement',
                'data' => $advertisement
            ];
            Gateway::sendToClient($client_id, json_encode($chat_message, 256));
            unset($chat_message);
        }
        unset($advertisement);
    }

    /**
     * 当客户端发来消息时触发
     * @param int $client_id 连接id
     * @param mixed $message 具体消息
     */
    public static function onMessage($client_id, $message)
    {
        if ($message == '{"type":"ping"}') {
            Gateway::sendToCurrentClient('{"type":"pong"}');
            return;
        } else {
            self::DebugOut($message, "OnMessage");
            self::DebugOut([self::$global->kfList, self::$global->userList, self::$global->uidSimpleList, self::$global->userToKf, $_SESSION['remotip'] . ':' . $_SESSION['remotport']], 'Msg mem: ');
        }
        $message = json_decode($message, true);
        if (isset($message['type'])) {
            switch ($message['type']) {
                // 管理员初始化
                case 'adminInit':
                    $token = $message['token'];
                    self::adminInit($client_id, $token);
                    break;
                // 客服初始化
                case 'init':
                    $data = $message['data'];
                    self::Kfinit($client_id, $data);
                    break;
                // 顾客初始化
                case 'userInit';
                    $data = $message['data'];
                    self::userInitEnt($client_id, $data);
                    break;
                //在线客服信息
                case 'getkfonlines':
                    Gateway::sendToCurrentClient(json_encode(self::getkfonlines(), 256));
                    break;
                case 'kfgetuserinfo':
                    $tmp_id = isset($message['data']['id']) ? $message['data']['id'] : 0;
                    self::kfgetuserinfo($client_id, intval($tmp_id));
                    break;
                case 'chatMessage':
                    $client = Gateway::getClientIdByUid($message['data']['to_id']);
                    if (!empty($client)) {
                        $chat_message = [
                            'message_type' => 'chatMessage',
                            'data' => [
                                'name' => $message['data']['from_name'],
                                'id' => $message['data']['from_id'],
                                'time' => date('H:i'),
                                'content' => $message['data']['content'],
                            ]
                        ];
                        Gateway::sendToClient($client['0'], json_encode($chat_message));
                        unset($chat_message);

                        // 聊天信息入库
                        $serviceLog = [
                            'from_id' => $message['data']['from_id'],
                            'from_name' => $message['data']['from_name'],
                            'to_id' => $message['data']['to_id'],
                            'to_name' => $message['data']['to_name'],
                            'content' => $message['data']['content'],
                            'servicelog_id' => $message['data']['conversationId'],
                            'time_line' => time()
                        ];
                        self::$db->insert('ws_chat_log')->cols($serviceLog)->query();

                        /*
                        if ($message['data']['sensitiveNumber']) {

                        }
                        self::$db->query("update `ws_alarm` set `alarm_corresponding` = '$corresponding',alarm_respond=2 where `servicelog_id`= '$servicelog_id'");
                        */

                        unset($serviceLog);
                    }
                    if (isset($message['data']['isFirst']) && $message['data']['isFirst']) {
                        $servicelog_id = $message['data']['conversationId'];
                        $serviceLog = self::$db->query("select `start_time` from `ws_service_log` where `servicelog_id`= '$servicelog_id'");
                        $corresponding = time() - $serviceLog[0]['start_time'];
                        self::$db->query("update `ws_alarm` set `alarm_corresponding` = '$corresponding',alarm_respond=2 where `servicelog_id`= '$servicelog_id'");
                    }
                    break;
                // 转接
                case 'changeGroup':
                    // 通知客户端转接中
                    $simpleList = self::$global->uidSimpleList;

                    if (!isset($simpleList[$message['uid']])) { // 客户已经退出
                        return;
                    }

                    $userClient = $simpleList[$message['uid']]['0'];
                    $userGroup = $simpleList[$message['uid']]['1'];  // 会员原来的分组也是客服的分组

                    $reLink = [
                        'message_type' => 'relinkMessage'
                    ];
                    Gateway::sendToClient($userClient, json_encode($reLink, 256));
                    unset($reLink);

                    // 记录该客服与该会员的服务结束
                    $servicelog_id = $message['data']['conversationId'];
                    self::$db->query("update `ws_service_log` set `end_time` = " . time() . " , `status` = '2' where `servicelog_id`= '" . $servicelog_id . "'");

                    // 修改会话时长
                    $serviceLog = self::$db->query("select `start_time`,`intime` from `ws_service_log` where `servicelog_id`= '$servicelog_id'");
                    $logCount = self::$db->query("select count(*) as `count` from `ws_chat_log` where `servicelog_id`= '$servicelog_id'");
                    $alarmCount = $logCount[0]['count'];
                    $cvtOvertime = time() - $serviceLog[0]['start_time'];
                    $alarmLineTime = $serviceLog[0]['start_time'] - $serviceLog[0]['intime'];
                    self::$db->query("update `ws_alarm` set `alarm_cvtOvertime` = '$cvtOvertime',`alarm_lineTime` = '$alarmLineTime',`alarm_count` = '$alarmCount'
                                      where `servicelog_id`= '$servicelog_id'");

                    // 从当前客服的服务表中删除这个会员
                    $old = $kfList = self::$global->kfList;
                    if (!isset($kfList[$userGroup])) {
                        $waitMsg = '暂时没有相关客服上班,请稍后再咨询。';
                        // 逐一通知
                        foreach (self::$global->userList as $vo) {

                            $waitMessage = [
                                'message_type' => 'wait',
                                'data' => [
                                    'content' => $waitMsg,
                                ]
                            ];
                            Gateway::sendToClient($userClient, json_encode($waitMessage, 256));
                            unset($waitMessage);
                        }
                        return;
                    }
                    $myList = $kfList[$userGroup]; // 该客服分组数组
                    foreach ($myList as $key => $vo) {
                        if (in_array($userClient, $vo['user_info'])) {

                            // 维护现在的该客服的服务信息
                            $kfList[$userGroup][$key]['task'] -= 1; // 当前服务的人数 -1
                            foreach ($vo['user_info'] as $k => $v) {
                                if ($userClient == $v) {
                                    unset($kfList[$userGroup][$key]['user_info'][$k]);
                                    break;
                                }
                            }

                            break;
                        }
                    }
                    while (!self::$global->cas('kfList', $old, $kfList)) {
                    }; // 刷新内存中客服的服务列表
                    unset($old, $kfList, $myList);

                    // 将会员加入队列中
                    $userList = self::$global->userList;
                    do {
                        $NewUserList = $userList;
                        $NewUserList[$message['uid']] = [
                            'id' => $message['uid'],
                            'name' => $message['name'],
                            'avatar' => $message['avatar'],
                            'ip' => $message['ip'],
                            'group' => $message['group'], // 指定要链接的分组
                            'client_id' => $userClient
                        ];

                    } while (!self::$global->cas('userList', $userList, $NewUserList));
                    unset($NewUserList, $userList);

                    // 执行会员分配通知双方
                    self::userOnlineTask($userClient, $message['group']);
                    unset($userClient, $userGroup);

                    break;
                case 'closeUser':

                    $userInfo = self::$global->uidSimpleList;
                    if (isset($userInfo[$message['uid']])) {
                        $waitMessage = [
                            'message_type' => 'wait',
                            'data' => [
                                'content' => '暂时没有客服上班,请稍后再咨询。',
                            ]
                        ];
                        Gateway::sendToClient($userInfo[$message['uid']]['0'], json_encode($waitMessage, 256));
                        unset($waitMessage);
                    }
                    unset($userInfo);
                    break;
                // 机器人问答.
                case 'toRobot':
                    self::toRobot($client_id, $message);
                    break;
                // 评价.
                case 'evaluate':
                    self::evaluate($client_id, $message);
                    break;
                // 客服关闭会话.
                case 'kfCloseUser':
                    $userId = $message['data']['to_id'];
                    $kfId = $message['data']['kf_id'];
                    $groupId = $message['data']['group_id'];
                    $client = Gateway::getClientIdByUid($userId);
                    $servicelog_id = $message['data']['conversationId'];
                    self::$db->query("update `ws_service_log` set `servicelog_close_type` = 3 where `servicelog_id`= '$servicelog_id'");
                    if (!empty($client)) {
                        $clientId = $client['0'];
                        self::serverClose($clientId, $servicelog_id, $userId, $kfId, $groupId);
                    } else {
                        self::closeUser($servicelog_id, $userId, $kfId, $groupId);
                    }
                    break;
                // 客服更改状态.
                case 'kfOnline':
                    if (!isset($_SESSION['iskefu']) || $_SESSION['iskefu'] != 1) {
                        return;
                    }
                    $kfList = self::$global->kfList;
                    $userId = $message['data']['uid'];
                    $status = $message['data']['status'];
                    $oldstatus = '';
                    foreach ($kfList as $k => $v) {
                        foreach ($v as $ke => $va) {
                            if ($ke == $userId) {
                                $oldstatus = $kfList[$k][$ke]['status'];
                                if ($oldstatus != $status) {
                                    $kfList[$k][$ke]['status'] = $status;
                                    break 2;
                                } else {
                                    return;
                                }
                            }
                        }
                    }
                    self::$global->kfList = $kfList;
                    self::writeLogKfStatus($userId, $status);
                    Gateway::sendToCurrentClient(json_encode(['message_type' => 'cgstatus', 'data' => ['new_status' => $status, 'old_status' => $oldstatus]]));

                    break;
                case 'changeOtherhKeFu';
                    $servicelog_id = $message['data']['conversationId'];
                    self::$db->query("update `ws_service_log` set `servicelog_close_type` = 5 where `servicelog_id`= '$servicelog_id'");
                    self::changeOtherhKeFu($client_id, $message);
                    break;
                // 弹出评价.
                case 'getEvaluate';
                    $client = Gateway::getClientIdByUid($message['data']['to_id']);
                    if (!empty($client)) {
                        $chat_message = [
                            'message_type' => 'getEvaluate',
                            'data' => [
                                'content' => '欢迎你的咨询，请对我们的服务做出评价',
                            ]
                        ];
                        Gateway::sendToClient($client['0'], json_encode($chat_message, 256));
                        unset($chat_message);
                    }
            }
        }
    }

    //得到一个用户详细信息
    public static function kfgetuserinfo($clientid, $id)
    {
        $ret = self::$db->select('*')->from('ws_account')->where('id=:id')->bindValues(['id' => $id])->row();
        Gateway::sendToClient($clientid, json_encode(['message_type' => 'userdetailinfo', 'data' => $ret]));
        return;
    }


    //获取在线客服列表
    public static function getkfonlines()
    {
        $return = [
            'message_type' => 'onlinekfs',
            'data' => [],
        ];
        $nowkfid = isset($_SESSION['uid']) ? $_SESSION['uid'] : 0;
        $fromgrouupid = isset($_SESSION['group']) ? $_SESSION['group'] : 0;

        if (empty($fromgrouupid) || empty($nowkfid)) {
            return $return;
        }

        $kfs = self::$global->kfList;
        $groupnamemap = self::$global->groupmap;

        if (!$kfs || empty($groupnamemap)) {
            return $return;
        }

        $ret = [];

        foreach ($kfs as $gruop => $users) {
            foreach ($users as $uid => $uinfo) {
                if ($uid != $nowkfid && $uinfo['status'] == 1) {
                    $ret[] = ['groupid' => $gruop, 'groupname' => $groupnamemap[$gruop], 'kfuid' => $uid, 'kfname' => $uinfo['name'], 'kfjobname' => $uinfo['job_name']];
                }
            }
        }
        $return['data'] = $ret;
        return $return;
    }


    //客户工单内部组转接
    public static function changeOtherhKeFu($client_id, $smessage)
    {
        $message = $smessage['data'];

        $groupid = isset($message['fromgroup']) ? intval($message['fromgroup']) : 0;
        $groupidto = isset($message['togroup']) ? intval($message['togroup']) : 0;
        $toukfid = isset($message['toukfuid']) ? $message['toukfuid'] : 0;
        $fromkfuid = isset($message['fromkfuid']) ? $message['fromkfuid'] : 0;
        $uid = isset($message['uid']) ? $message['uid'] : 0;
        $word = isset($message['word']) ? $message['word'] : '';

        if (empty($groupid) || empty($groupidto) || empty($toukfid) || empty($fromkfuid) || empty($uid) || ($toukfid == $fromkfuid)) {
            self::DebugOut('changeOtherhKeFu exit1...');
            return false;
        }
        if (!Gateway::isUidOnline($toukfid) || !Gateway::isUidOnline($uid)) {
            self::DebugOut('changeOtherhKeFu exit2...');
            return false;
        }


        $tokfidclientid = Gateway::getClientIdByUid($toukfid);
        $tokfidclientid = $tokfidclientid['0'];
        $uidclientid = Gateway::getClientIdByUid($uid);
        $uidclientid = $uidclientid['0'];

        $kfList = $kfList_new = self::$global->kfList;
        $userToKf = $userToKf_new = self::$global->userToKf;

        if (!isset($kfList[$groupidto]) || !isset($kfList[$groupidto][$toukfid]) || !isset($kfList[$groupidto][$fromkfuid])) {
            self::DebugOut('changeOtherhKeFu exit3...');
            return false;
        }
        if ($kfList[$groupidto][$toukfid]['status'] != 1) {
            self::DebugOut('changeOtherhKeFu exit4...');
            return false;
        }


        foreach ($kfList[$groupid] as $key => $val) {
            if ($key == $fromkfuid) {
                $kfList_new[$groupid][$fromkfuid]['task']--;
                foreach ($kfList[$groupid][$key]['user_info'] as $skey => $sval) {
                    if ($sval == $uidclientid) {
                        unset($kfList_new[$groupid][$key]['user_info'][$skey]);
                    }
                }
            }
        }
        foreach ($kfList[$groupidto] as $key => $val) {
            if ($key == $toukfid) {
                $kfList_new[$groupidto][$toukfid]['task']++;
                array_push($kfList_new[$groupidto][$key]['user_info'], $uidclientid);
            }
        }

        do {
        } while (!self::$global->cas('kfList', $kfList, $kfList_new));

        if (isset($userToKf[$uid])) {
            $userToKf_new[$uid]['1'] = $toukfid;
        }
        do {
        } while (!self::$global->cas('userToKf', $userToKf, $userToKf_new));

        /////////取消原有会话，开启新会话
        $histarttimelimit = time() - 3600 * 24;
        //$bindval = ['user_id' => $uid, 'client_id' => $uidclientid, 'kf_id' => intval(trim($fromkfuid, 'KF')), 'histime' => $histarttimelimit];
        $bindval = ['user_id' => $uid, 'kf_id' => intval(trim($fromkfuid, 'KF')), 'histime' => $histarttimelimit];
        $oldlog = self::$db->select('*')->from('ws_service_log')->where('user_id= :user_id and  kf_id=:kf_id and  status!=2 and  start_time>=:histime ')->bindValues($bindval)->orderByDESC(['servicelog_id'])->row();
        if (!$oldlog) {
            self::DebugOut('changeOtherhKeFu exit5...');
            return false;
        }
        self::$db->update('ws_service_log')->cols(['status' => 2, 'end_time' => time()])->where('servicelog_id=' . $oldlog['servicelog_id'])->query();
        $tmp_old_service_logid = $oldlog['servicelog_id'];
        $oldservicelog_id = $oldlog['servicelog_id'];
        unset($oldlog['servicelog_id']);

        // 修改会话时长
        $servicelog_id = $oldservicelog_id;
        $serviceLog = self::$db->query("select `start_time`,`intime` from `ws_service_log` where `servicelog_id`= '$servicelog_id'");
        $logCount = self::$db->query("select count(*) as `count` from `ws_chat_log` where `servicelog_id`= '$servicelog_id'");
        $alarmCount = $logCount[0]['count'];
        $cvtOvertime = time() - $serviceLog[0]['start_time'];
        $alarmLineTime = $serviceLog[0]['start_time'] - $serviceLog[0]['intime'];
        self::$db->query("update `ws_alarm` set `alarm_cvtOvertime` = '$cvtOvertime',`alarm_lineTime` = '$alarmLineTime',`alarm_count` = '$alarmCount'
                          where `servicelog_id`= '$servicelog_id'");

        $oldlog = array_merge($oldlog, ['kf_id' => intval(trim($toukfid, 'KF')), 'start_time' => time(), 'end_time' => 0, 'status' => 1, 'evaluate_id' => 0]);
        $new_id = self::$db->insert('ws_service_log')->cols($oldlog)->query();
        if (!$new_id) {
            self::DebugOut('changeOtherhKeFu exit6...');
            return false;
        }

        ///通知消息发送--------------
        // 通知会员发送信息绑定客服的id
        $noticeUser = [
            'message_type' => 'connect',
            'data' => [
                'kf_id' => $toukfid,
                'conversationId' => $new_id,
                'kf_name' => Gateway::getSession(Gateway::getClientIdByUid($toukfid)['0'])['name'],
                'serverInfo' => self::$global->kfList[$groupid][$toukfid],
            ]
        ];
        Gateway::sendToClient($uidclientid, json_encode($noticeUser, 256));
        unset($noticeUser);

        // 通知客服端绑定会员的信息
        //$userinfodetail = self::getClientIndo($uid);
        $userinfoarr = ['id' => $uid, 'name' => $oldlog['user_name'], 'avatar' => $oldlog['user_avatar'], 'website' => $oldlog['website'], 'browse' => $oldlog['browse'], 'system' => $oldlog['system'], 'ip' => $oldlog['user_ip'], 'group' => $oldlog['group_id'], 'client_id' => $oldlog['client_id']];
        $noticeKf = [
            'message_type' => 'connect',
            'data' => [
                'user_info' => $userinfoarr,
                'conversationId' => $new_id,
            ]
        ];
        Gateway::sendToClient($tokfidclientid, json_encode($noticeKf, 256));
        unset($noticeKf);

        self::servicetrutoother('OUT', $fromkfuid, $toukfid, $tmp_old_service_logid, $uid);
        self::servicetrutoother('IN', $toukfid, $fromkfuid, $new_id, $uid);

        //回转接人，转接成功
        Gateway::sendToCurrentClient(json_encode(['message_type' => 'trunconnect', 'data' => ['status' => 1]], 256));

        self::DebugOut('changekf 转换成功!');

        return;
    }

    //获取某个用户全部信息
    public static function getClientIndo($id)
    {
        $ret = self::$db->from('ws_accounts')->select("*")->where(['id' => $id])->row();
        return $ret;
    }

    //客服接入sock,及初始化
    public static function Kfinit($client_id, $message)
    {
        $kfList = self::$global->kfList;

        //客服登陆验证 不符合的直接断掉
        //$logcheck = true;     //开发时使用
        $kfinfo = self::KfloginChedk($client_id, $message);
        if (empty($kfinfo)) {
            Gateway::sendToClient($client_id, json_encode(["message_type" => 'checkfalse', 'data' => "验证失败"], 256));
            Gateway::closeCurrentClient();
            return true;
        } elseif ($kfinfo['status'] != 1) {
            Gateway::sendToClient($client_id, json_encode(["message_type" => 'checkfalse', 'data' => "禁用中..."], 256));
            Gateway::closeCurrentClient();
            return true;
        }

        if (isset($kfList[$message['group']][$message['uid']])) {
            $oldcontid = $kfList[$message['group']][$message['uid']]['client_id'];
            Gateway::sendToClient($oldcontid, (json_encode(['message_type' => 'reLoginErr', 'msg' => '你的账号在其它登陆，本次下线'], 256)));
            Gateway::closeClient($oldcontid);
            sleep(3);
        }

        // 如果该客服未在内存中记录则记录
        if (!isset($kfList[$message['group']]) || !array_key_exists($message['uid'], $kfList[$message['group']])) {
            do {
                $newKfList = $kfList;
                $newKfList[$message['group']][$message['uid']] = [
                    'id' => 'KF' . $kfinfo['id'],
                    'name' => $kfinfo['user_name'],
                    'job_name' => $kfinfo['user_job_number'],
                    'avatar' => $kfinfo['user_avatar'],
                    'client_id' => $client_id,
                    'task' => 0,
                    'signature' => $kfinfo['signature'],
                    'status' => 2,// 1为在线（接收分配、接收消息）2为隐身（不接收分配、只接收消息）3、休息
                    'user_info' => []
                ];
            } while (!self::$global->cas('kfList', $kfList, $newKfList));
            unset($newKfList, $kfList);
        } else if (isset($kfList[$message['group']][$message['uid']])) {

            do {
                $newKfList = $kfList;
                $newKfList[$message['group']][$message['uid']]['client_id'] = $client_id;
            } while (!self::$global->cas('kfList', $kfList, $newKfList));
            unset($newKfList, $kfList);
        }

        // 绑定 client_id 和 uid
        Gateway::bindUid($client_id, $message['uid']);
        $_SESSION['group'] = $message['group'];
        $_SESSION['iskefu'] = 1;
        $_SESSION['uid'] = $message['uid'];
        $_SESSION['name'] = $message['name'];


        Gateway::joinGroup($client_id, 'group_' . $message['group']);

        $chat_message = [
            'message_type' => 'loginSuccess',
        ];
        Gateway::sendToClient($client_id, json_encode($chat_message, 256));
        unset($chat_message);


        self::writeLogKfStatus($message['uid'], 2);

        // TODO 尝试拉取用户来服务 [二期规划]

    }


    /**
     * 管理员
     * @param $client_id 服务ID
     * @param $message 数据
     */
    public static function adminInit($client_id, $token)
    {
        // 查询token是否存在.
        $systemConfigData = self::$db->query("SELECT `id` FROM `ws_admins` where `token`= '$token'");
        //print_r(self::$global->adminList);
        if ($systemConfigData) {
            $adminList = self::$global->adminList;
            $adminList[] = $client_id;
            self::$global->adminList = $adminList;
            self::systemMonitoring([$client_id]);
        } else {
            Gateway::closeClient($client_id);
        }
    }

    //客服登陆验证
    public static function KfloginChedk($client, $messageArray)
    {
        $uid = isset($messageArray['uid']) ? $messageArray['uid'] : '';
        $token = isset($messageArray['token']) ? $messageArray['token'] : '';
        if (empty($uid) || empty($token)) {
            return false;
        }
        $expire_time_vali = time() - 60 * 60 * 24;
        $kfid = intval(substr($uid, 2));
        $ret = self::$db->select('*')->from('ws_users')->where('id=:id and  token=:token and  expire_time>=:expire_time')->bindValues(array('id' => $kfid, 'token' => $token, 'expire_time' => $expire_time_vali))->row();

        if ($ret) {
            self::$db->update('ws_users')->cols(array('online_status' => 1, 'online_connectid' => $client))->where('id=' . $kfid)->query();
            return $ret;
        }
        return false;
    }

    //用户发送邦定用户事件
    public static function userInitEnt($client_id, $message)
    {
        $userList = self::$global->userList;
        // 如果该顾客未在内存中记录则记录

        $uidSimpleList = self::$global->uidSimpleList;
        if (isset($uidSimpleList[$message['uid']])) {
            $uidSimpleList = self::$global->uidSimpleList;
            $oldclientid = $uidSimpleList[$message['uid']]['0'];
            Gateway::sendToClient($oldclientid, json_encode(['type' => 'reLoginErr', 'msg' => '相同账号登陆，本次退出'], 256));
            Gateway::closeClient($oldclientid);
            sleep(2);
        }

        $group = $message['group'];
        $onlinekf = self::$global->kfList;
        if (!isset($onlinekf[$group]) || count($onlinekf[$group]) <= 0) {
            Gateway::sendToClient($client_id, json_encode(['message_type' => 'notice', 'content' => '暂时没有客服上班,请稍后再咨询。'], 256));
            Gateway::closeClient($client_id);
            return;
        }

        if (!array_key_exists($message['uid'], $userList)) {
            do {
                $NewUserList = $userList;
                $NewUserList[$message['uid']] = [
                    'id' => $message['uid'],
                    'name' => $message['name'],
                    'avatar' => $message['avatar'],
                    'website' => $_SESSION['origin'],//$_SERVER['HTTP_ORIGIN'],
                    'browse' => Gateway::browse_info(),
                    'system' => Gateway::get_os(),
                    'ip' => isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '',
                    'group' => $message['group'],
                    'intime' => time(),
                    'client_id' => $client_id
                ];

            } while (!self::$global->cas('userList', $userList, $NewUserList));
            unset($NewUserList, $userList);

            // 维护 UID对应的client_id 数组
            do {
                $old = $newList = self::$global->uidSimpleList;
                $newList[$message['uid']] = [
                    $client_id,
                    $message['group']
                ];

            } while (!self::$global->cas('uidSimpleList', $old, $newList));
            unset($old, $newList);

            // 写入接入值
            $key = date('Ymd') . 'total_in';
            self::$global->$key = 0;
            do {
                $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
                unset(self::$global->$oldKey);
            } while (!self::$global->increment($key));
            unset($key);
        }

        // 绑定 client_id 和 uid
        Gateway::bindUid($client_id, $message['uid']);
        $_SESSION['iskefu'] = 0;
        $_SESSION['uid'] = $message['uid'];

        // 尝试分配新会员进入服务
        self::userOnlineTask($client_id, $message['group'], $message['uid']);
    }

    /**
     * 当用户断开连接时触发
     * @param int $client_id 连接id
     *
     * tips: 当服务端主动退出的时候，会出现 exit status 9.原因是：服务端主动断开之后，连接的客户端会走这个方法，而短时间内进程
     * 需要处理这多的逻辑，又有cas操作，导致进程退出会超时，然后会被内核杀死，从而报出错误 9.实际对真正的业务没有任何的影响。
     */
    public static function onClose($client_id)
    {
        $isKefuoff = isset($_SESSION['iskefu']) ? $_SESSION['iskefu'] : 0;
        $uid = isset($_SESSION['uid']) ? $_SESSION['uid'] : false;

        echo "下线：uid: $uid  - cid: $client_id - iskf: $isKefuoff \n";

        $adminList = self::$global->adminList ?? [];
        $key = array_search($client_id, $adminList);
        if (strlen($key)) {
            array_splice($adminList, $key, 1);
            self::$global->adminList = $adminList;
        }
        if (empty($uid)) {
            return;
        }

        if ($isKefuoff) {
            self::serviceOffline($client_id, $uid);
        } else {
            self::guestOffline($client_id, $uid);
        }
        return;
    }

    //客服下线了
    public static function serviceOffline($client_id, $uid)
    {
        $group = $_SESSION['group'];
        $kefuinfo_old = $kefuinfo_old_new = self::$global->kfList;
        $user_info = $kefuinfo_old_new[$group][$uid]['user_info'];

        $simpliUsers = self::$global->uidSimpleList;
        $simpliUsersID_UID_Arr = [];
        if (!empty($simpliUsers)) {
            foreach ($simpliUsers as $cuid => $val) {
                $simpliUsersID_UID_Arr[$val['0']] = $cuid;
            }
        }

        $now = time();
        if (!empty($user_info)) {
            foreach ($user_info as $val) {
                Gateway::sendToClient($val, json_encode(['message_type' => 'serviceoffline', 'msg' => '客户人员下线!'], 256));
                if (isset($simpliUsersID_UID_Arr[$val])) {
                    // 修改会话时长
                    $serviceLog = self::$db->query("select `start_time`,`servicelog_id`,`intime` from `ws_service_log` where `user_id`= '$simpliUsersID_UID_Arr[$val]' and  kf_id='$uid' and  group_id=$group  and  `status`!=2");
                    if ($serviceLog) {
                        $servicelog_id = $serviceLog[0]['servicelog_id'];
                        $logCount = self::$db->query("select count(*) as `count` from `ws_chat_log` where `servicelog_id`= '$servicelog_id'");
                        if ($logCount) {
                            $alarmCount = $logCount[0]['count'];
                            $cvtOvertime = time() - $serviceLog[0]['start_time'];
                            $alarmLineTime = $serviceLog[0]['start_time'] - $serviceLog[0]['intime'];
                            self::$db->query("update `ws_alarm` set `alarm_cvtOvertime` = '$cvtOvertime',`alarm_lineTime` = '$alarmLineTime',`alarm_count` = '$alarmCount'
                                      where `servicelog_id`= '$servicelog_id'");
                        }
                    }
                }
                Gateway::closeClient($val);
            }
        }
        if ($uid) {
            $uiiid = intval(substr($uid, 2));
            self::$db->query("update `ws_service_log` set `status` = '2',end_time=$now,`servicelog_close_type` = 4   where  kf_id=$uiiid and  group_id=$group  and  `status`!=2 ");
        }

        unset($kefuinfo_old_new[$group][$uid]);

        $kfid = intval(substr($uid, 2));
        self::$db->update('ws_users')->cols(array('online_status' => 0, 'online_connectid' => ''))->where('id=' . $kfid)->query();

        do {
        } while (!self::$global->cas('kfList', $kefuinfo_old, $kefuinfo_old_new));

        self::writeLogKfStatus($uid, 0);

        return;
    }

    //用户下线了
    public static function guestOffline($client_id, $uid)
    {
        $kfuid = -1;
        $krclient_id = 0;
        $kfgroup = -1;
        $istalking = 1;

        $userToKf = $userToKfNew = self::$global->userToKf;
        if (isset($userToKfNew[$uid])) {
            $kfuid = isset($userToKfNew[$uid]['1']) ? $userToKfNew[$uid]['1'] : -1;
            $krclient_id = isset(Gateway::getClientIdByUid($kfuid)['0']) ? Gateway::getClientIdByUid($kfuid)['0'] : 0;

            /*用户可能意外掉线，还可以再连上来的情况下，暂不删除些关联，待公单关闭时再删除
            unset($userToKfNew[$uid]);
            do {
            } while (!self::$global->cas('userToKf', $userToKf, $userToKfNew));
            */
        }

        $uidSimpleList = $uidSimpleListNew = self::$global->uidSimpleList;
        if (isset($uidSimpleListNew[$uid])) {
            $kfgroup = $uidSimpleListNew[$uid]['1'];
            unset($uidSimpleListNew[$uid]);
            do {
            } while (!self::$global->cas('uidSimpleList', $uidSimpleList, $uidSimpleListNew));
        }

        $userList = $userListNew = self::$global->userList;
        $group_wait_count = 0;
        if (!empty($userList)) {
            $ischange = 0;
            foreach ($userList as $key => $val) {
                if ($val['group'] == $kfuid) {
                    $group_wait_count++;
                }
                if ($val['id'] == $uid) {
                    unset($userListNew[$key]);
                    $ischange = 1;
                    $group_wait_count--;
                    break;
                }
            }
            if ($ischange) {
                $istalking = 0;
                do {
                } while (!self::$global->cas('userList', $userList, $userListNew));
                Gateway::sendToGroup('group_' . $kfgroup, json_encode(['message_type' => 'kfqueuelength', 'leng' => $group_wait_count], 256));
            }
        }


        if ($kfuid != -1 && $kfgroup != -1) {
            $kefuinfo_old = $kefuinfo_old_new = self::$global->kfList;
            $ischange_kf_list = 0;
            if (isset($kefuinfo_old[$kfgroup][$kfuid])) {
                $infos = $kefuinfo_old[$kfgroup][$kfuid]['user_info'];
                if ($infos) {
                    if (is_array($infos)) {
                        foreach ($infos as $key => $val) {
                            if ($val == $client_id) {
                                $ischange_kf_list = 1;
                                unset($kefuinfo_old_new[$kfgroup][$kfuid]['user_info'][$key]);
                                $kefuinfo_old_new[$kfgroup][$kfuid]['task'] = $kefuinfo_old_new[$kfgroup][$kfuid]['task'] - 1;
                            }
                        }
                    }
                    if ($ischange_kf_list) {
                        do {
                        } while (!self::$global->cas('kfList', $kefuinfo_old, $kefuinfo_old_new));

                        $chat_message = [
                            'message_type' => 'userClose',
                            'data' => [
                                'content' => '用户连接已断开',
                                'id' => $uid,
                                'time' => date('H:i'),
                            ]
                        ];
                        $now = time();
                        $kf__uid = substr($kfuid, 2);
                        $sql = "update `ws_service_log` set `status` = '3'  where `user_id`= '$uid' and  kf_id='$kf__uid' and  group_id=$kfgroup  and  status=1 ";
                        //echo "客户退出：". $sql ."\n";
                        self::$db->query($sql);
                        Gateway::sendToClient($krclient_id, json_encode($chat_message, 256));
                    }
                }
            }
        }


    }


    /**
     * 客服结束会话
     *
     * tips: 未有$client_id的关闭
     */
    public static function closeUser($servicelog_id, $userId, $kf_id, $groupId)
    {
        $userToKf = $userToKfNew = self::$global->userToKf;
        $kfList = $userToKfNew = self::$global->kfList;
        $del_message = [
            'message_type' => 'delUser',
            'data' => [
                'id' => $userId
            ]
        ];
        Gateway::sendToClient($kfList[$groupId][$kf_id]['client_id'], json_encode($del_message, 256));
        unset($del_message);
        $now = time();
        $sql = "update `ws_service_log` set `status`='2',end_time=$now  where `servicelog_id`= '$servicelog_id'";
        self::$db->query($sql);
        // 修改会话时长
        $serviceLog = self::$db->query("select `start_time`,`intime` from `ws_service_log` where `servicelog_id`= '$servicelog_id'");
        $logCount = self::$db->query("select count(*) as `count` from `ws_chat_log` where `servicelog_id`= '$servicelog_id'");
        $alarmCount = $logCount[0]['count'];
        $cvtOvertime = time() - $serviceLog[0]['start_time'];
        $alarmLineTime = $serviceLog[0]['start_time'] - $serviceLog[0]['intime'];
        self::$db->query("update `ws_alarm` set `alarm_cvtOvertime` = '$cvtOvertime',`alarm_lineTime` = '$alarmLineTime',`alarm_count` = '$alarmCount'
                          where `servicelog_id`= '$servicelog_id'");
    }


    /**
     * 客服结束会话
     * @param int $client_id 连接id
     *
     * tips: 当服务端主动退出的时候，会出现 exit status 9.原因是：服务端主动断开之后，连接的客户端会走这个方法，而短时间内进程
     * 需要处理这多的逻辑，又有cas操作，导致进程退出会超时，然后会被内核杀死，从而报出错误 9.实际对真正的业务没有任何的影响。
     */
    public static function serverClose($client_id, $servicelog_id, $userId, $kf_id, $groupId)
    {
        // 返回.
        $chat_message = [
            'message_type' => 'closeBysever',
            'data' => [
                'content' => '客服停止了该会话',
                'time' => date('H:i'),
            ]
        ];
        Gateway::sendToClient($client_id, json_encode($chat_message, 256));
        Gateway::closeClient($client_id);
        $now = time();
        $sql = "update `ws_service_log` set `status`='2',end_time=$now  where `servicelog_id`= '$servicelog_id'";
        //echo "客户退出：". $sql ."\n";
        self::$db->query($sql);
        $isServiceUserOut = false;
        $noticeIs = 0;

        $userToKf = $userToKfNew = self::$global->userToKf;
        $kfList = $userToKfNew = self::$global->kfList;
        $del_message = [
            'message_type' => 'delUser',
            'data' => [
                'id' => $userId
            ]
        ];
        Gateway::sendToClient($kfList[$groupId][$kf_id]['client_id'], json_encode($del_message, 256));
        unset($del_message);
        // 删除关联.
        if (isset($userToKfNew[$userId])) {
            unset($userToKfNew[$userId]);
            do {
            } while (!self::$global->cas('userToKf', $userToKf, $userToKfNew));
        }

        // 修改会话时长
        $serviceLog = self::$db->query("select `start_time`,`intime` from `ws_service_log` where `servicelog_id`= '$servicelog_id'");
        $logCount = self::$db->query("select count(*) as `count` from `ws_chat_log` where `servicelog_id`= '$servicelog_id'");
        $alarmCount = $logCount[0]['count'];
        $cvtOvertime = time() - $serviceLog[0]['start_time'];
        $alarmLineTime = $serviceLog[0]['start_time'] - $serviceLog[0]['intime'];
        self::$db->query("update `ws_alarm` set `alarm_cvtOvertime` = '$cvtOvertime',`alarm_lineTime` = '$alarmLineTime',`alarm_count` = '$alarmCount'
                          where `servicelog_id`= '$servicelog_id'");
        // 将会员服务信息，从客服的服务列表中移除
        $old = $kfList = self::$global->kfList;
        foreach ($kfList as $k => $v) {
            foreach ($v as $key => $vo) {
                if (in_array($client_id, $vo['user_info'])) {

                    $isServiceUserOut = true;

                    // 根据client id 去更新会话工单一些信息
                    self::$db->query("update `ws_service_log` set `end_time` = " . time() . " , `status` = '2' where `client_id`= '" . $client_id . "'");

                    // 从会员的内存表中检索出该会员的信息，并更新内存
                    $oldSimple = $simpleList = self::$global->uidSimpleList;
                    $outUser = [];
                    foreach ($simpleList as $u => $c) {
                        if ($c['0'] == $client_id) {
                            $outUser[] = [
                                'user_id' => $u,
                                'group_id' => $c['1']
                            ];
                            unset($simpleList[$u]);
                            break;
                        }
                    }
                    while (!self::$global->cas('uidSimpleList', $oldSimple, $simpleList)) {
                    };
                    unset($oldSimple, $simpleList);


                    $outUser = self::$db->query("select `user_id`,`group_id` from `ws_service_log` where `client_id`= '" . $client_id . "'");
                    // 通知 客服删除退出的用户
                    if (!empty($outUser)) {

                        // 尝试分配新会员进入服务
                        self::userOfflineTask($outUser['0']['group_id']);
                    }
                    unset($outUser);

                    // 维护现在的该客服的服务信息
                    $kfList[$k][$key]['task'] -= 1; // 当前服务的人数 -1
                    foreach ($vo['user_info'] as $m => $l) {
                        if ($client_id == $l) {
                            unset($kfList[$k][$key]['user_info'][$m]);
                            break;
                        }
                    }

                    // 刷新内存中客服的服务列表
                    while (!self::$global->cas('kfList', $old, $kfList)) {
                    };
                    unset($old, $kfList);

                    break;
                }
            }

            if ($isServiceUserOut) break;
        }


        // 尝试从排队的用户中删除退出的客户端
        if (false == $isServiceUserOut) {
            $old = $userList = self::$global->userList;
            foreach (self::$global->userList as $key => $vo) {
                if ($client_id == $vo['client_id']) {

                    $isServiceUserOut = true;

                    unset($userList[$key]);
                    break;
                }
            }
            while (!self::$global->cas('userList', $old, $userList)) {
            };

            // 从会员的内存表中检索出该会员的信息，并更新内存
            $oldSimple = $simpleList = self::$global->uidSimpleList;
            foreach ($simpleList as $u => $c) {
                if ($c['0'] == $client_id) {
                    unset($simpleList[$u]);
                    break;
                }
            }
            while (!self::$global->cas('uidSimpleList', $oldSimple, $simpleList)) {
            };
            unset($oldSimple, $simpleList);
        }

        // 尝试是否是客服退出
        if (false == $isServiceUserOut) {
            $old = $kfList = self::$global->kfList;
            foreach (self::$global->kfList as $k => $v) {
                foreach ($v as $key => $vo) {
                    // 客服服务列表中无数据，才去删除客服内存信息
                    if ($client_id == $vo['client_id'] && (0 == count($vo['user_info']))) {
                        unset($kfList[$k][$key]);
                        break;
                    }
                }
            }

            while (!self::$global->cas('kfList', $old, $kfList)) {
            };
        }
    }


    /**
     * 有人退出
     * @param $group
     */
    private static function userOfflineTask($group)
    {
        // TODO 此处查询最大的可服务人数，后面可以用其他的方式，存储这个数值，让其更高效的访问
        $maxNumber = self::getMaxServiceNum();

        $res = self::assignmentTask(self::$global->kfList, self::$global->userList, $group, $maxNumber);
        unset($maxNumber);

        if (1 == $res['code']) {

            while (!self::$global->cas('kfList', self::$global->kfList, $res['data']['4'])) {
            }; // 更新客服数据
            while (!self::$global->cas('userList', self::$global->userList, $res['data']['5'])) {
            }; // 更新会员数据


            // 服务信息入库
            $serviceLog = [
                'user_id' => $res['data']['3']['id'],
                'client_id' => $res['data']['3']['client_id'],
                'user_name' => $res['data']['3']['name'],
                'user_ip' => $res['data']['3']['ip'],
                'user_avatar' => $res['data']['3']['avatar'],
                'kf_id' => intval(ltrim($res['data']['0'], 'KF')),
                'start_time' => time(),
                'group_id' => $group,
                'website' => $res['data']['3']['website'],
                'system' => $res['data']['3']['system'],
                'browse' => $res['data']['3']['browse'],
                'status' => 1,
                'intime' => $res['data']['3']['intime'],
                'end_time' => 0
            ];
            $hisSession = self::$db->select('*')->from('ws_service_log')->where('user_id=:user_id and kf_id=:kf_id and group_id=:group_id and status in (1,3)')->bindValues(array('user_id' => $res['data']['3']['id'], 'kf_id' => intval(ltrim($res['data']['0'], 'KF')), 'group_id' => $group))->row();
            if (!$hisSession) {
                $conversationId = self::$db->insert('ws_service_log')->cols($serviceLog)->query();
            } else {
                self::$db->update('ws_service_log')->cols(['status' => 1])->where('servicelog_id=' . $hisSession['servicelog_id'])->query();
                $conversationId = $hisSession['servicelog_id'];
            }
            unset($serviceLog);


            // 通知会员发送信息绑定客服的id
            $noticeUser = [
                'message_type' => 'connect',
                'data' => [
                    'kf_id' => $res['data']['0'],
                    'kf_name' => $res['data']['1'],
                    'conversationId' => $conversationId,
                    'serverInfo' => self::$global->kfList[$group][$res['data']['0']],
                ]
            ];
            Gateway::sendToClient($res['data']['3']['client_id'], json_encode($noticeUser, 256));
            unset($noticeUser);

            // 通知客服端绑定会员的信息
            $noticeKf = [
                'message_type' => 'connect',
                'data' => [
                    'user_info' => $res['data']['3'],
                    'conversationId' => $conversationId,
                ]
            ];
            Gateway::sendToClient($res['data']['2'], json_encode($noticeKf, 256));
            unset($noticeKf);

            // 逐一通知
            $number = 1;
            foreach (self::$global->userList as $vo) {

                $waitMsg = '您前面还有 ' . $number . ' 位会员在等待。';
                $waitMessage = [
                    'message_type' => 'wait',
                    'data' => [
                        'content' => $waitMsg,
                    ]
                ];

                Gateway::sendToClient($vo['client_id'], json_encode($waitMessage, 256));
                $number++;
            }
            unset($waitMessage, $number);

            // 写入接入值
            $key = date('Ymd') . 'success_in';
            self::$global->$key = 0;
            do {
                $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
                unset(self::$global->$oldKey);
            } while (!self::$global->increment($key));
            unset($key);

        } else {

            switch ($res['code']) {

                case -1:
                    $waitMsg = '暂时没有客服上班,请稍后再咨询。';
                    // 逐一通知
                    foreach (self::$global->userList as $vo) {

                        $waitMessage = [
                            'message_type' => 'wait',
                            'data' => [
                                'content' => $waitMsg,
                            ]
                        ];
                        Gateway::sendToClient($vo['client_id'], json_encode($waitMessage, 256));
                    }
                    break;
                case -2:
                    $waitMsg = '暂时没有客服上班,请稍后再咨询。';
                    // 逐一通知
                    foreach (self::$global->userList as $vo) {

                        $waitMessage = [
                            'message_type' => 'wait',
                            'data' => [
                                'content' => $waitMsg,
                            ]
                        ];
                        Gateway::sendToClient($vo['client_id'], json_encode($waitMessage, 256));
                    }
                    break;
                case -3:
                    $waitMsg = '暂时没有客服上班,请稍后再咨询。';
                    // 逐一通知
                    foreach (self::$global->userList as $vo) {

                        $waitMessage = [
                            'message_type' => 'wait',
                            'data' => [
                                'content' => $waitMsg,
                            ]
                        ];
                        Gateway::sendToClient($vo['client_id'], json_encode($waitMessage, 256));
                    }
                    break;
                case -4:
                    // 逐一通知
                    $number = 1;
                    foreach (self::$global->userList as $vo) {

                        $waitMsg = '您前面还有 ' . $number . ' 位会员在等待。';
                        $waitMessage = [
                            'message_type' => 'wait',
                            'data' => [
                                'content' => $waitMsg,
                            ]
                        ];

                        Gateway::sendToClient($vo['client_id'], json_encode($waitMessage, 256));
                        $number++;
                    }
                    break;
            }
            unset($waitMessage, $number);
        }
    }

    /**
     * 有人进入执行分配
     * @param $client_id
     * @param $group
     * @param $uid
     */
    private static function userOnlineTask($client_id, $group, $uid = 0)
    {
        // TODO 此处查询最大的可服务人数，后面可以用其他的方式，存储这个数值，让其更高效的访问
        $maxNumber = self::getMaxServiceNum();

        $res = self::assignmentTask(self::$global->kfList, self::$global->userList, $group, $maxNumber, $uid);
        unset($maxNumber);

        if (1 == $res['code']) {

            while (!self::$global->cas('kfList', self::$global->kfList, $res['data']['4'])) {
            }; // 更新客服数据
            while (!self::$global->cas('userList', self::$global->userList, $res['data']['5'])) {
            }; // 更新会员数据
            $userToKf = self::$global->userToKf;
            $userToKf[$res['data']['3']['id']] = [
                $res['data']['3']['id'],
                $res['data']['0']
            ];
            self::$global->userToKf = $userToKf;

            // 服务信息入库
            $serviceLog = [
                'user_id' => $res['data']['3']['id'],
                'client_id' => $res['data']['3']['client_id'],
                'user_name' => $res['data']['3']['name'],
                'user_ip' => $res['data']['3']['ip'],
                'user_avatar' => $res['data']['3']['avatar'],
                'kf_id' => intval(ltrim($res['data']['0'], 'KF')),
                'start_time' => time(),
                'group_id' => $group,
                'website' => $res['data']['3']['website'],
                'system' => $res['data']['3']['system'],
                'browse' => $res['data']['3']['browse'],
                'status' => 1,
                'intime' => $res['data']['3']['intime'],
                'end_time' => 0
            ];
            $hisSession = self::$db->select('*')->from('ws_service_log')->where('user_id=:user_id and kf_id=:kf_id and group_id=:group_id and status in (1,3)')->bindValues(array('user_id' => $res['data']['3']['id'], 'kf_id' => intval(ltrim($res['data']['0'], 'KF')), 'group_id' => $group))->row();
            if (!$hisSession) {
                $conversationId = self::$db->insert('ws_service_log')->cols($serviceLog)->query();
                $alarmData = [
                    'servicelog_id' => $conversationId,
                ];
                self::$db->insert('ws_alarm')->cols($alarmData)->query();
            } else {
                self::$db->update('ws_service_log')->cols(['status' => 1])->where('servicelog_id=' . $hisSession['servicelog_id'])->query();
                $conversationId = $hisSession['servicelog_id'];
            }
            unset($serviceLog);


            // 通知会员发送信息绑定客服的id
            $noticeUser = [
                'message_type' => 'connect',
                'data' => [
                    'kf_id' => $res['data']['0'],
                    'conversationId' => $conversationId,
                    'serverInfo' => self::$global->kfList[$group][$res['data']['0']],
                    'kf_name' => $res['data']['1']
                ]
            ];
            Gateway::sendToClient($client_id, json_encode($noticeUser, 256));
            unset($noticeUser);


            // 发送客服欢迎语
            $sayHello = self::$db->query('select `word`,`status` from `ws_reply` where `id` = 2');
            if (!empty($sayHello) && 1 == $sayHello['0']['status']) {
                $chat_message = [
                    'message_type' => 'chatMessage',
                    'data' => [
                        'name' => $res['data']['1'],
                        //'avatar' => self::$global->kfList[$group][$res['data']['0']],
                        'id' => $res['data']['0'],
                        'time' => date('H:i'),
                        'content' => $sayHello['0']['word']
                    ]
                ];
                Gateway::sendToClient($client_id, json_encode($chat_message, 256));
                unset($chat_message);
            }
            unset($sayHello);

            // 通知客服端绑定会员的信息
            $noticeKf = [
                'message_type' => 'connect',
                'data' => [
                    'user_info' => $res['data']['3'],
                    'conversationId' => $conversationId,
                ]
            ];
            Gateway::sendToClient($res['data']['2'], json_encode($noticeKf, 256));
            unset($noticeKf);

            // 写入接入值
            $key = date('Ymd') . 'success_in';
            self::$global->$key = 0;
            do {
                $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
                unset(self::$global->$oldKey);
            } while (!self::$global->increment($key));
            unset($key);

        } else {

            $waitMsg = '';
            switch ($res['code']) {

                case -1:
                    $waitMsg = '暂时没有客服上班,请稍后再咨询。';
                    Gateway::sendToClient($client_id, json_encode(['message_type' => "notice", 'content' => $waitMsg], 256));
                    Gateway::closeClient($client_id);
                    return;
                    break;
                case -2:
                    break;
                case -3:
                    break;
                case -4:
                    $number = count(self::$global->userList);
                    $waitMsg = '您前面还有 ' . $number . ' 位会员在等待。';
                    break;
            }

            $waitMessage = [
                'message_type' => 'wait',
                'data' => [
                    'content' => $waitMsg,
                ]
            ];

            Gateway::sendToClient($client_id, json_encode($waitMessage, 256));
            unset($waitMessage);
        }

        $userlist = self::$global->userList;
        $waitcount = 0;
        if ($userlist) {
            foreach ($userlist as $val) {
                if ($val['group'] == $group) {
                    $waitcount++;
                }
            }
            Gateway::sendToGroup('group_' . $group, json_encode(['message_type' => 'kfqueuelength', 'leng' => $waitcount], 256));
            self::todayqueuelength();
        }

    }

    //今天排序累加
    private static function todayqueuelength()
    {
        $dtype = 'user.queue.day.length';
        $today = date("Y-m-d");

        $sret = self::$db->select('*')->from('ws_countmidtable')->where('dtype=:dtype and  mdate=:mdate')->bindValues(array('dtype' => $dtype, 'mdate' => $today))->row();
        if ($sret) {
            self::$db->update('ws_countmidtable')->cols(array('dcontent' => intval($sret['dcontent']) + 1))->where('id=' . $sret['id'])->query();
        } else {
            self::$db->insert('ws_countmidtable')->cols(array(
                'dtype' => $dtype,
                'mdate' => $today,
                'datatype' => 1,
                'dcontent' => 1))->query();
        }
    }

    //客服工单转单
    private static function servicetrutoother($type, $owen, $otherkfid, $serverid, $clientuid)
    {
        $owen = intval(substr($owen, 2));
        $otherkfid = intval(substr($otherkfid, 2));

        self::$db->insert('ws_serviceturn_log')->cols(array(
            'stype' => $type,
            'uid' => $owen,
            'tuid' => $otherkfid,
            'serverid' => $serverid,
            'guestuid' => $clientuid
        ))->query();
    }


    /**
     * 给客服分配会员【均分策略】
     * @param $kfList
     * @param $userList
     * @param $group
     * @param $total
     */
    private static function assignmentTask($kfList, $userList, $group, $total, $uid = 0)
    {
        // 注：修改为已上线（status为1上线status为2不接受分配）
        $onlineKF = [];
        foreach ($kfList as $k => $v) {
            foreach ($v as $ke => $va) {
                if ($va['status'] == 1) {
                    $onlineKF[$k][$ke] = $va;
                }
            }
        }
        // 没有客服上线
        if (empty($onlineKF) || empty($onlineKF[$group])) {
            return ['code' => -1];
        }

        // 没有待分配的会员
        if (empty($userList)) {
            return ['code' => -2];
        }

        // 未设置每个客服可以服务多少人
        if (0 == $total) {
            return ['code' => -3];
        }

        // 查看该组的客服是否在线
        if (!isset($onlineKF[$group])) {
            return ['code' => -1];
        }

        //上次用户掉线后，还可以继续上一次 (如果没有关闭) 的会话  --1
        $odltalksession = false;
        $user = $user_first = array_shift($userList);
        if ($uid > 0 && $user['id'] != $uid && count($userList) > 1) {
            $timevalielimit = time() - 60 * 5;
            $odltalksession = self::$db->select('*')->from('ws_service_log')->where('user_id=:uid and  `group`=:group and  `status`=3 and  end_time>=:timevalielimit"')->bindValues(array('uid' => $uid, 'group' => $group, 'timevalielimit' => $timevalielimit))->row();
            if ($odltalksession) {
                foreach ($userList as $ttkey => $ttval) {
                    if ($ttval['id'] == $uid) {
                        array_unshift($userList, $user);
                        $user = $userList[$ttkey];
                        unset($userList[$ttkey]);
                        break;
                    }
                }
            }
        }


        //上次用户掉线后，还可以继续上一次 (如果没有关闭) 的会话  --2
        if ($odltalksession) {
            $oldkrid = 'KF' . $odltalksession['kf_id'];
            if (isset($onlineKF[$group][$oldkrid])) {
                $kf = $onlineKF[$group][$oldkrid];
                $min = $kf['task'];
                $flag = $kf['id'];
                unset($onlineKF[$group][$oldkrid]);
            } else {
                goto NOSIGNKF;
            }
        } else {
            NOSIGNKF:
            $kf = $onlineKF[$group];
            $kf = array_shift($kf);
            $min = $kf['task'];
            $flag = $kf['id'];

            foreach ($onlineKF[$group] as $key => $vo) {
                if ($vo['task'] < $min) {
                    $min = $vo['task'];
                    $flag = $key;
                }
            }
            unset($kf);
        }

        // 需要排队了
        if ($onlineKF[$group][$flag]['task'] == $total) {
            array_unshift($userList, $user);
            return ['code' => -4];
        }

        $kfList[$group][$flag]['task'] += 1;
        array_push($kfList[$group][$flag]['user_info'], $user['client_id']); // 被分配的用户信息

        return [
            'code' => 1,
            'data' => [
                $onlineKF[$group][$flag]['id'],
                $onlineKF[$group][$flag]['name'],
                $onlineKF[$group][$flag]['client_id'],
                $user,
                $kfList,
                $userList
            ]
        ];
    }

    /**
     * 获取最大的服务人数
     * @return int
     */
    private static function getMaxServiceNum()
    {
        $maxNumber = self::$db->query('select `max_service` from `ws_kf_config` where `id` = 1');
        if (!empty($maxNumber)) {
            $maxNumber = 5;
        } else {
            $maxNumber = $maxNumber['0']['max_service'];
        }

        return $maxNumber;
    }

    /**
     * 将内存中的数据写入统计表
     * @param int $flag
     */
    private static function writeLog($flag = 1)
    {
        // 上午 8点 到 22 点开始统计
        if (date('H') < 8 || date('H') > 22) {
            return;
        }

        // 当前正在接入的人 和 在线客服数
        $kfList = self::$global->kfList;

        $nowTalking = 0;
        $onlineKf = 0;
        if (!empty($kfList)) {

            foreach ($kfList as $key => $vo) {

                $onlineKf += count($vo);
                foreach ($vo as $k => $v) {
                    $nowTalking += count($v['user_info']);
                }
            }
        }

        // 在队列中的用户
        $inQueue = count(self::$global->userList);

        $key = date('Ymd') . 'total_in';
        $key2 = date('Ymd') . 'success_in';
        $param = [
            'is_talking' => $nowTalking,
            'in_queue' => $inQueue,
            'online_kf' => $onlineKf,
            'success_in' => self::$global->$key2,
            'total_in' => self::$global->$key,
            'now_date' => date('Y-m-d')
        ];
        self::$db->update('ws_now_data')->cols($param)->where('id=1')->query();

        if (2 == $flag) {
            $param = [
                'is_talking' => $nowTalking,
                'in_queue' => $inQueue,
                'online_kf' => $onlineKf,
                'success_in' => self::$global->$key2,
                'total_in' => self::$global->$key,
                'add_date' => date('Y-m-d'),
                'add_hour' => date('H'),
                'add_minute' => date('i'),
            ];
            self::$db->insert('ws_service_data')->cols($param)->query();
        }
        unset($kfList, $nowTalking, $inQueue, $onlineKf, $key, $key2, $param);
    }

    /**
     * 机器人问答
     * @param $client_id 服务ID
     * @param $message 数据
     */
    private static function toRobot($client_id, $message)
    {
        $groups_id = $message['data']['groups_id'];
        $robot_name = $message['data']['robot_name'];
        $robotgroups_id = $message['data']['robotgroups_id'];
        // 查询问题.
        $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 . "'");
        $chat_message = [
            'message_type' => 'robotMessage',
            //'message_type' => 'chatMessage',
            'data' => [
                'name' => '智能助手',
                'time' => date('H:i'),
                'content' => $getRobot ? $getRobot[0]['robot_content'] : 'error',
            ]
        ];
        sleep(1);
        Gateway::sendToClient($client_id, json_encode($chat_message, 256));
    }

    /**
     * 评价
     * @param $client_id 服务ID
     * @param $message 数据
     */
    private static function evaluate($client_id, $message)
    {
        // 修改数据库.
        $evaluate_id = $message['data']['evaluate_id'];
        $result = self::$db->query("UPDATE `ws_service_log` SET `evaluate_id` = '" . $evaluate_id . "' WHERE `client_id`='" . $client_id . "'");
        if ($result) {
            $chat_message = [
                'message_type' => 'evaluate',
                'data' => [
                    'status' => 1,
                    'time' => date('H:i'),
                ]
            ];
        } else {
            $chat_message = [
                'message_type' => 'evaluate',
                'data' => [
                    'status' => 2,
                    'time' => date('H:i'),
                ]
            ];
        }
        Gateway::sendToClient($client_id, json_encode($chat_message, 256));
    }


    //获取系统配置
    private static function upsystemconfig()
    {
        $systemConfigData = self::$db->query("SELECT *  FROM `ws_systemconfig`");
        $arr = [];
        if ($systemConfigData) {
            foreach ($systemConfigData as $item) {
                $arr[$item['systemconfig_enName']] = $item;
            }
            self::$global->systemconfig = $arr;
        }

        $group = self::$db->query("SELECT *  FROM `ws_groups`");
        $arr = [];
        if ($group) {
            foreach ($group as $val) {
                $arr[$val['id']] = $val['name'];
            }
            self::$global->groupmap = $arr;
        }

    }

    /**
     * 超时
     * @param $client_id 服务ID
     * @param $message 数据
     */
    private static function overTime()
    {
        // 查询对话时效设置.
        $systemConfigData = self::$db->query("SELECT `systemconfig_data`,`systemconfig_enName`,`systemconfig_content` FROM `ws_systemconfig`");
        foreach ($systemConfigData as $k => $v) {
            if ($v['systemconfig_enName'] == 'overtime') {
                self::$global->overtime = $v;
            } elseif ($v['systemconfig_enName'] == 'unoperated') {
                self::$global->unoperated = $v;
            } elseif ($v['systemconfig_enName'] == 'noResponse') {
                self::$global->noResponse = $v;
            }
        }
        // 查询未断开的工单.
        $serviceLog = self::$db->query("SELECT `servicelog_id`,`client_id`,`start_time`,`user_id`,`kf_id`,`group_id` FROM `ws_service_log` WHERE `status`='1' OR `status`='3'");
        $whereOr = '1=0';
        foreach ($serviceLog as $k => $v) {
            if ($k == 0) {
                $whereOr = "`servicelog_id`=" . $v['servicelog_id'];
            } else {
                $whereOr .= " OR `servicelog_id`=" . $v['servicelog_id'];
            }
        }
        // 查询最后一次会话.
        //$chatLog = self::$db->query("SELECT `servicelog_id`,MAX(`time_line`) FROM `ws_chat_log` WHERE ".$whereOr." group by `servicelog_id`");
        $chatLog = self::$db->query("
                select * from ws_chat_log as a where  time_line=(
                  select max(b.time_line) from ws_chat_log as b where a.servicelog_id = b.servicelog_id and from_id not like 'KF%' and (" . $whereOr . ") group by servicelog_id
                )
            ");
        $setOvertime = strtotime('-' . (self::$global->overtime['systemconfig_data'] - 60) . ' second');
        $overtime = strtotime('-' . (self::$global->overtime['systemconfig_data']) . ' second');
        $setUnoperated = strtotime('-' . (self::$global->unoperated['systemconfig_data'] - 60) . ' second');
        $unoperated = strtotime('-' . (self::$global->unoperated['systemconfig_data']) . ' second');
        $noResponse = strtotime('-' . (self::$global->noResponse['systemconfig_data']) . ' second');
        foreach ($serviceLog as $k => $v) {
            // 会话超时关闭.
            /*if ($v['start_time'] <= $overtime) {
                $servicelog_id = $v['servicelog_id'];
                self::$db->query("update `ws_service_log` set `servicelog_close_type` = 2 where `servicelog_id`= '$servicelog_id'");
                self::serverClose($v['client_id'], $servicelog_id, $v['user_id'], 'KF'.$v['kf_id'], $v['group_id']);
                // 如果小于设定时间前一分钟则给出提示.
            } elseif ($v['start_time'] <= $setOvertime) {
                $chat_message = [
                    'message_type' => 'overtime',
                    'data' => [
                        'content' => self::$global->overtime['systemconfig_content'],
                    ]
                ];
                Gateway::sendToClient($v['client_id'], json_encode($chat_message, 256));
            }*/
            // 无效会话关闭.如果没有说一句话.
            if (!strlen(array_search($v['servicelog_id'], array_column($chatLog, 'servicelog_id')))) {
                if ($v['start_time'] <= $unoperated) {
                    $servicelog_id = $v['servicelog_id'];
                    self::$db->query("update `ws_service_log` set `servicelog_close_type` = 1 where `servicelog_id`= '$servicelog_id'");
                    self::serverClose($v['client_id'], $servicelog_id, $v['user_id'], 'KF' . $v['kf_id'], $v['group_id']);
                    // 如果小于设定时间前一分钟则给出提示.
                } elseif ($v['start_time'] <= $setUnoperated) {
                    $chat_message = [
                        'message_type' => 'overtime',
                        'data' => [
                            'content' => self::$global->unoperated['systemconfig_content'],
                        ]
                    ];
                    Gateway::sendToClient($v['client_id'], json_encode($chat_message, 256));
                }
            }
        }
        // 双方静默超时.
        foreach ($chatLog as $k => $v) {
            // 如果对话为客服的最后一次对话且时间小于设定时间则结束工单.
            if ($v['time_line'] <= $overtime) {
                $found_key = array_search($v['servicelog_id'], array_column($serviceLog, 'servicelog_id'));
                $servicelog_id = $v['servicelog_id'];
                self::$db->query("update `ws_service_log` set `servicelog_close_type` = 2 where `servicelog_id`= '$servicelog_id'");
                self::serverClose($serviceLog[$found_key]['client_id'], $servicelog_id, $serviceLog[$found_key]['user_id'], 'KF' . $serviceLog[$found_key]['kf_id'], $serviceLog[$found_key]['group_id']);
                // 如果对话为客服的最后一次对话且时间小于设定时间前一分钟则给出提示.
            } elseif ($v['time_line'] <= $setOvertime) {
                $chat_message = [
                    'message_type' => 'overtime',
                    'data' => [
                        'content' => self::$global->overtime['systemconfig_content'],
                    ]
                ];
                $found_key = array_search($v['servicelog_id'], array_column($serviceLog, 'servicelog_id'));
                Gateway::sendToClient($serviceLog[$found_key]['client_id'], json_encode($chat_message, 256));
            }
        }
    }

    /**
     * 系统监控
     * @param $message 数据
     */
    private static function systemMonitoring($adminList)
    {
        // 查询未结束工单.
        $serviceLog = self::$db->query("select ws_service_log.servicelog_id,ws_users.user_name as server_name,ws_service_log.user_name,kf_id,start_time,end_time,ws_service_log.group_id,evaluate_id,intime,ws_service_log.status,alarm_userSensitive,alarm_serverSensitive,alarm_corresponding
          from `ws_service_log` 
          join `ws_alarm` on ws_service_log.servicelog_id=ws_alarm.servicelog_id
          join `ws_users` on ws_service_log.kf_id=ws_users.id 
          WHERE ws_service_log.status='1' OR ws_service_log.status='3'");
        // 查询系统设置表.
        $systemconfig = self::$db->query("SELECT `systemconfig_data`,`systemconfig_enName` FROM `ws_systemconfig` WHERE `systemconfig_enName`='verifyReturnTime' or `systemconfig_enName`='verifyAllTime'");
        $returnTimeKey = array_search('verifyReturnTime', array_column($systemconfig, 'systemconfig_enName'));
        // 质检会话响应时长.
        $verifyReturnTime = $systemconfig[$returnTimeKey]['systemconfig_data'];
        $allTimeKey = array_search('verifyAllTime', array_column($systemconfig, 'systemconfig_enName'));
        // 质检会话时长.
        $verifyAllTime = $systemconfig[$allTimeKey]['systemconfig_data'];
        // 差评次数.
        $evaluateCount = 0;
        // 未结束工单id.
        $servicelog_ids = '';
        $overtimeNumber = 0; // 会话超时次数.
        $overtimeTime = []; // 会话超时时间.
        $userSensitive = 0; // 用户敏感词报警次数.
        $serverSensitive = 0; // 客服敏感词报警次数.
        $csdNumber = 0; // 响应超时次数.
        $csdTime = []; // 响应超时时间.
        foreach ($serviceLog as $k => $v) {
            // 工单报警总次数.
            $allCount = 0;
            // 差评次数.
            if ($v['evaluate_id'] == 3) {
                $evaluateCount++;
                $allCount++;
            }
            $duration = time() - $v['start_time'];
            // 会话超时.
            if ($duration > $verifyAllTime) {
                $overtimeNumber++;
                $allCount++;
                $overtimeTime[] = $duration;
            }
            // 敏感词报警.
            $userSensitive += $v['alarm_userSensitive'];
            $allCount += $v['alarm_userSensitive'];
            $serverSensitive += $v['alarm_serverSensitive'];
            $allCount += $v['alarm_serverSensitive'];
            // 响应超时.
            if ($v['alarm_corresponding'] > $verifyReturnTime) {
                $csdTime[] = $v['alarm_corresponding'];
                $csdNumber++;
                $allCount++;
            }
            $serviceLog[$k]['allCount'] = $allCount;
        }

        self::DebugOut([$serviceLog, $csdTime, $verifyReturnTime], 'systemMonitoring');

        // 查询对话时效设置.
        foreach ($adminList as $v) {
            $chat_message = [
                'message_type' => 'monitor',
                'data' => [
                    'cvtList' => $serviceLog,
                    'userSensitive' => $userSensitive,
                    'serverSensitive' => $serverSensitive,
                    'csdNumber' => $csdNumber,
                    'csdTime' => $csdTime,
                    'overtimeNumber' => $overtimeNumber,
                    'overtimeTime' => $overtimeTime,
                    'evaluateCount' => $evaluateCount,
                ]
            ];
            Gateway::sendToClient($v, json_encode($chat_message, 256));
        }
    }


    //客服在线状态写组
    private static function writeLogKfStatus($kf, $status, $flag = 1)
    {
        if ($flag == 1) {
            $status = intval($status);
            if ($status == 0) {
                self::$db->delete('ws_kfonline')->where("uid='$kf'")->query();
            } else {
                $now = date('Y-m-d H:i;s');
                $ip = isset($_SESSION['remotip']) ? $_SESSION['remotip'] : '';
                $sql = "insert into ws_kfonline(uid,status,uptime,ip) values('$kf',$status,'$now','$ip') ON DUPLICATE KEY UPDATE status=$status,uptime='$now' ";
                self::$db->query($sql);
            }
        } else {
            self::$db->query("delete from ws_kfonline ");
        }
    }


    public static function resetServiceLog($kfid = 0)
    {
        $t = time() - 24 * 3600;

        if ($kfid) {
            if ((substr($kfid, 0, 2) == 'KF')) {
                $kfid = intval(substr($kfid, 2));
            }
            $kfid = intval($kfid);
            self::$db->query("update ws_service_log set status=2 where kf_id=$kfid and  start_time>=$t and  status!=2");
        } else {
            self::$db->query("update ws_service_log set status=2 where  start_time>=$t and  status!=2");
        }

    }

    public static function onWorkerStop($businessWorker)
    {
        if ($businessWorker->worker_id == 1) {
            self::resetServiceLog();
        }
    }


    //用户下线通知
    private static function userCloseNotice($client_id, $cuid, $group)
    {


    }

    //踢掉同一用户的旧用户
    private static function tickOlduser($uid)
    {

    }

    private static function DebugOut($msg, $title = '', $type = 'info')
    {
        $config = self::$global->systemconfig;
        if (!isset($config['isdebug']) || empty($config['isdebug']['systemconfig_data'])) {
            return;
        }
        if (!is_string($msg)) {
            $msg = json_encode([$msg], 256);
        }
        $msg = date("Y-m-d H:i:s") . ' - ' . $type . ' - ' . $title . ' - ' . $msg . "\n";
        echo $msg;
    }


}
