<?php

require_once join(DIRECTORY_SEPARATOR, array(__DIR__,  "vendor", "autoload.php"));
use Workerman\Worker;
use Workerman\WebServer;
use Workerman\Autoloader;
use PHPSocketIO\SocketIO;
// define("FRONT_ROUTE_HTML", false);
// 引入核心启动类
include __DIR__ . "/silephp/core/Framework.class.php";

$sile_Framework = Framework::run2();
// $sile_Framework = [];
// 创建socket.io服务端，监听2021端口
////////启用https
$context = array(
    'ssl' => array(
        'local_cert'  => '/www/wwwroot/onlive/storage/httpd/server.pem',
        'local_pk'    => '/www/wwwroot/onlive/storage/httpd/server.key',
        'verify_peer' => false,
    )
);
$io = new SocketIO(2000, $context);
// $io = new SocketIO(2000);
//定义一个公共方法 获取用户信息

// 监听一个http端口，通过http协议访问这个端口可以向所有客户端推送数据(url类似http://ip:9191?msg=xxxx)
// $io->on('workerStart', function()use($io) {
//     $inner_http_worker = new Worker('http://0.0.0.0:2000');
//     $inner_http_worker->onMessage = function($http_connection, $data)use($io){
//         if(!isset($_GET['msg'])) {
//             return $http_connection->send('fail, $_GET["msg"] not found');
//         }
//         $io->emit('chat message', $_GET['msg']);
//         $http_connection->send('ok');
//     };
//     $inner_http_worker->listen();
// });
//定义用户的单人组

