<?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 Illuminate\Support\Facades\Redis;
use App\Model\Question;
use App\Model\Option;
use App\Model\RoomQuestion;
use GatewayWorker\Lib\Gateway;

class Distribute 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()
    {
        if(!$this->room_id){
            echo "找不到房间ID";
            return 0;
        }
        //获取当前房间是否还有未结算题目
        $has_not_settlement_question = RoomQuestion::where("room_id", $this->room_id)->whereNull("end_at")->count();
        if($has_not_settlement_question){
            echo "当前房间还有未结算题目";
            return 0;
        }
        //获取当前房间题目数
        $questions_id = RoomQuestion::where("room_id", $this->room_id)->pluck("question_id");
        if(count($questions_id) < 5){
            //注册地址
            Gateway::$registerAddress = '127.0.0.1:1238';
            //获取题目
            $question = Question::inRandomOrder()->select('question_id','title')->where("is_released",1)->whereNotIn("question_id", $questions_id)->first();
            $options = Option::select('option_id','title')->where("question_id",$question->question_id)->get($question->question_id);
            //记录题目
            $date = date('Y-m-d H:i:s');
            $next_date = date('YmdHis', strtotime("{$date} +10 seconds"));
            RoomQuestion::insert([
                "room_id" => $this->room_id,
                "question_id" => $question->question_id,
                "title" => $question->title,
                "start_at" => $date,
                "created_at" => $date,
                "updated_at" => $date,
            ]);
            //发送题目
            $info['question'] = $question; 
            $info['options'] = $options; 
            $info['start_at'] = $date; 
            $message = [
                "type" => 'question',
                "msg" => "获取题目成功",
                "info" => $info,
            ];
            echo "发送题目到房间 {$this->room_id} \n";
            Gateway::sendToGroup($this->room_id, json_encode($message));
            //设置下次结算固定时间
            $room_list = Redis::rpush("Game_settlement_{$next_date}", $this->room_id);
        }
    }
}
