<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Model\Question;
use App\Model\Option;
use App\Model\User;
use App\Model\RoomUser;
use GuzzleHttp\Client;
use GuzzleHttp\Cookie\CookieJar;
use Workerman\Worker;
use Workerman\Connection\AsyncTcpConnection;
use Illuminate\Support\Facades\Redis;
use GatewayWorker\Lib\Gateway;

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

    /**
     * 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()
    {
        //获取机器人信息
        $user_id = $this->argument('user_id');
        if(!$user_id){
            $user = User::inRandomOrder()->select('user_id','name')->where("is_robot", 1)->where("is_login", 0)->first();
        }else{
            // $user = User::select('user_id','name')->where("is_robot",1)->where("user_id", $user_id)->where("is_login",0)->first();
            $user = User::select('user_id','name')->where("is_robot",1)->where("user_id", $user_id)->first();
        }
        if(!$user){
            echo "未找到机器人";
            die;
        }
        $worker = new Worker();
        $worker->onWorkerStart = function($worker) use($user){
            //定义基本信息
            $http_addr = 'http://183.234.61.252:8090/';
            // $http_addr = 'http://www.dt.com/';
            //定义请求客户端
            $room_id = ''; //定义当前机器人加入的room_id
            $client_id = ''; //定义当前机器人client_id
            $client = new Client([
                'cookies' => true,
                'verify' => false,
            ]);
            $response = $client->request('GET', $http_addr . 'Home/User/Info', [
                'query' => [
                    'user_id' => $user->user_id,
                    'mt' => 1,
                ]
            ]);
            // $robot = $response->getBody()->getContents();

            $con = new AsyncTcpConnection('ws://183.234.61.252:8282');
            // $con = new AsyncTcpConnection('ws://127.0.0.1:8282');
            $con->onConnect = function($con) use($client) {
            };
            $con->onMessage = function($con, $data) use($client, &$room_id, &$client_id, $user, $http_addr, $worker){
                //注册地址
                Gateway::$registerAddress = '127.0.0.1:1238';
                //格式化参数
                $json_data = json_decode($data);
                //初始化
                if($json_data->type == 'init'){
                    $client_id = $json_data->client_id;
                    $response = $client->request('POST', $http_addr . 'Home/User/Bind', [
                        'form_params' => [
                            'client_id' => $client_id,
                        ]
                    ]);
                    $result = json_decode($response->getBody()->getContents());
                    if($result->code == 400 || ($result->code == 0 && $result->info->in_game == 1)){
                        echo "断线重连中 ...";
                        return 0;
                    }
                    echo "client: {$client_id} 成功绑定socket\n";
                    $update_data = [
                        "is_login" => 1,
                        "client_id" => $client_id,
                    ];
                    //更新机器人登陆状态
                    User::where("user_id", $user->user_id)->update($update_data);
                    //启动匹配
                    $response = $client->request('GET', $http_addr . 'Home/Game/Join',[
                        'form_params' => [
                            'client_id' => $client_id,
                        ]
                    ]);
                    echo "{$client_id} 成功加入匹配\n";
                }
                //唤起匹配
                if($json_data->type == 'gotomatch'){
                    $response = $client->request('POST', $http_addr . 'Home/Game/Join',[
                        'form_params' => [
                            'client_id' => $client_id,
                        ]
                    ]);
                    echo "{$client_id} 成功加入匹配\n";
                }

                //匹配成功
                if($json_data->type == 'match'){
                    $room_id = $json_data->info->room_id;
                    echo "{$client_id} 成功加入 {$room_id} \n";
                }
                //获得题目
                if($json_data->type == 'question'){
                    $question_id = $json_data->info->question->question_id;
                    $options = $json_data->info->options;
                    $answer = rand(0, count($json_data->info->options) - 1);
                    //随机几秒回答问题
                    $second = rand(0,6);
                    sleep($second);
                    echo "获得题目 {$json_data->info->question->question_id} ： {$json_data->info->question->title}\n";
                    $response = $client->request('POST', $http_addr . 'Home/Game/Answer',[
                        'form_params' => [
                            'question_id' => $question_id,
                            'option_id' => $options[$answer]->option_id,
                        ]
                    ]);
                }

                //结算
                if($json_data->type == 'round_end'){
                    echo "回合结束，已结算";
                }

                //结算
                if($json_data->type == 'game_end'){
                    $update_data = [
                        "is_login" => 0,
                        "client_id" => '',
                    ];
                    //更新机器人登陆状态
                    User::where("user_id", $user->user_id)->update($update_data);
                    unset($update_data);
                    $update_data['state'] = 2;
                    RoomUser::where("user_id", $user->user_id)->where("state", 1)->update($update_data);
                    echo "已结算，关闭机器人";
                    Gateway::leaveGroup($client_id, $room_id);
                    Gateway::unbindUid($client_id, $user->user_id);
                    Gateway::closeClient($client_id);
                    $worker->stopAll();
                }

            };
            $con->connect();
        };

        Worker::runAll();
    }
}
