<?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;
use App\Model\User;
use App\Model\Room;
use App\Model\RoomUser;
use Ramsey\Uuid\Uuid;
use App\Jobs\Distribute;

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';
        $match_times = 0;
        //循环匹配
        while (1) {
            $user_id = Redis::lpop('match_list');
            if(!$user_id){
                if($match_times > 5){
                    $match_times = 0;
                    //获取是否有房间未满人
                    $room_id = $this->get_free_room();
                    if(!$room_id){
                        echo "未找到匹配房间\n";
                        continue;
                    }
                    //获取离线机器人
                    $user = User::inRandomOrder()->select('user_id','name')->where("is_robot",1)->where("is_login",0)->first();
                    if(!$user){
                        echo "没有离线机器人\n";
                        sleep(1);
                        continue;
                    }
                    //发布启动机器人
                    Redis::publish("startRobot", $user->user_id);
                }
                sleep(3);
                $match_times++;
                continue;
            }
            $match_times = 0;
            $info = [];
            $room_id = $this->get_free_room();
            $user = User::select('user_id', 'avatar', 'name', 'win_count', 'lose_count','client_id')->where("user_id", $user_id)->first();
            if($user->is_robot && !$user->is_login){
                if(Gateway::isUidOnline($user_id)){
                    //更新用户登陆状态
                    unset($update_data);
                    $update_data = [
                        "is_login" => 1,
                        "client_id" => $user->client_id,
                    ];
                    User::where("user_id", $user_id)->update($update_data);
                }else{
                    continue;
                }
            }
            if($room_id){
                //获取房间信息
                $room = Room::where("room_id", $room_id)->first();
                //把当前用户加入当前房间
                Gateway::joinGroup($user->client_id, $room_id);
                RoomUser::insert([
                    'user_id' => $user_id, 
                    'room_id' => $room_id, 
                    'state' => 1,
                    'created_at' => date('Y-m-d H:i:s'),
                    'updated_at' => date('Y-m-d H:i:s'),
                ]);
                if($user->win_count == 0 || ($user->win_count == 0 && $user->lose_count == 0)){
                    $win_rate = 0;
                }else{
                    $win_rate = $user->win_count / ($user->win_count + $user->lose_count);
                }
                $info['user'] = [
                    "user_id" => $user_id,
                    "name" => $user->name,
                    "avatar" => $user->avatar,
                    "win_rate" => $win_rate,
                ];
                //获取房间玩家信息
                $group_users = Gateway::getUidListByGroup($room_id);
                if(count($group_users) > 0 && count($group_users) < $room->user_limit){
                    //清理不在房间的用户
                    RoomUser::whereNotIn('user_id', array_values($group_users))->delete();
                }
                $info['players'] = User::select('user_id', 'avatar', 'name', 'win_count', 'lose_count')->whereIn("user_id", array_values($group_users))->get();
                //发送可以开始消息
                $message = [
                    "type" => 'player_join',
                    "msg" => "玩家加入房间",
                    "info" => $info
                ];
                Gateway::sendToGroup($room_id, json_encode($message));
                echo "玩家加入房间: {$user_id}\n";
                //判断对战是否开启标志
                if(count($group_users) == $room->user_limit){
                    unset($update_data);
                    $update_data['is_full'] = 1;
                    $update_data['start_at'] = date('Y-m-d H:i:s');
                    Room::where("room_id", $room_id)->update($update_data);
                }

                //执行发题
                Distribute::dispatch($room_id)->onQueue('distribute');
                
                //发送题目
                // $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 = Room::insertGetId([
                    'title' => 'room_' . $user->name . date('YmdHis'),
                    'is_full' => 0,
                    'is_end' => 0,
                    'user_limit' => 2,
                    'nickname' => $user->name,
                    'user_id' => $user_id,
                    'created_at' => date('Y-m-d H:i:s'),
                    'updated_at' => date('Y-m-d H:i:s'),
                ]);
                RoomUser::insert([
                    "user_id" => $user_id,
                    "room_id" => $room_id,
                    "state" => 1,
                    'created_at' => date('Y-m-d H:i:s'),
                    'updated_at' => date('Y-m-d H:i:s'),
                ]);
                //把当前用户加入当前房间 保险点获取用户最新 client_id
                Gateway::joinGroup($user->client_id, $room_id);
                echo "玩家新建房间: {$user_id}\n";
                if($user->win_count == 0 || ($user->win_count == 0 && $user->lose_count == 0)){
                    $win_rate = 0;
                }else{
                    $win_rate = $user->win_count / ($user->win_count + $user->lose_count);
                }
                //当前用户信息
                $info['user'] = [
                    "user_id" => $user_id,
                    "name" => $user->name,
                    "avatar" => $user->avatar,
                    "win_rate" => $win_rate,
                ];
                //获取房间玩家信息
                $group_users = Gateway::getUidListByGroup($room_id);
                $info['players'] = User::select('user_id', 'avatar', 'name', 'win_count', 'lose_count')->whereIn("user_id", array_values($group_users))->get();
                //发送可以开始消息
                $message = [
                    "type" => 'player_join',
                    "msg" => "玩家加入房间",
                    "info" => $info
                ];
                Gateway::sendToGroup($room_id, json_encode($message));
            }
        }
    }

    /**
     * 获取正在匹配的房间
     */
    public function get_free_room()
    {
        //注册地址
        Gateway::$registerAddress = '127.0.0.1:1238';
        while (1) {
            $room = Room::select("room_id")->where("is_full",0)->where("is_end","<>",1)->first();
            if($room){
                $users = RoomUser::select("user_id")->where("room_id", $room->room_id)->where("state", 1)->get();
                foreach ($users as $user) {
                    //检查当前room玩家是否还在房间中
                    $is_online = Gateway::isUidOnline($user->user_id);
                    if(!$is_online){
                        //把当前房间关闭
                        $update_data["is_end"] = 1;
                        $update_data["end_at"] = date('Y-m-d H:i:s');
                        Room::where("room_id", $room->room_id)->update($update_data);
                        unset($update_data);
                        //取消用户在房间的状态
                        $update_data['state'] = 2;
                        RoomUser::where([
                            "room_id" => $room->room_id, 
                            "user_id" => $user->user_id,
                        ])->update($update_data);
                        continue;
                    }
                }
                return $room->room_id;
            }else{
                return false;
            }
        }
    }

}
