<?php
/*
 本代码由 焕岱科技 创建
 技术支持 WX：15285007200
 严禁反编译、逆向等任何形式的侵权行为，违者将追究法律责任
*/
use \GatewayWorker\Lib\Gateway;
use app\common\model\bbfxshop\Chat;
use think\Db;

class Events
{
   
    public static function printLog($content){
        $text = "[".date("Y-m-d H:i:s")."]"." ".$content.PHP_EOL;
        echo $text;
        file_put_contents("chat111.txt",$text,FILE_APPEND);
    }

    public static function onWorkerStart(){
        \Workerman\Lib\Timer::add(50, function(){
            Db::query('select 1');
        });
    }

    public static function onConnect($client_id){
        $message = [
            'type'=>'connect',
            'client_id'=>$client_id
        ];
        Gateway::sendToClient($client_id, json_encode($message));
    }

    /**
     * 有消息时
     * @param int $client_id
     * @param mixed $message
    */
    public static function onMessage($client_id, $result)
    {
        // 开发文档：https://www.workerman.net/
        $result = json_decode($result, true);
        if(empty($result)){
            return ;
        }
        $type = $result['type'];
        if(empty($type)){
            return ;
        }
        
        switch ($type) {
            case 'pong':
                
                break;
            case 'chat_list_login':
                $user_id = $result['user_id'];
                if(!empty($user_id)){
                    Gateway::bindUid($client_id, $user_id);
                }
                break;
            case 'chat_login':
                $rid = $result['rid'];
                $user_id = $result['user_id'];
                $to_user_id = $result['to_user_id'];
                if(!empty($user_id) && !empty($to_user_id) && !empty($rid)){
                    $uuid = $rid."_".$user_id;
                    // 绑定用户ID
                    Gateway::bindUid($client_id, $uuid);
                    // 加入房间
                    Gateway::joinGroup($client_id, $rid);
                    $clients_list = Gateway::getClientIdCountByGroup($rid);
                    self::printLog("用户列表数量：".json_encode($clients_list));
                    // $user_client_id = Gateway::getClientIdByUid($uuid);
                    self::printLog("用户client_id：".$client_id);
                    $uuid = Gateway::getUidByClientId($client_id);
                    self::printLog("用户ID：".json_encode($uuid));
                }
                break;
            case 'chat_send':
                try {
                    $rid = $result['rid'];
                    $user_id = $result['user_id'];
                    $to_user_id = $result['to_user_id'];
                    
                    if(!empty($user_id) && !empty($to_user_id)){

                        self::printLog("发送消息：".$result['content']);

                        $res = Chat::send($result);

                        self::printLog("发送消息：".json_encode($res));

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


                            $message = [
                                'type'=>'chat_send',
                                'new'=> $result['new'],
                                'id'=> $res['data']['chat_id'],
                            ];
                            // 推送消息给发送用户
                            Gateway::sendToClient($client_id, json_encode($message));

                            self::printLog("发送成功：".$result['content']);

                            $message = [
                                'type'=>'message',
                                'message_type'  => $result['message_type'],  // 消息类型（1=文本，2=图片，3=视频）
                                'from_user_id'  => $user_id,                 // 发送者ID
                                'client_id'  => $client_id,                  // 发送者ID
                                'id'            => $res['data']['chat_id'],  // 消息ID
                                'createtime'    => time(),                   // 创建时间
                                'content'       => $result['content'],       // 消息内容
                            ];
                            
                            $clients_count = Gateway::getClientIdCountByGroup($rid);
                            if($clients_count > 1){
                                self::printLog("接收成功：".$result['content']);
                                Gateway::sendToGroup($rid, json_encode($message));
                                /*
                                $uuid = $rid."_".$to_user_id;
                                // 判断接收用户是否在线
                                $isUidOnline = Gateway::isUidOnline($uuid);
                                if($isUidOnline){
                                    $to_client_id = Gateway::getClientIdByUid($uuid);
                                    if(!empty($to_client_id)){
                                        // 推送消息给接收用户
                                        Gateway::sendToClient($to_client_id[0], json_encode($message));
                                    }
                                    else{
                                        self::printLog("未查询到接收用户");
                                    }
                                }
                                else{
                                    self::printLog("接收用户离线");
                                }
                                */
                            }
                            else{
                                self::printLog("接收失败：".$result['content']);
                            }
                            
                            // 判断接收用户是否列表在线
                            $isUidOnline = Gateway::isUidOnline($to_user_id);
                            if($isUidOnline){
                                self::printLog("发送消息列表");
                                $to_client_id = Gateway::getClientIdByUid($to_user_id);
                                if(!empty($to_client_id)){

                                    $list = [];
                                    $listRes = Chat::getList($to_user_id);
                                    if($listRes['code'] == 1){
                                        $list = $listRes['data']['list'];
                                    }
                                    
                                    $message = [
                                        'type'=>'chat_list',
                                        'list'=> $list
                                    ];

                                    self::printLog("接收消息列表");

                                    // 推送消息给接收用户消息列表
                                    Gateway::sendToClient($to_client_id[0], json_encode($message));
                                }
                            }
                            else{
                                self::printLog("用户不在线");
                            }
                        }
                        else{

                            self::printLog("发送失败：".$res['message']);
                            try {
                                $message = [
                                    'type'=>'error',
                                    'content'=> $res['message'],
                                ];
                                // 推送消息给发送用户
                                Gateway::sendToClient($client_id, json_encode($message));
                                
                            } catch (\Exception $e) {
                                self::printLog($e->getMessage()." ".$e->getLine());
                            }
                        }
                    }
                    
                } catch (\Exception $e) {
                    self::printLog($e->getMessage()." ".$e->getLine());
                }
                
                break;
            case 'chat_revoke':
                // 消息撤回
                $id = $result['id'];
                $rid = $result['rid'];
                $user_id = $result['user_id'];
                $to_user_id = $result['to_user_id'];
                self::printLog("消息撤回：".$id);
                if(!empty($id)){
                    $res = Chat::revoke($id, $result['user_id']);
                    if($res['code'] == 1){
                        self::printLog("消息撤回成功：".$id);
                        $message = [
                            'type'=>'chat_revoke',
                            'id'=> $id,
                        ];
                        // 推送消息给发送用户
                        Gateway::sendToClient($client_id, json_encode($message));

                        // 判断接收用户是否列表在线
                        $isUidOnline = Gateway::isUidOnline($to_user_id);
                        if($isUidOnline){
                            $to_client_id = Gateway::getClientIdByUid($to_user_id);
                            if(!empty($to_client_id)){
                                $list = [];
                                $listRes = Chat::getList($to_user_id);
                                if($listRes['code'] == 1){
                                    $list = $listRes['data']['list'];
                                }
                                
                                $message = [
                                    'type'=>'chat_list',
                                    'list'         => $list
                                ];
                                // 推送消息给接收用户消息列表
                                Gateway::sendToClient($to_client_id[0], json_encode($message));
                            }
                        }
                    }
                    else{
                        self::printLog("消息撤回失败：".$id."，".$res['message']);
                        $message = [
                            'type'=>'error',
                            'content'=> $res['message'],
                        ];
                        // 推送消息给发送用户
                        Gateway::sendToClient($client_id, json_encode($message));
                    }
                }
                break;
            case 'chat_read':
                // 消息已读
                $id = $result['id'];
                $rid = $result['rid'];
                $user_id = $result['user_id'];
                $to_user_id = $result['to_user_id'];
                self::printLog("消息已读：".$id);
                if(!empty($id)){
                    $res = Chat::read($id, $result['user_id']);
                    if($res['code'] == 1){
                        self::printLog("消息已读成功：".$id);
                        // 判断接收用户是否列表在线
                        $isUidOnline = Gateway::isUidOnline($to_user_id);
                        if($isUidOnline){
                            $to_client_id = Gateway::getClientIdByUid($to_user_id);
                            if(!empty($to_client_id)){
                                $list = [];
                                $listRes = Chat::getList($to_user_id);
                                if($listRes['code'] == 1){
                                    $list = $listRes['data']['list'];
                                }
                                
                                $message = [
                                    'type'=>'chat_list',
                                    'list'=> $list
                                ];
                                // 推送消息给接收用户消息列表
                                Gateway::sendToClient($to_client_id[0], json_encode($message));
                            }
                        }
                    }
                    else{
                        self::printLog("消息已读失败：".$id);
                    }
                }
                break;
        }
        
        
    }
   
    /**
    * 当客户端断开连接时
    * @param integer $client_id 客户端id
    */
    public static function onClose($client_id)
    {
        $user_id = Gateway::getUidByClientId($client_id);
        if(!empty($user_id)){
            self::printLog("用户退出聊天：".$client_id);
            Gateway::unbindUid($client_id, $user_id);
        }
        self::printLog("用户退出：".$client_id);
    }
  
}