$io->on('connection', function($socket)use($io,$sile_Framework){
    $socket->userdata=[];
    //定义私聊组
    //定义房间组
    $socket->roomdata=[];
    //用户连接的时候  将用户的信息绑定
    //$request = Request::unsetRoute()->all();
    //清空$_SESSION;
    //获取用户的个人信息
    //$xin = (new commonModule())->getUserInfoByToken();
    $user = new userModule();
    $userRoom = new userRoomModule();
    $giftModule = new giftModule();
    $userLeavl = new userLevelModule();
    $userLog = new userSeeLiveLogModule();
    // 定义用户登录 保存参数事件回调函数
    $socket->on('userLogin', function($msg,$ack)use($io,$socket,$user,$userLeavl){

        //临时获取用户信息
        $xin = $user->where(['number'=>$msg['number']])->one();
        $yonghu['user_number'] = $xin['number'] ;
        $yonghu['user_nickname'] = $xin['nickname'] ;
        $yonghu['user_id'] = $xin['id'] ;
        $socket->userdata = $xin['number'];
        $socket->join($socket->userdata);
        $c = array_diff($socket->userdata, $yonghu);
        if (!$c){
            $arr['user_number'] = $xin['number'];
            $arr['user_nickname'] = $xin['nickname'];
            $arr['user_id'] = $xin['id'];
            $socket->userdata= $arr;
        }
        if ($socket->userdata){
            $dataArr=[
                'code'=>200,
                'status'=>true,
                'message'=>"登录成功",
                'type'=>'userLogin',
            ];
        }else{
            $dataArr=[
                'code'=>1001,
                'status'=>false,
                'message'=>'登录失败',
                'type'=>'userLogin',
            ];
        }

        // 触发所有客户端定义的chat message from server事件
        $ack($dataArr);
    });
    //主播创建房间
    $socket->on('creat_room', function($msg,$ack)use($io,$socket,$user){
        //临时获取用户信息
        $xin = $user->where(['number'=>$msg['number']])->one();
        $yonghu['user_number'] = $xin['number'] ;
        $yonghu['user_nickname'] = $xin['nickname'] ;
        $yonghu['user_id'] = $xin['id'] ;
        $socket->roomdata = $xin['id'];
        $socket->join($socket->roomdata[$xin['id']]);
        if ($socket->join($socket->roomdata)){
            $dataArr=[
                'room_id'=>$xin['id'],
                'code'=>200,
                'status'=>true,
                'message'=>'创建房间成功',
                'type'=>'creat_room',
            ];
        }else{
            $dataArr=[
                'code'=>1002,
                'status'=>false,
                'message'=>'创建房间失败',
                'type'=>'creat_room',
            ];
        }
        $ack($dataArr);
        $socket->to($xin['id'])->emit('creat_room', $dataArr);
    });
    //私聊
    $socket->on('say', function($msg,$ack)use($io,$socket,$user){
        //临时获取用户信息
        $xin = $user->where(['number'=>$msg['number']])->one();
        $yonghu['user_number'] = $xin['number'] ;
        $yonghu['nickname'] = $xin['nickname'] ;
        $yonghu['user_id'] = $xin['id'] ;
        $yonghu['avatar'] = $xin['avatar'] ;
        $data['to_user_number'] = $msg['to_user_number'];
        //获取接收人的昵称
        $usered = $user->where(['number'=>$data['to_user_number']])->one();
        $data['to_nickname'] = $usered['nickname'];
        $data['nickname'] = $xin['nickname'];
        $data['user_avatar'] = $xin['avatar'];
        $data['usered_avatar'] = $usered['avatar'];
        //查询用户的client_id
        $data['dtime'] = date('Y-m-d H:i:s');
        $data['content'] = $msg['content'];
        // 如果是向某个客户端发送消息
        // 转发消息给对应的客户端
        $arr1 = $data;
        $arr1['number'] = $xin['number'];
        $arr1['usered_number'] = $usered['number'];
        $io->to($usered['number'])->emit('say', $data);

//            //发送成功后  存日志
        $log = (new commonModule('sl_user_say'))->insert($arr1);
//            $data['type'] = 'say';

    });
    //用户加入房间
    $socket->on('band_room', function($msg,$ack)use($io,$socket,$user,$userRoom,$userLeavl,$userLog){

        //临时获取用户信息
        $xin = $user->where(['number'=>$msg['number']])->one();
        $yonghu['user_number'] = $xin['number'] ;
        $yonghu['user_nickname'] = $xin['nickname'] ;
        $yonghu['user_id'] = $xin['id'] ;
        $socket->roomdata = $msg['room_id'];
        //查询影虎等级
        $user_leavel = $userLeavl->getUserLevelByExp($xin['experience']);
        //查询主播编号
        $num = $user->findOne($msg['room_id']);
        $number = $num['number'];
        if ($xin['id']!=$msg['room_id']){
            $log = $userLog->userSee($xin['number'],$msg['room_id']);
        }
        print_r($msg);
        print_r($xin['number']);
        $is_ban = $userRoom->where(['anchor_id'=>$number,'usered_number'=>$xin['number'],'type'=>3])->one();
        if ($is_ban['time']>date('Y-m-d H:i:s')){
            $dataArr=[
                'code'=>1003,
                'status'=>true,
                'message'=>'您已被踢出房间',
                'type'=>'banned',
            ];
            $socket->emit('event name', $dataArr);
        }
        $socket->join($socket->roomdata[$msg['room_id']]);

        if ($socket->join($socket->roomdata)){

            $dataArr=[
                'room_id'=>$msg['room_id'],
                'code'=>200,
                'nickname'=>$xin['nickname'],
                'user_id'=>$xin['id'],
                'user_leavel'=>$user_leavel['leavel'],
                'message'=>'加入房间成功',
                'type'=>'band_room',
            ];
        }else{
            $dataArr=[
                'code'=>1002,
                'status'=>false,
                'message'=>'加入房间失败',
                'type'=>'band_room',
            ];
        }

        $ack($dataArr);
        $io->to($msg['room_id'])->emit('band_room', $dataArr);

    });
    //用户在房间内发言user_room_say
    $socket->on('user_room_say', function($msg,$ack)use($io,$socket,$user,$userRoom,$userLeavl){
        //临时获取用户信息
        $xin = $user->where(['number'=>$msg['number']])->one();
        $yonghu['user_number'] = $xin['number'] ;
        $yonghu['nickname'] = $xin['nickname'] ;
        $yonghu['user_id'] = $xin['id'] ;
        $yonghu['content'] = $msg['content'];
        $yonghu['code'] = 200;
        $yonghu['status'] = true;
        $yonghu['type'] = 'user_room_say';
        $num = $user->findOne($msg['room_id']);
        $user_leavel = $userLeavl->getUserLevelByExp($xin['experience']);
        $yonghu['user_leavel'] = $user_leavel['leavel'];
        $number = $num['number'];
        $is_ban = $userRoom->where(['anchor_id'=>$number,'usered_number'=>$xin['number'],'type'=>2])->one();
        if ($is_ban){
            $dataArr=[
                'code'=>1004,
                'status'=>true,
                'message'=>'你已被禁言',
                'type'=>'user_room_say',
            ];
            $socket->emit('user_room_say', $dataArr);
        }

        $ack($yonghu);
        $io->to($msg['room_id'])->emit('user_room_say', $yonghu);

    });
    //用户禁言
    $socket->on('banned', function($msg)use($io,$socket,$user,$userRoom){
        $data = $userRoom->etRoomManage($msg);
        if ($data['type']){
            switch ($data['type']){
                case '1':
                    $dataArr=[
                        'code'=>200,
                        'status'=>true,
                        'message'=>'设置房管成功',
                    ];
                    // $socket->emit('banned', $dataArr);
                    $io->to($msg['usered_number'])->emit('banned', '你被设置成房管');
                    break;
                case '2':
                    $dataArr=[
                        'code'=>200,
                        'status'=>true,
                        'message'=>'取消房管成功',
                    ];
                    // $socket->emit('banned', $dataArr);
                    $io->to($msg['usered_number'])->emit('banned', '你被取消房管');
                    break;
                case '3':
                    $dataArr=[
                        'code'=>200,
                        'status'=>true,
                        'message'=>'禁言成功',
                    ];
                    // $socket->emit('banned', $dataArr);
                    $io->to($msg['usered_number'])->emit('banned', '你已被禁言');
                    break;
                case '4':
                    $dataArr=[
                        'code'=>200,
                        'status'=>true,
                        'message'=>'取消禁言成功',
                    ];
                    // $socket->emit('banned', $dataArr);
                    $io->to($msg['usered_number'])->emit('banned', '你已被解除禁言');
                    break;
                case '5':
                    $dataArr=[
                        'code'=>200,
                        'status'=>true,
                        'message'=>'踢人成功',
                    ];
                    // $socket->emit('banned', $dataArr);
                    $io->to($msg['usered_number'])->emit('banned', '你被踢出房间');
                    break;
                case '6':
                    $dataArr=[
                        'code'=>200,
                        'status'=>true,
                        'message'=>'解除成功',
                    ];
                    // $socket->emit('banned', $dataArr);
                    $io->to($msg['usered_number'])->emit('banned', '你被解除踢出房间');
                    break;
            }
        }else{
            $socket->emit('banned', $data);
        }
//        });
//
    });
    //送礼
    $socket->on('gift', function($msg,$ack)use($io,$socket,$user,$userRoom,$giftModule,$userLeavl){

        //临时获取用户信息
        $xin = $user->where(['number'=>$msg['number']])->one();
        $yonghu['user_number'] = $xin['number'] ;
        $yonghu['user_nickname'] = $xin['nickname'] ;
        $yonghu['user_id'] = $xin['id'] ;
        $num = $user->findOne($msg['room_id']);

        //$user_leavel = $userLeavl->getUserLevelByExp($xin['experience']);
        $number = 1;

        $request = $msg;
        // if (empty($msg["number"])){
        //     $dataArr['code'] = 5001;
        //     $dataArr['status'] = false;
        //     $dataArr['msg'] = '主播信息有误0';
        //     $socket->to($xin['id'])->emit('gift', $dataArr);
        //     return;
        // }
        // $anchor = $user->$xin;
        // if (empty($anchor)){
        //     $dataArr['code'] = 5001;
        //     $dataArr['status'] = false;
        //     $dataArr['msg'] = '主播信息有误1';
        //     $socket->to($xin['id'])->emit('gift', $dataArr);
        //     return;
        // }

        //礼物
        if (empty($request["gift"])){
            $dataArr['code'] = 5002;
            $dataArr['status'] = false;
            $dataArr['msg'] = '礼物信息有误';
            $socket->to($xin['id'])->emit('gift', $dataArr);
            return;
        }
        // $giftModule = new giftModule();
        $gift = $giftModule->findOne($request["gift"]);

        if (empty($gift)){
            $dataArr['code'] = 5002;
            $dataArr['status'] = false;
            $dataArr['msg'] = '礼物信息有误';
            $socket->to($xin['id'])->emit('gift', $dataArr);
            return;
        }

        // //礼物数量
        // if (empty($request["number"])){
        //     $dataArr['code'] = 5003;
        //     $dataArr['status'] = false;
        //     $dataArr['msg'] = '请输入礼物数量';
        //     $socket->to($xin['id'])->emit('gift', $dataArr);
        //     return;
        // }
        $usered = $user->findOne($msg['room_id']);
        //礼物所需钻石
        $diamond_need = $gift["diamond"];
        //判断用户钻石是否足够支付
        if ($xin["diamond"] < $diamond_need){
            $dataArr['code'] = 5004;
            $dataArr['status'] = false;
            $dataArr['msg'] = '钻石不足，请先充值';
            $socket->to($xin['id'])->emit('gift', $dataArr);
            return;
        }
        //扣除用户钻石
        $user->start_T();
        $user_diamond = (double)$xin["diamond"] - $diamond_need;
        $res_user = $user->where(["id"=>$xin["id"]])->update(["diamond"=>$user_diamond]);

        //生成收礼物日志
        $gift_log = [
            "user_number" => $xin["number"],
            "usered_number" => $usered["number"],
            "gift_id" => $request["gift"],
            "num" => 1,
            "price" => $diamond_need,
            "create_time" => date("Y-m-d H:i:s"),
        ];
        $res_gift = (new userGiftLogModule())->insert($gift_log);

        //用户消费日志
        $buy_log = [
            "gift" => $request["gift"],
            "number" => $request["number"],
            "total" => $diamond_need,
            "dtime" => date("Y-m-d H:i:s"),
        ];

        $res_buy_log = (new userBuyLogModule())->insert($buy_log);
        //判断结果
        if ($res_user && $res_gift && $res_buy_log){
            $user->comit_T();
            $gift['gift_type'] = $gift['type'];
            $gift['type'] = 'gift';
            $gift['code'] = '200';
            $gift['msg'] = '送礼成功';
            $gift['user_id'] = $xin["id"];
            $gift['nickname'] = $xin["nickname"];
            $gift['user_leavel'] = $user_leavel['leavel'];
            $io->to($msg['room_id'])->emit('gift', $gift);
            $ack($gift);
        }else{
            $user->roll_T();
            $dataArr['code'] = 10001;
            $dataArr['status'] = false;
            $dataArr['msg'] = '送礼失败';
            $socket->emit('gift', $dataArr);
        }



    });
    //禁播主播
    $socket->on('ban', function($msg)use($io,$socket,$user,$userRoom){
        //临时获取用户信息
        $xin = $user->where(['number'=>$msg['number']])->one();
        $yonghu['user_number'] = $xin['number'] ;
        $yonghu['user_nickname'] = $xin['nickname'] ;
        $yonghu['user_id'] = $xin['id'] ;
        $socket->roomdata = $msg['room_id'];
        //查询主播编号
        $num = $user->findOne($msg['room_id']);
        $number = $num['number'];
        $dataArr=[
            'room_id'=>$xin['id'],
            'code'=>200,
            'status'=>true,
            'message'=>'主播被禁播',
            'type'=>'ban',
        ];
        $io->to($xin['id'])->emit('ban', $dataArr);
        $socket->emit('ban', $dataArr);

    });
    //关闭主播本场直播
    $socket->on('close', function($msg)use($io,$socket,$user,$userRoom){
        //临时获取用户信息
        $xin = $user->where(['number'=>$msg['number']])->one();
        $yonghu['user_number'] = $xin['number'] ;
        $yonghu['user_nickname'] = $xin['nickname'] ;
        $yonghu['user_id'] = $xin['id'] ;
        $socket->roomdata = $msg['room_id'];
        //查询主播编号
        $num = $user->findOne($msg['room_id']);
        $number = $num['number'];
        $dataArr=[
            'room_id'=>$xin['id'],
            'code'=>200,
            'status'=>true,
            'message'=>'直播间被关闭',
            'type'=>'ban',
        ];
        $io->to($xin['id'])->emit('close', $dataArr);
        $socket->emit('close', $dataArr);

    });
    //警告正在直播中的主播
    $socket->on('warning', function($msg)use($io,$socket,$user,$userRoom){
        //临时获取用户信息
        $xin = $user->where(['number'=>$msg['number']])->one();
        $yonghu['user_number'] = $xin['number'] ;
        $yonghu['user_nickname'] = $xin['nickname'] ;
        $yonghu['user_id'] = $xin['id'] ;
        $socket->roomdata = $msg['room_id'];
        //查询主播编号
        $num = $user->findOne($msg['room_id']);
        $number = $num['number'];
        $dataArr=[
            'room_id'=>$xin['id'],
            'code'=>200,
            'status'=>true,
            'title'=>$msg['type'],
            'message'=>$msg['content'],
            'msg'=>'成功警告主播',
            'type'=>'warning',
        ];
        $io->to($xin['id'])->emit('warning', $dataArr);
        $socket->emit('warning', $dataArr);
    });
    //修改用户状态为无效
    $socket->on('state', function($msg)use($io,$socket,$user,$userRoom){
        //临时获取用户信息
        $xin = $user->where(['number'=>$msg['number']])->one();
        $yonghu['user_number'] = $xin['number'] ;
        $yonghu['user_nickname'] = $xin['nickname'] ;
        $yonghu['user_id'] = $xin['id'] ;
        $socket->roomdata = $msg['room_id'];
        //查询主播编号
        $num = $user->findOne($msg['room_id']);
        $number = $num['number'];
        $dataArr=[
            'code'=>200,
            'status'=>true,
            'msg'=>'用户被后台禁止登陆',
            'type'=>'state',
        ];
        $socket->emit('state', $dataArr);
    });
});
Worker::runAll();
