<?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;
use Workerman\Worker;


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

    const  KFSERVICES = 'KFSERVICES';          //KFSERVICES:KF10 1213131=>22这样的 客服工单hash表 健为连接号,值为工单号
    const  KFINFOKEY = 'KFINFO';              //客服信息hash表
    const  USERINFOKEY = 'USERINFO';          //用户信息hash表
    const  USERLIST = 'USERLIST';             //用户排队表
    const  SERVICELOG = 'SERVICELOG';            //工单信息
    const  WEBSOCKALLUSER = 'WEBSOCKALLUSER';          //所有连接
    const  KFRELONINFLAG = 'KFRELOGIN';                 //客服重登陆标示

    /**
     * 进程启动后初始化数据库连接
     */
    public static function onWorkerStart($worker)
    {
        include_once(__DIR__ . DIRECTORY_SEPARATOR . "Mlogic.php");
        self::$logic = Mlogic::GetInstance();
        self::$db = self::$logic->getDb();
        self::$redis = self::$logic->getRedis();
        self::$global = self::$logic->getGlbData();

        self::TimerThing($worker);
    }

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

    public static function lineup()
    {
        $group = self::$global->groupmap;

        foreach ($group as $groupid => $gname) {
            $users = self::getUselistData($groupid);
            if (!empty($users)) {
                Gateway::sendToGroup('group_' . $groupid, json_encode(['type' => 'lineupCount', 'data' => ['count' => count($users)]], 256));
            }
        }
    }


    /**
     * 当客户端连接时触发
     * 如果业务不需此回调可以删除onConnect
     *
     * @param int $client_id 连接id
     */
    public static function onConnect($client_id)
    {
        // 检测是否开启自动应答
        $sayHello = self::$global->systemReplay;
        if (!empty($sayHello)) {
            foreach ($sayHello as $v) {
                $hello = [
                    'message_type' => 'helloMessage',
                    'data' => [
                        'name' => '智能助手',
                        'time' => date('H:i'),
                        'content' => $v
                    ]
                ];
                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);

        self::$redis->hset(self::WEBSOCKALLUSER, $client_id, json_encode(['time' => date('H:i:s'), 'ip' => $_SERVER['REMOTE_ADDR'] . ':' . $_SERVER['REMOTE_PORT']]));
    }

    /**
     * 当客户端发来消息时触发
     * @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");
        }

        $message = json_decode($message, true);
        if (isset($message['type'])) {
            switch ($message['type']) {
                case 'mydebug':
                    self::mydebug($client_id, $message['data']);
                    break;
                // 管理员初始化
                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':
                    self::chatMessage($message['data']);
                    break;
                // 机器人问答.
                case 'toRobot':
                    self::toRobot($client_id, $message);
                    break;
                // 评价.
                case 'evaluate':
                    self::evaluate($message['data']);
                    break;
                // 客服关闭会话.
                case 'kfCloseUser':
                    self::serverClose($message['data']['conversationId'], $message['data']['type']);
                    break;
                // 客服更改状态.
                case 'kfOnline':
                    self::KFStatusCg($client_id, $message);
                    break;
                case 'changeOtherhKeFu';
                    self::changeOtherhKeFu($client_id, $message);
                    break;
                case 'userlabeall':
                    self::getUserLabAll($client_id, $message);
                    break;
                // 弹出评价.
                case 'getEvaluate';
                    self::getEvaluate($message['data']);
                    break;
                case 'debug':
                    self::debug($message['data']);
                    break;
                case 'cancelqueue':
                    self::cancelqueue($message['data']);
                    break;
            }
        }
        return true;
    }

    //用户取消排队
    public function cancelqueue($messageArray)
    {
        $uid = intval($messageArray['uid']);
        if (empty($uid)) {
            return false;
        }
        $sessionuid = intval($_SESSION['uid']);
        if ($sessionuid != $uid) {
            return false;
        }
        $listu = self::$redis->hget(self::USERLIST, $uid);
        if ($listu) {
            self::$redis->hdel(self::USERLIST, $uid);
            self::$redis->hdel(self::USERINFOKEY, $uid);
            Gateway::sendToCurrentClient(json_encode(['message_type' => 'cancelqueueret', 'data' => ['flag' => 1, 'msg' => '取消排队成功!']], 256));
            return;
        } else {
            Gateway::sendToCurrentClient(json_encode(['message_type' => 'cancelqueueret', 'data' => ['flag' => 0, 'msg' => '取消排队失败!']], 256));
        }
        return;
    }

    // 弹出评价.
    public static function getEvaluate($message)
    {
        // 获取当前会话工单.
        $data = json_decode(self::$redis->HGET('SERVICELOG', $message['conversationId']), true);
        if (empty($data)) {
            return;
        }
        $chat_message = [
            'message_type' => 'getEvaluate',
            'data' => [
                'content' => '欢迎你的咨询，请对我们的服务做出评价',
            ]
        ];
        Gateway::sendToClient($data['client_id'], json_encode($chat_message, 256));
    }

    //客服聊天
    public static function chatMessage($message)
    {
        // 获取当前会话工单.
        $data = json_decode(self::$redis->HGET('SERVICELOG', $message['conversationId']), true);
        if (empty($data)) {
            return;
        }
        if (!Gateway::isOnline($data['kf_client_id'])) {
            $errorMessage = [
                'message_type' => 'kfNotOnlin',
                'data' => [
                    'error' => '客服不在线，可能无法及时应答',
                ]
            ];
            Gateway::sendToClient($data['client_id'], json_encode($errorMessage, 256));
        }
        $chat_message = [
            'message_type' => 'chatMessage',
            'data' => [
                'name' => $message['from_name'],
                'id' => $message['from_id'],
                'time' => date('H:i'),
                'content' => $message['content'],
            ]
        ];
        // 是否为第一次回复.
        if (isset($message['isFirst']) && $message['isFirst']) {
            $data['alarm_corresponding'] = time() - $data['start_time'];
            $data['alarm_respond'] = 2;
        }
        // 发送消息.
        if (substr($message['from_id'], 0, 2) === 'KF') {
            // 统计敏感词.
            $data['alarm_serverSensitive'] += (isset($message['sensitiveNumber']) ? intval($message['sensitiveNumber']) : 0);
            $data['serverLastTime'] = time();
            Gateway::sendToClient($data['client_id'], json_encode($chat_message, 256));
        } else {
            // 统计敏感词.
            $data['alarm_userSensitive'] += (isset($message['sensitiveNumber']) ? intval($message['sensitiveNumber']) : 0);
            $data['userLastTime'] = time();
            Gateway::sendToClient($data['kf_client_id'], json_encode($chat_message, 256));
        }
        // 返回当前时间
        $chat_message = [
            'message_type' => 'webTime',
            'data' => [
                'webTime' => date('H:i'),
            ]
        ];
        Gateway::sendToCurrentClient(json_encode($chat_message, 256));
        // 保存修改后的工单信息.
        self::$redis->HSET('SERVICELOG', $message['conversationId'], json_encode($data, 256));

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

    //得到一个用户详细信息
    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;
        }

        $online = self::getOnlineKfData(0, 1);

        if (empty($online)) {
            return $return;
        }

        $groupnamemap = self::$global->groupmap;
        $ret = [];

        foreach ($online as $uinfo) {
            if ($nowkfid == $uinfo['id']) {
                continue;
            }
            $ret[] = ['groupid' => $uinfo['group'], 'groupname' => $groupnamemap[$uinfo['group']], 'kfuid' => $uinfo['id'], 'kfname' => $uinfo['name'], 'kfjobname' => $uinfo['job_name']];
        }
        $return['data'] = $ret;

        return $return;
    }


    public static function KFStatusCg($client_id, $message)
    {
        if (!isset($_SESSION['iskefu']) || $_SESSION['iskefu'] != 1) {
            return;
        }

        $userId = $message['data']['uid'];
        $status = intval($message['data']['status']);
        if (!in_array($status, [1, 2, 3])) {
            return false;
        }
        $oldstatus = '';
        $kfinfo = self::$redis->hget(self::KFINFOKEY, $userId);
        if (empty($kfinfo)) {
            return false;
        }
        $kfinfo = json_decode($kfinfo, true);
        if (!$kfinfo) {
            return false;
        }
        if ($kfinfo['status'] != $status) {
            $oldstatus = $kfinfo['status'];
            $kfinfo['status'] = $status;
            self::$redis->hset(self::KFINFOKEY, $userId, json_encode($kfinfo, 256));
        }

        self::writeLogKfStatus($userId, $status);
        Gateway::sendToCurrentClient(json_encode(['message_type' => 'cgstatus', 'data' => ['new_status' => $status, 'old_status' => $oldstatus]]));

        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)
    {
        $uid = self::getPars($message, 'uid');
        $group = intval(self::getPars($message, 'group', 0));

        if (empty($uid) || empty($group) || !isset(self::$global->groupmap[$group])) {
            self::MySendMsg($client_id, json_encode(["message_type" => 'checkfalse', 'data' => "客服登陆参数错误"], 256));
            Gateway::closeCurrentClient();
            return;
        }

        $loginstate = self::$logic->userIsLogin($client_id, $uid, $group);
        if ($loginstate == 1) {
            self::MySendMsg($client_id, (json_encode(['message_type' => 'reLoginErr', 'msg' => '正在登陆中，请稍后...'], 256)));
            Gateway::closeClient($client_id);
            return;
        }

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

        if ($loginstate == 2) {
            $oldcontids = Gateway::getClientIdByUid($uid);
            Gateway::sendToClient($oldcontids['0'], (json_encode(['message_type' => 'reLoginErr', 'msg' => '你的账号在其它登陆，本次下线'], 256)));
            Gateway::closeClient($oldcontids['0']);
            sleep(1);
        }

        self::$redis->hset('loginTmp:' . $uid, 'uid', time());
        self::$redis->expire('loginTmp:' . $uid, 5);
        self::$redis->hset(self::KFRELONINFLAG, $uid, time());


        $newinfo =
            [
                'id' => 'KF' . $kfinfo['id'],
                'name' => $kfinfo['user_name'],
                'job_name' => $kfinfo['user_job_number'],
                'avatar' => $kfinfo['user_avatar'],
                'group' => $group,
                'groupname' => self::$global->groupmap[$group],
                'client_id' => $client_id,
                'task' => 0,
                'intime' => time(),
                'signature' => $kfinfo['signature'],
                'status' => 2, // 1为在线（接收分配、接收消息）2为隐身（不接收分配、只接收消息）3、休息
                'user_info' => [],  //在会话的用户cid  key为clientid ，值为工单号               ///////弃用 改为hash数据了
            ];

        self::$redis->hset(self::KFINFOKEY, $uid, json_encode($newinfo, 256));
        $_SESSION['info'] = $newinfo;

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

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

        $chat_message = [
            'message_type' => 'loginSuccess',
            'userlabels' => self::$global->accountslabel,
        ];
        self::MySendMsg($client_id, json_encode($chat_message, 256));
        unset($chat_message);
        self::KFStatusCg($client_id, ['data' => ['uid' => $uid, 'status' => 1]]);

        self::SendKFHistoryRecord($client_id, $uid);
        echo date("Y-m-d H:i:s") . ' - ' . '客服上线-' . $message['name'] . "\n";

        return;
    }


    //客服掉线后 历史聊天记录
    private static function SendKFHistoryRecord($client_id, $userId)
    {
        $flag = self::$redis->hget(self::KFRELONINFLAG, $userId);
        if (!empty($flag)) {
            self::kfonlilneRework($client_id, $userId);
            self::$redis->hdel(self::KFRELONINFLAG, $userId);
        }
        return;
    }

    //客服上线重新处理下旧的没完成的工单信息
    private static function kfonlilneRework($clientid, $kfuid)
    {
        $oldService = self::$redis->hgetall(self::getKfServiceKey($kfuid));

        if ($oldService) {
            foreach ($oldService as $tmpcie => $tmpsid) {
                $tmpserver = json_decode(self::$redis->hget(self::SERVICELOG, $tmpsid), true);
                if (!$tmpserver) {
                    continue;
                }
                $tmpserver['kf_client_id'] = $clientid;
                self::$redis->hset(self::SERVICELOG, $tmpsid, json_encode($tmpserver, 256));
                self::userOnlineTask($tmpserver['group_id'], $tmpserver['user_id'], $tmpserver, 0);
            }
        }
        return;
    }

    /**
     * 管理员登陆验证
     * @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'");
        if ($systemConfigData) {
            self::$redis->sadd('adminList', $client_id);
            self::systemMonitoring([$client_id]);
        } else {
            $chat_message = [
                'message_type' => 'tips',
                'data' => '管理员不存在'
            ];
            Gateway::sendToClient($client_id, json_encode($chat_message, 256));
            Gateway::closeClient($client_id);
        }
    }

    //客服登陆验证
    public static function KfloginCheck($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)
    {
        $uid = intval($message['uid']);
        $group = intval($message['group']);
        $userTmpInfo = self::getUserInfoCache($uid);
        if (empty($userTmpInfo)) {
            self::MySendMsg($client_id, (json_encode(['message_type' => 'reLoginErr', 'msg' => '不存在的用户....'], 256)));
            Gateway::closeCurrentClient();
            return true;
        }


        $last = self::UserHasOldTalk($uid);
        if (!isset(self::$global->groupmap[$group]) && !$last) {
            self::MySendMsg($client_id, (json_encode(['message_type' => 'reLoginErr', 'msg' => '不存在客服组....'], 256)));
            return true;
            //Gateway::closeCurrentClient();
        }

        $loginstate = self::$logic->userIsLogin($client_id, $uid, $group);
        if ($loginstate == 1) {
            self::MySendMsg($client_id, (json_encode(['message_type' => 'reLoginErr', 'msg' => '正在登陆中，请稍后...'], 256)));
            Gateway::closeCurrentClient();
            return;
        }

        $hisdata = self::$redis->hget(self::USERINFOKEY, $uid);
        if ($hisdata) {
            $hisdata = json_decode($hisdata, true);
            $oldclientid = $hisdata['client_id'];
            self::MySendMsg($oldclientid, json_encode(['type' => 'reLoginErr', 'msg' => '相同账号登陆1，本次退出'], 256));
            self::MySendMsg($client_id, json_encode(['type' => 'reLoginErr', 'msg' => '相同账号登陆2，本次退出'], 256));
            Gateway::closeClient($oldclientid);
            Gateway::closeCurrentClient();
            return;
        }

        $onlinekf = self::getOnlineKfData($group, 1);
        if (empty($onlinekf) && empty($last)) {
            Gateway::sendToClient($client_id, json_encode(['message_type' => 'notice', 'content' => '暂时没有客服上班,请稍后再咨询。'], 256));
            //Gateway::closeClient($client_id);
            return;
        }

        $groupMax = self::$global->systemconfig['maxWait'];
        $noworders = self::getUselistData($group);
        if ($noworders && count($noworders) >= intval($groupMax['systemconfig_data'])) {
            Gateway::sendToClient($client_id, json_encode(['message_type' => 'notice', 'content' => '组排队人数超过上限，请稍后在连线。'], 256));
            return;
        }


        if (!$last && self::HasInqueue($group)) {
            Gateway::sendToClient($client_id, json_encode(['message_type' => 'inqueue', 'content' => '当前咨询人数繁多，正在排队中，请耐心等待。'], 256));
        }

        self::$redis->hset('loginTmp:' . $uid, 'uid', time());
        self::$redis->expire('loginTmp:' . $uid, 5);

        $data = [
            'id' => $uid,
            'name' => $message['name'],
            'avatar' => isset($message['avatar']) ? $message['avatar'] : '',
            'website' => $_SESSION['origin'],//$message['website'],
            'browse' => Gateway::browse_info(),
            'system' => Gateway::get_os(),//$message['system'],
            'ip' => isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '',//message['ip'],
            'group' => $message['group'],
            'intime' => time(),
            'kfuid' => '',
            'serverid' => 0,
            'client_id' => $client_id
        ];
        if ($last) {
            $data['group'] = $last['group_id'];
            $data['intime'] = $last['intime'];
            $data['kfuid'] = $last['kf_id'];
            $data['serverid'] = $last['servicelog_id'];
        }
        if (!$last) {
            self::$redis->hset(self::USERLIST, $uid, json_encode($data, 256));
        }
        self::$redis->hset(self::USERINFOKEY, $uid, json_encode($data, 256));

        // 写入接入值
        $key = date('Ymd') . 'total_in';
        self::$global->increment($key);

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

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

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

        echo date("Y-m-d H:i:s") . ' - ' . "下线：uid: $uid  - cid: $client_id - iskf: $isKefuoff \n";

        $isAdmin = self::$redis->sismember('adminList', $client_id);
        if ($isAdmin) {
            self::$redis->srem('adminList', $client_id);
        }
        if (empty($uid)) {
            return true;
        }

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


    //客服掉线处理 第二版  系统调用，不能手动调用
    public static function serviceOfflineV2($client_id, $uid)
    {
        $group = $_SESSION['group'];
        $uinfo = self::$redis->hget(self::KFINFOKEY, $uid);
        self::$redis->hdel(self::KFINFOKEY, $uid);
        $uinfo = json_decode($uinfo, true);
        if (empty($uinfo) || empty($group)) {
            echo date("Y-m-d H:i:s") . ' - ' . "客服发生异常退出\n";
            return;
        }
        $user_info = self::$redis->hgetall(self::getKfServiceKey($uid));
        if (!empty($user_info)) {
            foreach ($user_info as $val => $serverid) {
                self::MySendMsg($val, json_encode(['message_type' => 'serviceoffline', 'msg' => '客服人员下线!'], 256));
            }
        }
        echo date("Y-m-d H:i:s") . ' - ' . "客服退出： " . $uid . "\n";
        self::writeLogKfStatus($uid, 0);
        return;
    }


    //客服下线了  系统调用，不能手动调用
    public static function serviceOffline($client_id, $uid)
    {
        $group = $_SESSION['group'];
        $uinfo = self::$redis->hget(self::KFINFOKEY, $uid);
        self::$redis->hdel(self::KFINFOKEY, $uid);
        $uinfo = json_decode($uinfo, true);
        if (empty($uinfo)) {
            echo date("Y-m-d H:i:s") . ' - ' . "客服发生异常退出\n";
            return;
        }
        //$user_info = $uinfo['user_info'];
        $user_info = self::$redis->hgetall(self::getKfServiceKey($uid));
        $kfid = self::getkfid($uid);
        $now = time();
        $starttime = $now - 86400 * 7;

        self::$redis->hset('loginTmp:' . $uid, 'uid', time());
        self::$redis->expire('loginTmp:' . $uid, 5);

        if (!empty($user_info)) {
            foreach ($user_info as $val => $serverid) {
                self::insertServerLog($serverid, 4);
                self::$redis->hdel(self::SERVICELOG, intval($serverid));
                self::MySendMsg($val, json_encode(['message_type' => 'serviceoffline', 'msg' => '客服人员下线!'], 256));
                Gateway::closeClient($val);
            }
        }

        $sql = "update `ws_service_log` set `status` = '2',end_time=$now,`servicelog_close_type` = 4   where  start_time>=$starttime  and kf_id=$kfid and  group_id=$group  and  `status`!=2 ";
        echo date("Y-m-d H:i:s") . ' - ' . "客服退出： " . $uid . "\n";
        self::$db->query($sql);
        self::$db->update('ws_users')->cols(array('online_status' => 0, 'online_connectid' => ''))->where('id=' . $kfid)->query();
        self::$redis->del(self::getKfServiceKey($uid));
        self::writeLogKfStatus($uid, 0);

        return true;
    }

    //用户下线了          系统调用，不能手动调用
    public static function guestOffline($client_id, $uid)
    {
        self::$redis->hset('loginTmp:' . $uid, 'uid', time());
        self::$redis->expire('loginTmp:' . $uid, 3);

        $uid = intval($uid);
        $krclient_id = 0;

        $data = self::$redis->hget(self::USERINFOKEY, $uid);
        if (empty($data)) {
            return;
        }
        $info = json_decode($data, true);
        self::$redis->hdel(self::USERLIST, $uid);
        self::$redis->hdel(self::USERINFOKEY, $uid);


        if (!empty($info['kfuid'])) {
            $kfinfo = self::$redis->hget(self::KFINFOKEY, $info['kfuid']);
            if (!empty($kfinfo)) {
                $kfinfoArr = json_decode($kfinfo, true);
                $krclient_id = $kfinfoArr['client_id'];
                /*$kfinfoArr['user_info'] = self::ArrayDataopt($kfinfoArr['user_info'], $client_id, 0);
                $kfinfoArr['task'] = count($kfinfoArr['user_info']);
                self::$redis->hset(self::KFINFOKEY, $info['kfuid'], json_encode($kfinfoArr, 256));*/
            }
        }

        $chat_message = [
            'message_type' => 'userClose',
            'data' => [
                'content' => '用户连接已断开',
                'id' => $uid,
                'time' => date('H:i'),
            ]
        ];
        $now = time();
        $serverid = intval($info['serverid']);
        if ($serverid) {
            $sql = "update `ws_service_log` set `status` = '3'  where servicelog_id=$serverid  and  `status` !=2 ";
            self::$db->query($sql);
        }
        if ($krclient_id) {
            Gateway::sendToClient($krclient_id, json_encode($chat_message, 256));
        }

        return;
    }


    /**
     * 客服结束会话
     *
     * tips: 未有$client_id的关闭
     */
    public static function closeUser($servicelog_id, $userId, $kf_id, $groupId)
    {

    }


    /**
     * 工单结束
     * @param int $client_id 连接id
     *
     * tips: 当服务端主动退出的时候，会出现 exit status 9.原因是：服务端主动断开之后，连接的客户端会走这个方法，而短时间内进程
     * 需要处理这多的逻辑，又有cas操作，导致进程退出会超时，然后会被内核杀死，从而报出错误 9.实际对真正的业务没有任何的影响。
     */
    public static function serverClose($servicelogId, $closeBy = 0)
    {
        // 获取当前工单数据.
        $data = json_decode(self::$redis->HGET('SERVICELOG', $servicelogId), true);
        if (empty($data)) {
            return;
        }
        // 获取当前客服.
        $kfInfo = json_decode(self::$redis->HGET('KFINFO', 'KF' . $data['kf_id']), true);
        // 删除当前工单.
        self::$redis->hdel('SERVICELOG', $servicelogId);
        // 当前服务客服删除当前人员.
        //$kfUserList = self::ArrayDataopt($kfInfo['user_info'], $data['client_id'], 0);
        self::$redis->hdel(self::getKfServiceKey(self::getkfuid($data['kf_id'])), $data['client_id']);
        // 删除当前人员信息.
        self::$redis->hdel('USERINFO', $data['user_id']);
        // 当前客服所接待人员.
        //$kfInfo['user_info'] = $kfUserList;
        //$kfInfo['task'] = count($kfUserList);
        // 存入客服信息.
        //self::$redis->HSET('KFINFO', 'KF' . $data['kf_id'], json_encode($kfInfo, 256));
        // 发送消息给用户.
        $chat_message = [
            'message_type' => 'closeBysever',
            'data' => [
                'content' => '会话关闭',
                'time' => date('H:i'),
            ]
        ];
        Gateway::sendToClient($data['client_id'], json_encode($chat_message, 256));
        // 关闭用户连接.
        //Gateway::closeClient($data['client_id']);
        // 发送消息给客服.
        $del_message = [
            'message_type' => 'delUser',
            'data' => [
                'id' => $data['user_id']
            ]
        ];
        Gateway::sendToClient($data['kf_client_id'], json_encode($del_message, 256));
        // 查询工单会话总数.
        $chatCount = self::$db->select('count(*) as count')->from('ws_chat_log')->where("servicelog_id=$servicelogId")->row();
        // 将数据存入数据库.
        $updateServiceLogData = [
            'status' => 2,
            'evaluate_id' => isset($data['evaluate_id']) ? $data['evaluate_id'] : 0,
            'evaluate_content' => isset($data['evaluate_content']) ? $data['evaluate_content'] : '',
            'servicelog_close_type' => $closeBy,
            'end_time' => time(),
        ];
        $updataAlarmData = [
            'alarm_userSensitive' => $data['alarm_userSensitive'],
            'alarm_serverSensitive' => $data['alarm_serverSensitive'],
            'alarm_corresponding' => $data['alarm_corresponding'],
            'alarm_cvtOvertime' => time() - $data['start_time'],
            'alarm_respond' => $data['alarm_respond'],
            'alarm_lineTime' => $data['start_time'] - $data['intime'],
            'alarm_count' => $chatCount['count'],
        ];
        self::$db->update('ws_service_log')->cols($updateServiceLogData)->where("servicelog_id=$servicelogId")->query();
        self::$db->update('ws_alarm')->cols($updataAlarmData)->where("servicelog_id=$servicelogId")->query();
    }


    /**
     * 修改工单数据库数据
     * @param int $client_id 连接id
     *
     * tips: 当服务端主动退出的时候，会出现 exit status 9.原因是：服务端主动断开之后，连接的客户端会走这个方法，而短时间内进程
     * 需要处理这多的逻辑，又有cas操作，导致进程退出会超时，然后会被内核杀死，从而报出错误 9.实际对真正的业务没有任何的影响。
     */
    public static function insertServerLog($servicelogId, $closeBy = 0)
    {
        // 获取当前工单数据.
        $data = json_decode(self::$redis->HGET('SERVICELOG', $servicelogId), true);
        if (empty($data)) {
            return;
        }
        // 查询工单会话总数.
        $chatCount = self::$db->select('count(*) as count')->from('ws_chat_log')->where("servicelog_id=$servicelogId")->row();
        // 将数据存入数据库.
        $updateServiceLogData = [
            'status' => 2,
            'evaluate_id' => isset($data['evaluate_id']) ? $data['evaluate_id'] : 0,
            'evaluate_content' => isset($data['evaluate_content']) ? $data['evaluate_content'] : '',
            'servicelog_close_type' => $closeBy,
            'end_time' => time(),
        ];
        $updataAlarmData = [
            'alarm_userSensitive' => $data['alarm_userSensitive'],
            'alarm_serverSensitive' => $data['alarm_serverSensitive'],
            'alarm_corresponding' => $data['alarm_corresponding'],
            'alarm_cvtOvertime' => time() - $data['start_time'],
            'alarm_respond' => $data['alarm_respond'],
            'alarm_lineTime' => $data['start_time'] - $data['intime'],
            'alarm_count' => $chatCount['count'],
        ];
        self::$db->update('ws_service_log')->cols($updateServiceLogData)->where("servicelog_id=$servicelogId")->query();
        self::$db->update('ws_alarm')->cols($updataAlarmData)->where("servicelog_id=$servicelogId")->query();
    }


    /**
     * 有人退出
     * @param $group
     */
    private static function userOfflineTask($group)
    {

    }

    /**
     * 有人进入执行分配
     * @param $client_id
     * @param $group
     * @param $uid
     */
    private static function userOnlineTask($group = 0, $uid = 0, $last = [], $client_id = '')
    {
        if ($group && $uid) {
            // 指定用指定组 [可能存在断线重连的情况] 如果存在旧的会话，直接连线客服和用户
            //否则按先到后到以及客服最大服务数限制

            if ($last) {
                $userInfo = json_decode(self::$redis->hget(self::USERINFOKEY, $uid), true);
                self::BeginOldTalk(self::getkfuid($last['kf_id']), $uid, $last['group_id'], $last['servicelog_id']);
                if ($client_id == $userInfo['client_id']) {
                    // 查询工单历史会话.
                    $serviceid = $last['servicelog_id'];
                    $chatLog = self::$db->query("SELECT * FROM `ws_chat_log` where `servicelog_id`= '$serviceid' order by `time_line`");
                    $toOld_message = [
                        'message_type' => 'toOld',
                        'data' => [
                            'chatLog' => $chatLog ?? [],
                            'content' => '接入至未结束的会话',
                            'serviceid' => $serviceid,
                            'uid' => $uid
                        ]
                    ];
                    Gateway::sendToCurrentClient(json_encode($toOld_message, 256));
                }
                return;
            }
        }

        $allusergkarr = self::getUserListData();
        if (empty($allusergkarr)) {
            return;
        }

        $allkfgkarr = self::getWorkKfData();

        ///做某个组的客户是否还有人服务检测，如果此组没有客服在线了，要把对应排队的人踢掉
        self::Kf_user_click($allkfgkarr, $allusergkarr);

        if (empty($allkfgkarr) && !$last) {
            return;
        }
        $maxset = intval((self::$global->systemconfig)['KFMaxServices']['systemconfig_data']);

        //系统定时调用时，无组，无用户
        foreach ($allusergkarr as $group => $gusersArr) {
            if (!isset($allkfgkarr[$group]) || count($allkfgkarr[$group]) <= 0) {
                //所属客服组无人在线
                continue;
            }
            $nowkfs = $allkfgkarr[$group];
            $count = count($nowkfs);
            $i = 0;

            foreach ($gusersArr as $user) {
                if ($nowkfs[$i]['task'] >= $maxset) {
                    break;
                }
                $nowkfs[$i]['task']++;

                self::BeginTalk($nowkfs[$i]['id'], $user['id'], $group, 0, $user);
                self::$redis->hdel(self::USERLIST, $user['id']);

                $i++;
                if ($i >= $count) {
                    $i = 0;
                }
            }
        }


        return;

    }

    //踢掉某个组没有客服的用户
    private static function Kf_user_click($kfArrays, $userLIsts)
    {
        foreach ($userLIsts as $group => $groupusers) {
            $haskf = isset($kfArrays[$group]) ? 1 : 0;
            if (!$haskf) {
                foreach ($groupusers as $user) {
                    Gateway::sendToClient($user['client_id'], json_encode(['message_type' => 'notice', 'data' => ['msg' => "没有客服人员在线，请稍后再试。"]], 256));
                    Gateway::closeClient($user['client_id']);
                }
            }
        }
        return true;
    }

    //开启一个会话
    private static function BeginTalk($kfuid, $uid, $group, $serviceid = 0, $userInfo = false, $isChangeKF = 0)
    {

        $serviceid = intval($serviceid);
        if (!$userInfo) {
            $userInfo = json_decode(self::$redis->hget(self::USERINFOKEY, $uid), true);
        }
        $kfinfo = json_decode(self::$redis->hget(self::KFINFOKEY, $kfuid), true);
        if (empty($userInfo) || empty($kfinfo)) {
            return false;
        }

        $server = [];
        $armarr = [];
        if ($serviceid) {
            $server = self::$db->select('*')->from('ws_service_log')->where("servicelog_id=$serviceid ")->row();
            if ($server) {
                $armarr = self::$db->select('*')->from('ws_alarm')->where("servicelog_id=$serviceid ")->row();
            }
        }

        if (empty($server)) {
            $array = [
                'user_id' => intval($uid),
                'client_id' => $userInfo['client_id'],
                'user_name' => $userInfo['name'],
                'user_avatar' => $userInfo['avatar'],
                'user_ip' => $userInfo['ip'],
                'kf_id' => self::getkfid($kfuid),
                'start_time' => time(),
                'group_id' => $group ? $group : $userInfo['group'],
                'website' => $userInfo['website'],
                'system' => $userInfo['system'],
                'browse' => $userInfo['browse'],
                'intime' => $userInfo['intime'],
                'status' => 1,
                'evaluate_id' => 0,
                'servicelog_close_type' => 0
            ];
            $serviceid = self::$db->insert('ws_service_log')->cols($array)->query();
            $server = array_merge(['servicelog_id' => $serviceid], $array);
            $armid = self::$db->insert('ws_alarm')->cols(['servicelog_id' => $serviceid])->query();
            $armarr = self::$db->select('*')->from('ws_alarm')->where("alarm_id=$armid")->row();
        }

        $redisData = array_merge($server, $armarr, ['kf_client_id' => $kfinfo['client_id'], 'server_name' => $kfinfo['name']]);
        self::$redis->hset(self::SERVICELOG, $serviceid, json_encode($redisData, 256));
        self::setKfTasks($kfuid, $userInfo['client_id'], 1, $serviceid);

        $userInfo['serverid'] = $serviceid;
        $userInfo['kfuid'] = $kfuid;
        self::$redis->hset(self::USERINFOKEY, $uid, json_encode($userInfo, 256));

        // 通知会员发送信息绑定客服的id

        $noticeUser = [
            'message_type' => 'connect',
            'data' => [
                'kf_id' => $kfuid,
                'conversationId' => $serviceid,
                'serverInfo' => $kfinfo,
                'kf_name' => $kfinfo['job_name']
            ]
        ];
        self::MySendMsg($userInfo['client_id'], json_encode($noticeUser, 256));

        $sayHello = (self::$global->kfReplay)[0];
        if (!empty($sayHello) && 1 == $sayHello['status'] && !$isChangeKF) {
            $chat_message = [
                'message_type' => 'chatMessage',
                'data' => [
                    'id' => self::getkfuid($kfinfo['id']),
                    'name' => $kfinfo['name'],
                    'time' => date('H:i'),
                    'content' => $sayHello['word']
                ]
            ];
            self::MySendMsg($userInfo['client_id'], json_encode($chat_message, 256));
            unset($chat_message);
        }

        $userInfo['intime'] = date("H:i", $userInfo['intime']);  ///后改为只显示小时分
        $ut_tmp = self::getUserInfoCache($uid);
        $userInfo = array_merge($userInfo,
            [
                'account_name' => $ut_tmp['account_name'],
                'nick_name' => $ut_tmp['nick_name'],
                'account_email' => $ut_tmp['account_email'],
                'account_phone' => $ut_tmp['account_phone'],
                'address' => $ut_tmp['address'],
                'remark' => $ut_tmp['remark'],
                'label' => self::$global->accountslabel[$ut_tmp['label_id']]['name']
            ]
        );
        $noticeKf = [
            'message_type' => 'connect',
            'data' => [
                'user_info' => $userInfo,
                'conversationId' => $serviceid,
                'history' => [],
            ]
        ];
        self::MySendMsg($kfinfo['client_id'], json_encode($noticeKf, 256));
        unset($noticeKf);

        $key = date('Ymd') . 'success_in';
        self::$global->increment($key);

        return;
    }

    //连接至上一个会话
    private static function BeginOldTalk($kfuid, $uid, $group, $serviceid = 0, $userInfo = false)
    {

        $serviceid = intval($serviceid);
        $userInfo = json_decode(self::$redis->hget(self::USERINFOKEY, $uid), true);
        $kfinfo = json_decode(self::$redis->hget(self::KFINFOKEY, $kfuid), true);
        if (empty($userInfo)) {
            return false;
        }
        // 获取旧工单信息.
        $data = json_decode(self::$redis->HGET('SERVICELOG', $serviceid), true);
        if (empty($data)) {
            return;
        }
        // 修改工单数据.
        $data['user_avatar'] = $userInfo['avatar'];
        $data['client_id'] = $userInfo['client_id'];
        $data['user_ip'] = $userInfo['ip'];
        $data['website'] = $userInfo['website'];
        $data['system'] = $userInfo['system'];
        $data['browse'] = $userInfo['browse'];
        $data['status'] = 1;
        $data['kf_client_id'] = $kfinfo['client_id'];
        $data['kf_id'] = self::getkfid($kfuid);

        self::$redis->hset(self::SERVICELOG, $serviceid, json_encode($data, 256));

        // 更改用户连接客服信息
        $userInfo['serverid'] = $serviceid;
        $userInfo['kfuid'] = $kfuid;
        self::$redis->hset(self::USERINFOKEY, $uid, json_encode($userInfo, 256));
        // 更改客服连接信息.
        $kfinfo = json_decode(self::$redis->hget(self::KFINFOKEY, $kfuid), true);
        $kfUsers = self::$redis->hgetall(self::getKfServiceKey($kfuid));
        foreach ($kfUsers as $key => $value) {
            if ($value == $serviceid) {
                // 删除之前的当前用户连接
                self::$redis->hdel(self::getKfServiceKey($kfuid), $key);
                break;
            }
        }
        self::$redis->hset(self::getKfServiceKey($kfuid), $userInfo['client_id'], $serviceid);

        // 通知会员发送信息绑定客服的id
        $noticeUser = [
            'message_type' => 'connect',
            'data' => [
                'kf_id' => $kfuid,
                'conversationId' => $serviceid,
                'serverInfo' => $kfinfo,
                'kf_name' => $kfinfo['job_name'],
                'evaluate_id' => isset($data['evaluate_id']) ? intval($data['evaluate_id']) : 0,
            ]
        ];
        self::MySendMsg($userInfo['client_id'], json_encode($noticeUser, 256));

        // 发送给客服用户信息.
        $userInfo['intime'] = date("H:i", $userInfo['intime']);
        $noticeKf = [
            'message_type' => 'connect',
            'data' => [
                'user_info' => $userInfo,
                'conversationId' => $serviceid,
                'history' => self::getServerChagLog($serviceid),
                'evaluate_id' => isset($data['evaluate_id']) ? intval($data['evaluate_id']) : 0,
            ]
        ];
        self::MySendMsg($kfinfo['client_id'], json_encode($noticeKf, 256));
        unset($noticeKf);

        $key = date('Ymd') . 'success_in';
        self::$global->increment($key);

        return;
    }

    //获取工单最后20条聊天记录
    private static function getServerChagLog($sericeId, $limit = 20)
    {
        $ret = self::$db->select('from_id,from_name,to_id,to_name,content,time_line')->from('ws_chat_log')->where('servicelog_id=:sid')->bindValues(array('sid' => $sericeId))->orderByASC(['id'])->limit($limit)->query();
        if ($ret) {
            rsort($ret);
        }
        return $ret;
    }

    //用户排队数据  按组
    private static function getUserListData()
    {
        $alluser = self::$redis->hgetall(self::USERLIST);
        if (empty($alluser)) {
            return false;
        }
        $allusergkarr = [];
        foreach ($alluser as $val) {
            $now = json_decode($val, true);
            if ($now) {
                //用户分组后的数组
                $allusergkarr[$now['group']][] = $now;
            }
        }
        foreach ($allusergkarr as $group => $nowgroups) {
            usort($allusergkarr[$group], function ($a, $b) {
                if ($a['intime'] == $b['intime']) {
                    return 0;
                }
                return ($a['intime'] > $b['intime']) ? 1 : -1;
            });
        }

        if (!$allusergkarr) {
            return false;
        }
        unset($alluser);
        return $allusergkarr;
    }

    //找到可以接工单的客服 按组
    private static function getWorkKfData()
    {
        $allkfs = self::$redis->hgetall(self::KFINFOKEY);
        if (empty($allkfs)) {
            return false;
        }
        $allkfgkarr = [];
        foreach ($allkfs as $val) {
            $now = json_decode($val, true);
            if ($now && $now['status'] == 1) {
                //客分组后的数组
                $tmp = self::getKfTasks($now['id']);
                $now['task'] = $tmp ? count($tmp) : 0;
                $allkfgkarr[$now['group']][] = $now;
            }
        }
        if (!$allkfgkarr) {
            return false;
        }
        //客服每组按任务数由小到大排序 任务相同时按时间先后顺序
        foreach ($allkfgkarr as $group => $nowgroups) {
            usort($allkfgkarr[$group], function ($a, $b) {
                if ($a['task'] == $b['task']) {
                    if ($a['intime'] == $b['intime']) {
                        return 0;
                    }
                    return ($a['intime'] > $b['intime']) ? 1 : -1;
                }
                return ($a['task'] > $b['task']) ? 1 : -1;
            });
        }
        unset($allkfs);

        return $allkfgkarr;
    }


    //找到用户是否有一条未关闭的会话
    private static function UserHasOldTalk($uid, $database = 0)
    {
        if ($database) {
            $uid = intval($uid);
            $start_time = time() - 86400;
            $ret = self::$db->select('*')->from('ws_service_log')->where("start_time>=$start_time and user_id=$uid and  status!=2 ")->orderByDESC(['servicelog_id'])->row();
            return $ret;
        }

        $all = self::$redis->hgetall(self::SERVICELOG);
        if (empty($all)) {
            return false;
        }
        foreach ($all as $val) {
            $tmp = json_decode($val, true);
            if ($tmp && $tmp['user_id'] == $uid) {
                return $tmp;
            }
        }
        return false;
    }


    //今天排序累加
    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)
    {

    }

    /**
     * 获取最大的服务人数
     * @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;
        }

        $inQueue_1 = self::$redis->hgetall(self::USERLIST);
        $inQueue = empty($inQueue_1) ? 0 : count($inQueue_1);
        $allkf = self::$redis->hgetall(self::KFINFOKEY);
        $nowTalking = $onlineKf = 0;
        if (!empty($allkf)) {
            foreach ($allkf as $kfuid => $val) {
                $onlineKf++;
                $nowTalking = 0;
            }
        }

        $key = date('Ymd') . 'total_in';
        $key2 = date('Ymd') . 'success_in';
        $param = [
            'is_talking' => $nowTalking,
            'in_queue' => $inQueue,
            'online_kf' => $onlineKf,
            'success_in' => intval(self::$global->$key2),
            'total_in' => intval(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' => intval(self::$global->$key2),
                'total_in' => intval(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($allkf, $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',
            ]
        ];
        Gateway::sendToClient($client_id, json_encode($chat_message, 256));
    }

    /**
     * 评价
     * @param $client_id 服务ID
     * @param $message 数据
     */
    private static function evaluate($message)
    {
        // 获取当前会话工单.
        $data = json_decode(self::$redis->HGET('SERVICELOG', $message['conversationId']), true);
        if (empty($data)) {
            return;
        }
        $data['evaluate_id'] = $message['evaluate_id'];
        $data['evaluate_content'] = $message['evaluate_content'];
        self::$redis->HSET('SERVICELOG', $message['conversationId'], json_encode($data, 256));
        $chat_message = [
            'message_type' => 'evaluate',
            'data' => [
                'status' => 1,
                'time' => date('H:i'),
            ]
        ];
        Gateway::sendToCurrentClient(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;
        }

        $arr = [];
        $systemReplay = self::$db->query('select * from `ws_reply` where `type`=1 order by `sort`');
        $kfReplay = self::$db->query('select * from `ws_reply` where `type`=2');
        $systemWelcome = [];
        foreach ($systemReplay as $v) {
            $systemWelcome[] = htmlspecialchars_decode($v['word']);
        }
        self::$global->systemReplay = $systemWelcome;
        self::$global->kfReplay = $kfReplay;

        $arr = [];
        $bq = self::$db->query("select  *  from ws_accountslabel");
        if ($bq) {
            foreach ($bq as $val) {
                $arr[$val['id']] = $val;
            }
            self::$global->accountslabel = $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') {
                $configOvertime = $v;
            } elseif ($v['systemconfig_enName'] == 'unoperated') {
                $configUnoperated = $v;
            }
        }
        // 查询未断开的工单.
        $serviceLog = self::$redis->hGetall('SERVICELOG');
        $setOvertime = strtotime('-' . ($configOvertime['systemconfig_data'] - 60) . ' second');
        $overtime = strtotime('-' . ($configOvertime['systemconfig_data']) . ' second');
        $setUnoperated = strtotime('-' . ($configUnoperated['systemconfig_data'] - 60) . ' second');
        $unoperated = strtotime('-' . ($configUnoperated['systemconfig_data']) . ' second');
        foreach ($serviceLog as $k => $v) {
            // 无效会话关闭.如果没有说一句话.
            $data = json_decode($v, true);
            if (!isset($data['userLastTime'])) {
                if ($data['start_time'] <= $unoperated) {
                    self::serverClose($k, 1);
                    // 如果小于设定时间前一分钟则给出提示.
                } elseif ($data['start_time'] <= $setUnoperated) {
                    $chat_message = [
                        'message_type' => 'overtime',
                        'data' => [
                            'content' => $configUnoperated['systemconfig_content'],
                        ]
                    ];
                    Gateway::sendToClient($data['client_id'], json_encode($chat_message, 256));
                }
                // 双方静默超时.
            } elseif (isset($data['serverLastTime'])) {
                if ($data['userLastTime'] <= $overtime && $data['serverLastTime'] <= $overtime) {
                    self::serverClose($k, 2);
                } elseif ($data['userLastTime'] <= $setOvertime && $data['serverLastTime'] <= $setOvertime) {
                    $chat_message = [
                        'message_type' => 'overtime',
                        'data' => [
                            'content' => $configOvertime['systemconfig_content'],
                        ]
                    ];
                    Gateway::sendToClient($data['client_id'], json_encode($chat_message, 256));
                }
            } else {
                if ($data['userLastTime'] <= $overtime) {
                    self::serverClose($k, 2);
                } elseif ($data['userLastTime'] <= $setOvertime) {
                    $chat_message = [
                        'message_type' => 'overtime',
                        'data' => [
                            'content' => $configOvertime['systemconfig_content'],
                        ]
                    ];
                    Gateway::sendToClient($data['client_id'], json_encode($chat_message, 256));
                }
            }
        }
    }

    /**
     * 系统监控
     * @param $message 数据
     */
    private static function systemMonitoring($adminList)
    {
        // 查询正进行的工单.
        $serviceLog = self::$redis->hGetall('SERVICELOG');
        // 查询系统设置表.
        $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; // 差评总次数.
        $overtimeNumber = 0; // 会话超时总次数.
        $overtimeTime = []; // 每次会话超时时间.
        $userSensitive = 0; // 用户敏感词报警总次数.
        $serverSensitive = 0; // 客服敏感词报警总次数.
        $csdNumber = 0; // 响应超时总次数.
        $csdTime = []; // 每次响应超时时间.
        foreach ($serviceLog as $k => $v) {
            $data = json_decode($v, true);
            // 工单报警次数.
            $allCount = 0;
            if ($data['evaluate_id'] == 3) {
                $evaluateCount++; // 差评次数.
                $allCount++; // 工单报警次数.
            }
            // 会话超时.
            $duration = time() - $data['start_time'];
            if ($duration > $verifyAllTime) {
                $overtimeNumber++; // 会话超时总次数.
                $allCount++; // 工单报警次数.
                $overtimeTime[] = $duration; // 响应超时时间.
            }
            // 敏感词报警.
            $userSensitive += $data['alarm_userSensitive'];
            $allCount += $data['alarm_userSensitive'];
            $serverSensitive += $data['alarm_serverSensitive'];
            $allCount += $data['alarm_serverSensitive'];
            // 响应超时.
            if ($data['alarm_corresponding'] > $verifyReturnTime) {
                $csdTime[] = $data['alarm_corresponding']; // 响应超时时间.
                $csdNumber++; // 响应超时总次数.
                $allCount++; // 工单报警次数.
            }
            $serviceLog[$k] = $data;
            $serviceLog[$k]['allCount'] = $allCount; // 工单报警次数.
        }

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

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

    //客户工单内部组转接
    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']) ? intval($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;
        }

        $kf_info_from = json_decode(self::$redis->hget(self::KFINFOKEY, $fromkfuid), true);
        $kf_info_to = json_decode(self::$redis->hget(self::KFINFOKEY, $toukfid), true);
        $user_info = json_decode(self::$redis->hget(self::USERINFOKEY, $uid), true);
        $serviceid = intval($user_info['serverid']);

        if (empty($kf_info_from) || empty($kf_info_to) || empty($user_info) || empty($serviceid)) {
            self::DebugOut('changeOtherhKeFu exit23...');
            return false;
        }

        if ($kf_info_to['status'] != 1) {
            self::DebugOut('changeOtherhKeFu exit4...');
            return false;
        }

        /////////取消原有会话，开启新会话
        $oldlog = self::$db->select('*')->from('ws_service_log')->where('servicelog_id=:servicelog_id ')->bindValues(['servicelog_id' => $serviceid])->orderByDESC(['servicelog_id'])->row();
        if (!$oldlog) {
            self::DebugOut('changeOtherhKeFu exit5...');
            return false;
        }

        self::insertServerLog($serviceid, 5);
        self::$redis->hdel(self::SERVICELOG, $serviceid);
        unset($oldlog['servicelog_id']);

        ///更新redis数据
        self::updteKfTasksByservicd($fromkfuid, $serviceid, $user_info['client_id'], 0);

        self:: BeginTalk($toukfid, $uid, $groupidto, 0, $user_info, 1);
        self::servicetrutoother('OUT', $fromkfuid, $toukfid, $serviceid, $uid);
        $newUserInfo = json_decode(self::$redis->hget(self::USERINFOKEY, $uid), true);
        self::servicetrutoother('IN', $toukfid, $fromkfuid, $newUserInfo['serverid'], $uid);

        //回转接人，转接成功
        Gateway::sendToCurrentClient(json_encode(['message_type' => 'trunconnect', 'data' => ['status' => 1]], 256));
        // 发送给用户转接消息
        Gateway::sendToClient($user_info['client_id'], json_encode(['message_type' => 'changeKeFuSuccess', 'data' => ['content' => "会话转接成功"]], 256));

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

        return;
    }


    //客服在线状态写组
    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 * 7;
        $now = time();

        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,end_time=$now where  start_time>=$t and  kf_id=$kfid and  status!=2");
            self::$redis->hdel(self::KFINFOKEY, 'KF' . $kfid);
        } else {
            //self::$redis->del(self::KFINFOKEY);
            //self::$redis->del(self::USERLIST);
            //self::$redis->del(self::USERINFOKEY);
            //self::$redis->del('adminList');
            //self::$redis->del(self::WEBSOCKALLUSER);
            //self::$redis->del('SERVICELOG');
            self::$redis->flushdb();
            self::$db->query("update ws_service_log set status=2,end_time=$now where  start_time>=$t and  status!=2");
        }

    }

    public static function onWorkerStop($businessWorker)
    {
        if ($businessWorker->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;
    }


    //定时器相关
    private static function TimerThing($worker)
    {

        // 当天的累积接入值
        $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);
        }

        // 每1分钟做一次redis ping检测避免redis掉线
        Timer::add(60, function () {
            if (!self::$logic->RedisPing()) {
                self::$redis = self::$logic->getRedis(0);
            }
        });

        if (strtolower(substr(PHP_OS, 0, 3)) == 'win') {
            // 定时统计数据
            if (0 == $worker->id) {

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

                //每5秒更新进行一次人员分配
                Timer::add(5, function () {
                    self::userOnlineTask();
                });

                //每1分钟报告一次本组排列人员(如果有人排队)
                Timer::add(60, function () {
                    self::lineup();
                });


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

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

                // 删除前一天的统计值
                Timer::add(60 * 60 * 12, function () {
                    $oldKey = date('Ymd', strtotime('-1 day'));
                    unset(self::$global->$oldKey);
                });

                // 管理员实时监控.
                Timer::add(20, function () {
                    // 获取在线管理员
                    $adminList = self::$redis->smembers('adminList');
                    if ($adminList) {
                        self::systemMonitoring($adminList);
                    }
                });

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

                self::resetServiceLog();
            }
        } else {
            ///linux 下支持多进程....

            if (0 == $worker->id) {

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

                //每5秒更新进行一次人员分配
                Timer::add(5, function () {
                    self::userOnlineTask();
                });

                //每1分钟报告一次本组排列人员(如果有人排队)
                Timer::add(60, function () {
                    self::lineup();
                });

                self::resetServiceLog();

            } elseif (1 == $worker->id) {

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

            } elseif (2 == $worker->id) {

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

                // 删除前一天的统计值
                Timer::add(60 * 60 * 12, function () {
                    $oldKey = date('Ymd', strtotime('-1 day'));
                    unset(self::$global->$oldKey);
                });


            } elseif (3 == $worker->id) {
                // 管理员实时监控.
                Timer::add(20, function () {
                    // 获取在线管理员
                    $adminList = self::$redis->smembers('adminList');
                    if ($adminList) {
                        self::systemMonitoring($adminList);
                    }
                });

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

    }

    //调试使用
    public static function mydebug($client_id, $message)
    {

    }

    public static function MySendMsg($clientId, $msg)
    {
        Gateway::sendToClient($clientId, $msg);
    }

    //得到客服的UID字符值
    public static function getkfuid($uid)
    {
        if (substr($uid, 0, 2) == 'KF') {
            return $uid;
        } else {
            return 'KF' . intval($uid);
        }
    }

    //得到客服的ID整数值
    public static function getkfid($id)
    {
        if (strtolower(substr($id, 0, 2)) == 'kf') {
            return intval(substr($id, 2));
        }
        return intval($id);
    }

    //从数组中获取参数
    public static function getPars($array, $key, $default = '')
    {
        if (isset($array[$key])) {
            return $array[$key];
        }
        return $default;
    }

    //获取在线客服信息
    public static function getOnlineKfData($group = 0, $status = 0)
    {
        $all = self::$redis->hgetall(self::KFINFOKEY);
        if (!$all) {
            return false;
        }
        $return = [];
        foreach ($all as $val) {
            $now = json_decode($val, true);
            if ($group) {
                if ($now['group'] != $group) {
                    continue;
                }
            }
            if ($status) {
                if ($now['status'] != $status) {
                    continue;
                }
            }
            $return[$now['id']] = $now;
        }
        return $return;
    }

    //找到在排队的用户按时间先后顺序
    public static function getUselistData($group)
    {
        $all = self::$redis->hgetall(self::USERLIST);
        if (!$all) {
            return false;
        }
        $return = [];
        foreach ($all as $val) {
            $now = json_decode($val, true);
            if ($group == $now['group']) {
                $return[] = $now;
            }
        }
        usort($return, function ($a, $b) {
            if ($a['intime'] == $b['intime']) {
                return 0;
            }
            return $a['intime'] > $b['intime'] ? 1 : -1;
        });
        return $return;
    }

    //对客服的用户user_info数组进行加减操作  $clientid用户连接号    opt=1添加 0删除   $serverid服务工单号
    public static function ArrayDataopt($array, $clientid, $opt, $serverid = 0)
    {
        if (!is_array($array)) {
            return [];
        }

        if ($opt == 0) {
            if (isset($array[$clientid])) {
                unset($array[$clientid]);
            }
            return $array;
        } else {
            $array[$clientid] = $serverid;
            return $array;
        }
    }

    //用户重要性标签
    private static function getUserLabAll($client_id, $message)
    {
        $data = self::$global->accountslabel;
        Gateway::sendToCurrentClient(json_encode(['message_type' => 'userlabeall', 'data' => $data], 256));
    }

    //调试使用
    public static function debug($dataArray)
    {


    }


    //客服的工单hash健名
    public static function getKfServiceKey($kfuid)
    {
        return self::KFSERVICES . ':' . $kfuid;
    }


    //获取客服所有连接信息及工单信息
    public static function getKfTasks($kfuid)
    {
        $all = self::$redis->hgetall(self::getKfServiceKey($kfuid));
        if (empty($all)) {
            return false;
        }
        return $all;
    }

    //设置或删除客服的连接  opt==0删除 1添加
    public static function setKfTasks($kfuid, $clientid, $opt = 0, $serviceid = 0)
    {
        $k = self::getKfServiceKey($kfuid);
        if ($opt == 0) {
            self::$redis->hdel($k, $clientid);
            return;
        }
        self::$redis->hset($k, $clientid, $serviceid);
    }

    //有旧单时，更新连接ID
    public static function updteKfTasksByservicd($kfuid, $serciceid, $newclientid, $opt = 1)
    {
        $tkey = self::getKfServiceKey($kfuid);
        $all = self::getKfTasks($kfuid);
        $serciceid = intval($serciceid);


        if ($opt == 1) {
            if (empty($all)) {
                self::$redis->hset($tkey, $newclientid, $serciceid);
                return;
            }
            foreach ($all as $cid => $nowserverid) {
                if (intval($nowserverid) == $serciceid) {
                    self::$redis->hdel(self::getKfServiceKey($kfuid), $cid);
                }
            }
            self::$redis->hset($tkey, $newclientid, $serciceid);
            return true;
        } else {
            if (empty($all)) {
                return;
            }
            foreach ($all as $cid => $nowserverid) {
                if (intval($nowserverid) == $serciceid) {
                    self::$redis->hdel(self::getKfServiceKey($kfuid), $cid);
                }
            }
            return true;
        }

    }

    //缓存获取用户信息
    public static function getUserInfoCache($uid, $cacheTime = 180)
    {
        $uid = intval($uid);
        $key = 'TmpUserInfo:' . $uid;
        $cache = self::$redis->hget($key, $uid);
        if ($cache && $cacheTime) {
            return json_decode($cache, true);
        }
        $date = self::$db->select('*')->from('ws_accounts')->where("id= $uid ")->row();
        self::$redis->hset($key, $uid, json_encode($date, 256));
        self::$redis->EXPIRE($key, $cacheTime);
        return $date;
    }

    //检查一个新人是否需要排队
    public static function HasInqueue($group)
    {
        $group = intval($group);
        $allserveric = self::$redis->hgetall(self::SERVICELOG);
        if (empty($allserveric)) {
            return false;
        }
        $count = 0;
        foreach ($allserveric as $serv) {
            $tmp = json_decode($serv, true);
            if (isset($tmp['group_id']) && $tmp['group_id'] == $group) {
                $count++;
            }
        }

        $gkf = self::getOnlineKfData($group, 1);
        $max = intval(self::$global->systemconfig['KFMaxServices']['systemconfig_data']);

        if ($gkf) {
            $cc = count($gkf) * $max;
            if ($count >= $cc) {
                return true;
            }
        }

        return false;
    }

}

