<?php

namespace App\Home\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use GatewayWorker\Lib\Gateway;
use App\Model\Question;
use App\Model\Option;
use App\Model\RoomUser;
use App\Model\RoomQuestion;
use App\Model\RoomAnswer;
use App\Model\Room;
use Illuminate\Support\Facades\Redis;
use App\Jobs\Settlement;

class GameController extends Controller
{

    /**
     * 回答问题
     */
    public function Answer(Request $request)
    {
        if(!$request->session()->has('user_id')){
            $response['code'] = 400;
            $response['msg'] = '请先登录';
            return response()->json($response);
        }

        $answer_time = time();
        $question_id = $request->input('question_id');
        $option_id = $request->input('option_id');
        $user_id = $request->session()->get('user_id');

        //注册gateway地址
        Gateway::$registerAddress = '127.0.0.1:1238';
        //获取房间号
        $room_id = RoomUser::where(["user_id"=>$user_id,"state"=>1])->value('room_id');

        if(!$room_id){
            $response['code'] = 400;
            $response['msg'] = '没有加入房间';
            return response()->json($response);
        }

        //判断答案逻辑
        $is_true = Option::where([
          ["question_id", $question_id],
          ["option_id", $option_id],
          ["is_answer", 1],
        ])->count();

        //判断用户回答获取分数
        if($is_true){
            //获取当前题目开始时间
            $start_at = RoomQuestion::where(["question_id" => $question_id, "room_id" => $room_id])->value('start_at');
            $answer_diff = $answer_time - strtotime($start_at);
            switch ($answer_diff) {
                case '0':
                    $score = 100;
                    break;
                case '1':
                    $score = 90;
                    break;
                case '2':
                    $score = 80;
                    break;
                case '3':
                    $score = 70;
                    break;
                case '4':
                    $score = 60;
                    break;
                case '5':
                    $score = 50;
                    break;
                case '6':
                    $score = 40;
                    break;
                case '7':
                    $score = 30;
                    break;
                case '8':
                    $score = 20;
                    break;
                case '9':
                    $score = 10;
                    break;
                default:
                    $score = 0;
                    break;
            }
        }else{
            $score = 0;
        }

        //写入记录
        $result = RoomAnswer::insert([
            "question_id" => $question_id,
            "option_id" => $option_id,
            "user_id" => $user_id,
            "room_id" => $room_id,
            "score" => $score,
            "created_at" => date('Y-m-d H:i:s'),
            "updated_at" => date('Y-m-d H:i:s'),
        ]);

        if(!$result){
            //发送消息
            $response['code'] = 400;
            $response['msg'] = '重复回答';
            return response()->json($response);
        }

        if($score){
            //增加总分
            RoomUser::where([
                "user_id" => $user_id,
                "room_id" => $room_id,
            ])->increment('score', $score);
        }

        $message['score'] = $score;
        $message['user_id'] = $user_id;
        $message['type'] = 'answer';
        Gateway::sendToGroup($room_id, json_encode($message));

        //获取房间信息，最后一个回答触发结算程序
        $room_user_limit = Room::where("room_id", $room_id)->value("user_limit");
        //获取当前题目回答人数
        $answer_user_count = RoomAnswer::where([
            "room_id" => $room_id,
            "question_id" => $question_id,
        ])->count();
        if($room_user_limit == $answer_user_count){
            if(!isset($start_at)){
                $start_at = RoomQuestion::where(["question_id" => $question_id, "room_id" => $room_id])->value('start_at');
            }
            $next_date = date('YmdHis', strtotime("{$start_at} +10 seconds"));
            //先删除固定结算任务队列
            Redis::lrem("Game_settlement_{$next_date}", 1, $room_id);
            //执行结算队列
            Settlement::dispatch($room_id)->onQueue('settlement');
        }

        //发送消息
        $response['code'] = 0;
        $response['msg'] = '回答成功';
        //返回回答信息
        return response()->json($response);
    }

    /**
     * 加入房间
     */
    public function Join(Request $request)
    {
        if(!$request->session()->has('user_id')){
            $response['code'] = 400;
            $response['msg'] = '请先登录';
            return response()->json($response);
        }

        $user_id = $request->session()->get('user_id');
        //检查是否在房间中
        $is_in_room = RoomUser::where("user_id", $user_id)->where("state", 1)->count();
        if($is_in_room){
            $response['code'] = 400;
            $response['msg'] = "已在房间中";
            return response()->json($response);
        }
        //删除队列再加入匹配
        Redis::lrem('match_list', 1, $user_id);
        Redis::rpush('match_list', $user_id);

        $response['code'] = 0;
        $response['msg'] = "已加入匹配队列";
        return response()->json($response);
    }

    /**
     * 取消匹配
     */
    public function Quit(Request $request)
    {
        if(!$request->session()->has('user_id')){
            $response['code'] = 400;
            $response['msg'] = '请先登录';
            return response()->json($response);
        }
        $username = $session->get('username');
        $avatar = $session->get('avatar');

        $user_id = $request->session()->get('user_id');
        $username = $request->session()->get('username');
        $avatar = $request->session()->get('avatar');
        $client_id = $request->input('client_id');
        $data = json_encode(['user_id'=>$user_id,'level'=>'T1','avatar'=>$avatar,'username'=>$username,'client_id'=>$client_id]);
        Redis::lrem('match_list',1,$data);
        //删除房间
        Redis::del('T1');
        
        $response['code'] = 0;
        $response['msg'] = "已取消匹配";
        return response()->json($response);
    }
  

}