<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use GatewayWorker\Lib\Gateway;
use Illuminate\Support\Facades\Redis;
use App\Model\Question;
use App\Model\Option;

class gamematch extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'game:match';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '启动游戏匹配';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //注册地址
        Gateway::$registerAddress = '127.0.0.1:1238';
        //循环匹配
        while (1) {
            $data = Redis::lpop('match_list');
            if(!$data){
                echo "未找到匹配\n";
                sleep(1);
                continue;
            }
            $data = json_decode($data, 1);
            $room = Redis::get($data['level']);
            if($room){
                Redis::del($data['level']);
                $room = json_decode($room, 1);
                //获取玩家ClientID
                if($room['client_id'] == $data['client_id'] || $room['user_id'] == $data['user_id']){
                    continue;
                }
                // $player_1_ = Gateway::getClientIdByUid($room['uid']);
                Gateway::joinGroup($room['client_id'], $room['room_id']);
                // $player_2 = Gateway::getClientIdByUid($data['uid']);
                Gateway::joinGroup($data['client_id'], $room['room_id']);
                //组合玩家信息
                $players = [
                    $data,
                    $room
                ];
                //发送可以开始消息
                $message = [
                    "type" => 'match',
                    "msg" => "匹配成功",
                    "info" => ['room_id'=>$room['room_id'],"players"=>$players],
                ];
                //清理房间数据
                Redis::set($room['room_id'] . '_info','');
                Redis::set($room['room_id'] . '_questions','');
                Gateway::sendToGroup($room['room_id'], json_encode($message));
                echo "匹配成功: {$data['client_id']} 、 {$room['client_id']}\n";

                //设置session
                Gateway::setSession($room['client_id'], ['room_id'=>$room['room_id']]);
                Gateway::setSession($data['client_id'], ['room_id'=>$room['room_id']]);

                //发送题目
                $question = Question::inRandomOrder()->select('question_id','title')->where("is_released",1)->first();
                $options = Option::select('option_id','title')->where("question_id",$question->question_id)->get($question->question_id);
                $info['question'] = $question; 
                $info['options'] = $options; 
                $info['questions_count'] = 1;
                $questions[] = $info;
                Redis::set($room['room_id'] . '_questions', json_encode($questions));
                $message = [
                    "type" => 'question',
                    "msg" => "获取题目成功",
                    "info" => $info,
                ];
                Gateway::sendToGroup($room['room_id'], json_encode($message));
                echo "发送题目成功: {$room['room_id']}\n";
            }else{
                //新建一个房间
                $room_id = $this->get_room_id();
                $room = ['room_id'=>$room_id, "user_id"=>$data['user_id'], "avatar"=>$data['avatar'], "username"=>$data['username'],'client_id'=>$data['client_id']]; 
                Redis::set($data['level'], json_encode($room));
            }
        }
    }

    public function get_room_id()
    {
        while (1) {
            $room_id = 'room_' . rand(10000,99999);
            $count = Gateway::getUidCountByGroup($room_id);
            if(!$count){
                return $room_id;
            }
        }
    }

}
