<?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;

/**
 * 主逻辑
 * 主要是处理 onConnect onMessage onClose 三个方法
 * onConnect 和 onClose 如果不需要可以不用实现并删除
 */
class Events
{
    /**
     * 有消息时
     * @param int $client_id
     * @param mixed $message
     */
    public static function onMessage($client_id, $message)
    {
        Gateway::$registerAddress = '118.190.141.120:1238';
        // debug
        // 客户端传递的是json数据
        if(!$message)
        {
            return ;
        }
        // 根据类型执行不同的业务
        switch($message['post']['type'])
        {
//            case ""://公共相应 前端未发送成功消息
            case "pong"://心跳 心跳链接断了 踢出用户

            case 'say': //私聊
                $data['to_user_number'] = $message['post']['to_user_number'];
                //获取接收人的昵称
                $usered = (new userModule())->where(['number'=>$data['to_user_number']])->one();
                $data['to_nickname'] = $usered['nickname'];
                $data['nickname'] = $message['user']['user_info']['nickname'];
                //查询用户的client_id
                $data['client_id'] = $_SESSION['user'];
                $data['dtime'] = date('Y-m-d H:i:s');
                foreach ($_SESSION['user'] as $k=>$v){
                    if ($v['user_number'] == $data['to_user_number']){
                        $data['client_id'] = $v['client_id'];
                    };
                }
                $data['content'] = $message['post']['content'];
                // 如果是向某个客户端发送消息
                    // 转发消息给对应的客户端
                $arr1 = $data;
                $arr1['number'] = $message['user']['user_info']['number'];
                $arr1['usered_number'] = $usered['number'];
                if (Gateway::isOnline($data['client_id'])){
                    Gateway::sendToClient($data['client_id'], $data['content']);
                    //发送成功后  存日志
                    $log = (new commonModule('sl_user_say'))->insert($arr1);
                    $data['type'] = 'say';
                    return $data;
                }else{
                    $dataArr = [];
                    $dataArr=[
                        'code'=>200,
                        'client_id'=>$client_id,
                        'status'=>false,
                        'message'=>'用户不在线',
                        'type'=>'say',
                    ];
                    return $dataArr;
                }


        ##############################################
                //单人用户登录绑定client_id
            case 'oneUserLogin'://单人用户登录
            $yonghu['user_number'] = $message['user']['user_info']['number'] ;
            $yonghu['user_nickname'] = $message['user']['user_info']['nickname'] ;
            $yonghu['user_id'] = $message['user']['user_info']['id'] ;
            $c = array_diff($_SESSION['user'], $yonghu);
            if (!$c){
                $arr['user_number'] = $message['user']['user_info']['number'];
                $arr['user_nickname'] = $message['user']['user_info']['nickname'];
                $arr['user_id'] = $message['user']['user_info']['id'];
                $_SESSION['user'][] = $arr;
            }
            if ($_SESSION['user']){
                $dataArr=[
                    'code'=>200,
                    'status'=>true,
                    'message'=>'登录成功',
                    'message'=>'oneUserLogin',
                ];
            }else{
                $dataArr=[
                    'code'=>2013,
                    'status'=>false,
                    'message'=>'登录失败',
                    'type'=>'oneUserLogin',
                ];
            }
            return $dataArr;
            //用户绑定uid
            case 'oneUserBand'://单人用户绑定client_id
            //循环用户列表  找到相应的用户id 修改用户的client_id

                // client_id与uid绑定
                // 加入某个群组（可调用多次加入多个群组） 将clientid加入roomid分组中
//                Gateway::joinGroup($client_id, $message['user']['user_info']['id']);
                // 返回ajax json信息
                //绑定用户的$client_id
                foreach ($_SESSION['user'] as $k=>$v){
                    if ($v['user_number'] ==$message['user']['user_info']['number']){
                        $_SESSION['user'][$k]['client_id'] = $client_id;
                    }
                }
                //获取用户绑定的client_id
                 if (Gateway::bindUid($client_id, $message['user']['user_info']['id'])){
                     $dataArr=[
                         'code'=>200,
                         'client_id'=>$client_id,
                         'status'=>true,
                         'message'=>'用户绑定client_id成功',
                         'type'=>'oneUserBand',
                     ];
                 }else{
                     $dataArr=[
                         'code'=>201,
                         'client_id'=>$client_id,
                         'status'=>false,
                         'type'=>'oneUserBand'
                     ];
                 };
                return $dataArr;
            //用户绑定房间
            case 'band_room':
                //当用户进入房间时  查看用户是否被踢出房间
                $number = (new userModule())->findOne($message['post']['room_id']);
                $number = $number['number'];
                //查询用户是否被禁言
                $is_ban = (new userRoomModule())->where(['anchor_id'=>$number,'usered_number'=>$message['user']['userinfo']['number'],'type'=>3])->one();
                if ($is_ban['time']>date('Y-m-d H:i:s')){
                    Gateway::sendToUid($message['user']['userinfo']['id'],'您已被禁言');
                    $dataArr=[
                        'code'=>201,
                        'status'=>true,
                        'message'=>'您已被禁言',
                        'type'=>'banned',
                    ];
                    return $dataArr;
                }
                //获取用户的client_id
                foreach ($_SESSION['user'] as $k=>$v){
                    if ($v['user_number'] == $message['user']['user_info']['number']){
                        $user_client_id = $v['client_id'];
                        $_SESSION['user'][$k]['room_id'] = $message['post']['room_id'];
                    }
                }
                Gateway::$registerAddress = '127.0.0.1:1238';
                //用户加入房间组
                if (Gateway::joinGroup($user_client_id,$message['post']['room_id'])){
                    $dataArr=[
                        'code'=>200,
                        'status'=>true,
                        'message'=>'进入房间成功',
                        'type'=>'band_room',
                    ];

                }else{
                    $dataArr=[
                        'code'=>2021,
                        'status'=>false,
                        'message'=>'进入房间失败',
                        'type'=>'band_room',
                    ];
                }
                return $dataArr;
            //主播创建房间
            case 'creat_room':
                print_r($_SESSION);
                if (empty($_SESSION['room_id'])){
                    $_SESSION['room_id'][] = $message['user']['user_info']['id'];
                }
                foreach ($_SESSION['room_id'] as $k=>$v){
                    if ($message['user']['user_info']['id'] != $v){
                        $_SESSION['room_id'][] = $message['user']['user_info']['id'];
                    }
                }
                foreach ($_SESSION['user'] as $k=>$v){
                    if ($v['user_number'] == $message['user']['user_info']['number']){
                        $user_client_id = $v['client_id'];
                        $_SESSION['user'][$k]['room_id'] = $message['post']['room_id'];
                    }
                }
                if (Gateway::joinGroup($user_client_id,$message['post']['room_id'])){
                    $dataArr=[
                        'room_id'=>$message['user']['user_info']['id'],
                        'code'=>200,
                        'status'=>true,
                        'message'=>'创建房间成功',
                        'type'=>'creat_room',
                    ];
                }else{
                    $dataArr=[
                        'code'=>2021,
                        'status'=>false,
                        'message'=>'创建房间失败',
                        'type'=>'creat_room',
                    ];
                }
                return $dataArr;
                //房间内发言
            case 'user_room_say':
                //房间内发言 查看用户被禁言没有
                //根据房间id查询主播的编号
                $number = (new userModule())->findOne($message['post']['room_id']);
                $number = $number['number'];
                //查询用户是否被禁言
                $is_ban = (new userRoomModule())->where(['anchor_id'=>$number,'usered_number'=>$message['user']['userinfo']['number'],'type'=>2])->one();
                if ($is_ban){
                    Gateway::sendToUid($message['user']['userinfo']['id'],'你已被踢出房间');
                    $dataArr=[
                        'code'=>201,
                        'status'=>true,
                        'message'=>'你已被踢出房间',
                        'type'=>'remove_room',
                    ];
                    return $dataArr;
                }
                if (empty($message['post']['room_id'])){
                    returnFail([],getcodestr(2029),2029);
                }
                if (empty($message['post']['content'])){
                    returnFail([],getcodestr(2031),2031);
                }
                Gateway::sendToGroup($message['post']['room_id'],$message['post']['content']);
                $log = (new commonModule('sl_user_room_say'))->insert(['dtime'=>date('Y-m-d H:i:s'),'number'=>$message['user']['userinfo']['number'],
                    'content'=>$message['post']['content'],'room'=>$message['post']['room_id']]);
                if ($log){
                    $dataArr=[

                        'code'=>200,
                        'status'=>true,
                        'message'=>'发言成功',
                        'content'=>$message['post']['content'],
                        'type'=>'user_room_say',
                    ];
                }else{
                    $dataArr=[
                        'code'=>2030,
                        'status'=>false,
                        'message'=>'发言失败',
                        'content'=>$message['post']['content'],
                        'type'=>'user_room_say',
                    ];
                }
                return $dataArr;
       ##############################################
            //用户给主播送礼物
            case 'gift':
                $post = $message['post'];
                //暂定###########################################################
                $giftModule = new giftModule();
                $gift = $giftModule->verUserSentGift($message['user']['user_info'],$post);
                $gift['gift_type'] = $gift['type'];
                $gift['type'] = 'gift';
                $gift['code'] = '200';
                $gift['msg'] = '送礼成功';
                Gateway::sendToGroup($message['post']['room_id'],json_encode($gift));
                return $gift;
            case ""://媒体状态  主播重新开播

            case ""://充值回调
            case "message"://系统消息
            case "message"://系统消息
            case 'banned':
                //用户禁言
               //根据用户编号  查询用户的client_id
                foreach ($_SESSION['user'] as $k=>$v){
                    if($v['user_number'] == $message['usered_number'] && $v['room_id'] == $message['room_id']){
                        //将用户禁言  并且通知该用户
                        $data['type'] = 'banned';
                        $data['user_id'] = $v['user_id'];
                        $data['content'] = '你被禁言';
                        Gateway::sendToClient($v['client_id'], json_encode($data));
                    }
                }
                //查看房间内有多少人
               return $data;
            case 'remove_room'://将用户踢出房间
                foreach ($_SESSION['user'] as $k=>$v){
                    if($v['user_number'] == $message['usered_number'] && $v['room_id'] == $message['room_id']){
                        //将用户禁言  并且通知该用户
                        $data['type'] = 'remove_room';
                        $data['user_id'] = $v['user_id'];
                        $data['content'] = '您被踢出房间';
                        Gateway::sendToClient($v['client_id'], json_encode($data));
                    }
                }
                //查看房间内有多少人
                return $data;
                ##########################暂定#############################
            case 'get_room_user_num'://获取房间的用户人数
                ##########################暂定#############################
        }
    }

    /**
     * 当客户端断开连接时
     * @param integer $client_id 客户端id
     */
    public static function onClose($client_id)
    {
        // debug
        echo "client:{$_SERVER['REMOTE_ADDR']}:{$_SERVER['REMOTE_PORT']} gateway:{$_SERVER['GATEWAY_ADDR']}:{$_SERVER['GATEWAY_PORT']}  client_id:$client_id onClose:''\n";

        // 从房间的客户端列表中删除
        if(isset($_SESSION['room_id']))
        {
            $room_id = $_SESSION['room_id'];
            $new_message = array('type'=>'logout', 'from_client_id'=>$client_id, 'from_client_name'=>$_SESSION['client_name'], 'time'=>date('Y-m-d H:i:s'));
            Gateway::sendToGroup($room_id, json_encode($new_message));
        }
    }

    public static function onConnect($client_id)
    {
        $data['type'] = 'init';
        $data['client_id'] = $client_id;
        $data['name'] = '欢迎登陆';
        // 向当前client_id发送数据
//        Gateway::sendToClient($client_id, json_encode($data));
        // 向所有人发送
        Gateway::sendToAll(json_encode($data));
    }

}