<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use App\Model\Option;
use App\Model\User;
use App\Model\Room;
use App\Model\RoomUser;
use App\Model\RoomAnswer;
use App\Model\RoomQuestion;
use App\Jobs\Distribute;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Redis;
use GatewayWorker\Lib\Gateway;

class Settlement implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $room_id;     //房间ID

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($room_id)
    {
        $this->room_id = $room_id;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        //获取当前房间回答情况
        $question_id = RoomQuestion::where("room_id", $this->room_id)->whereNull("end_at")->value("question_id");
        if(!$question_id){
            echo "找不到题目";
            return 0;
        }
        //获取当前房间获取问题数
        $room_question_count = RoomQuestion::where("room_id", $this->room_id)->count();
        //注册gateway地址
        Gateway::$registerAddress = '127.0.0.1:1238';
        //进行结算
        if($room_question_count > 4){

            //结算当前局
            $update_data["end_at"] = date("Y-m-d H:i:s");
            RoomQuestion::where([
                "room_id" => $this->room_id,
                "question_id" => $question_id,
            ])->update($update_data);

            //当前房间结束
            $update_data["is_end"] = 1;
            $update_data["end_at"] = date("Y-m-d H:i:s");
            Room::where("room_id", $this->room_id)->update($update_data);
            //获取胜利者
            $players = RoomUser::select("user_id","score")->where([
                "room_id" => $this->room_id,
            ])->get();
            $winer = '';
            $winer_score = 0;
            foreach ($players as $k => $player) {
                if($player->score > $winer_score){
                    $winer = $player->user_id;
                    $winer_score = $player->score;
                }
            }
            //通知卓望平台跟用户端
            foreach ($players as $k => $player) {
                $is_win = 0;
                //获取用户令牌
                $user = User::where("user_id", $player->user_id)->first();
                if($winer == $player->user_id){
                    //更新胜利局数
                    User::where("user_id", $player->user_id)->increment('win_count', 1);
                    $is_win = 1;
                }else{
                    User::where("user_id", $player->user_id)->increment('lose_count', 1);
                }
                
                //更新用户在房间的信息
                unset($update_data);
                $update_data['state'] = 2;
                $update_data['is_win'] = $is_win;
                $update_data['updated_at'] = date("Y-m-d H:i:s");
                RoomUser::where([
                    "user_id" => $player->user_id,
                    "room_id" => $this->room_id,
                ])->update($update_data);

                //非机器人上传游戏得分
                if($user->is_robot != 1){
                    $client = new Client([
                        'verify' => false,
                    ]);
                    $ip = '211.139.191.175';
                    $port = '38083';
                    $req_time = date('YmdHis');
                    $sign = md5($user->cmcc_id . $req_time . $user->mt);
                    $params['req_param'] = [
                        "pub_info" => [
                            "req_src" => 1,
                            "ver" => "1.0",
                            "req_time" => $req_time,
                            "sign" => $sign,
                        ],
                        "page_info" => [
                            "current_page" => 1,
                            "page_size" => 10,
                        ],
                        "busi_info" => [],
                    ];
                    // $response = $client->request('POST', "http://{$ip}:{$port}/hgs/biz/pktaskresult",[
                    //     'form_params' => [
                    //         'username' => $user->name,
                    //     ]
                    // ]);
                    // $result = $response->getBody()->getContents();
                }

                //测试固定用户信息
                $info['user_id'] = $user->user_id;
                $info['name'] = $user->name;
                $info['avatar'] = $user->avatar;
                $info['is_win'] = $is_win;
                $info['play_next'] = 1;

                //获取用户星力变化等信息返回
                $message['info'] = $info;
                $message['winer'] = $winer;
                $message['winer_score'] = $winer_score;
                $message['type'] = 'game_end';
                Gateway::sendToUid($user->user_id, json_encode($message));
                //结束当前房间
                Gateway::ungroup($this->room_id);
            }

        }else{

            //结算当前局
            $update_data["end_at"] = date("Y-m-d H:i:s");
            RoomQuestion::where([
                "room_id" => $this->room_id,
                "question_id" => $question_id,
            ])->update($update_data);

            //返回各个用户回答的问题
            $group_users = Gateway::getUidListByGroup($this->room_id);
            $anwsers = RoomAnswer::select('user_id', 'option_id', 'question_id')->where([
                "question_id" => $question_id,
                "room_id" => $this->room_id,
            ])->whereIn("user_id", array_values($group_users))->get();
            $option_id = Option::where([
                "question_id" => $question_id,
                "is_answer" => 1,
            ])->value("option_id");
            $info['anwser'] = $option_id;
            $info['players_answer'] = $anwsers;
            //发送回合结算信息
            $message['info'] = $info;
            $message['type'] = 'round_end';
            Gateway::sendToGroup($this->room_id, json_encode($message));
            sleep(3);
            //执行发题
            Distribute::dispatch($this->room_id)->onQueue('distribute');
        }
    }
}
