<?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 Illuminate\Support\Facades\Redis;

class GameController extends Controller
{

    /**
     * 获取问题
     */
    public function Question(Request $request)
    {
        if(!$request->session()->has('user_id')){
            $response['code'] = 400;
            $response['msg'] = '请先登录';
            return response()->json($response);
        }
        $room_id = $request->input('room_id');
        if(!$room_id){
            $response['code'] = 400;
            $response['msg'] = '缺少房间参数';
            return response()->json($response);
        }
        //第几题
        $cur_question = $request->input('cur_question');
        if(!$cur_question){
            $cur_question = 1;
        }
        //防止并发问题加文件锁
        $Lock_file = "{$room_id}_lock_file.txt";
        $i = 1;
        while ($i < 30) {
            $fp = fopen($Lock_file, "a+");
            if($fp===false){
                sleep(1);
            }else{
                flock($fp,LOCK_EX);//获取独占锁
            }
            $i++;
        }
        //获取当前房间问题
        $questions = Redis::get($room_id . '_questions');
        if($questions){
            $questions = json_decode($questions);
        }else{
            $questions = [];
        }
        if(isset($questions[$cur_question -1])){
            $response['info'] = $questions[$cur_question - 1];
        }else{
            $questions_id = [];
            foreach ($questions as $k => $v) {
                $questions_id[] = $v->question->question_id;
            }
            // $questions_id = array_column($questions, 'question_id');
            $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);
            $info['question'] = $question; 
            $info['options'] = $options; 
            $info['questions_count'] = count($questions) + 1; 
            $questions[] = $info;
            Redis::set($room_id . '_questions', json_encode($questions));
            $response['info'] = $info;
        }

        //解锁
        if($fp!==false){
            @flock($fp,LOCK_UN);
            clearstatcache();
        }
        @fclose($fp);
        @unlink($Lock_file);

        //设置返回数据
        $response['code'] = 0;
        $response['msg'] = '获取成功';
        return response()->json($response);
    }

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

        $message['is_end'] = 0;  //是否结束答题标志
        $question_id = $request->input('question_id');
        $option_id = $request->input('option_id');
        $user_id = $request->session()->get('user_id');

        //检测用户断线
        Gateway::$registerAddress = '127.0.0.1:1238';
        //获取当前用户session
        $client_ids = Gateway::getClientIdByUid($user_id);
        $gateway_user = Gateway::getSession($client_ids[0]);
        $room_id = $gateway_user['room_id'];

        if(!$room_id){
            $response['code'] = 400;
            $response['msg'] = '缺少房间参数';
            return response()->json($response);
        }


        //获取当前房间问题条数
        $questions = Redis::get($room_id . '_questions');
        if($questions){
            $questions = json_decode($questions);
            $questions_count = count($questions);
        }else{
            $questions_count = 0;
        }
        //获取当前组存活用户
        $clients = Gateway::getUidListByGroup($room_id);
        if(count($clients) < 2){
          $message['is_end'] = 1;
        }

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

        $scores = Redis::get($room_id.'_info');
        if($scores){
          $scores = json_decode($scores, 1);
        }else{
          $scores = [];
        }
        if(!isset($scores[$user_id])){
          $scores[$user_id] = 0;
        }

        if($is_true  && !isset($scores['questions'][$question_id][$user_id])){
            $scores[$user_id] = (int) $scores[$user_id] + 1;
        }
        $scores['questions'][$question_id][$user_id] = $is_true; 

        Redis::set($room_id . '_info', json_encode($scores));
        $message['is_true'] = $is_true;
        $message['scores'] = $scores;
        $message['user_id'] = $user_id;
        $message['online'] = count($clients);
        $message['type'] = 'answer';
        $message['cur_quc'] = count($scores['questions'][$question_id]);
        
        //问题超过或者到第4条为结束标志
        if($questions_count > 4 && $message['cur_quc'] > 1){
          $message['is_end'] = 1;
        }

        //发送消息
        Gateway::sendToGroup($room_id, json_encode($message));
        $response['code'] = 0;
        $response['msg'] = '回答成功';

        //发送题目
        if($message['is_end'] != 1 && $message['cur_quc'] > 1){
            $questions_id = [];
            foreach ($questions as $k => $v) {
                $questions_id[] = $v->question->question_id;
            }
            $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);
            $info['question'] = $question; 
            $info['options'] = $options; 
            $info['questions_count'] = $questions_count + 1;
            $questions[] = $info;
            Redis::set($room_id . '_questions', json_encode($questions));
            $message = [
                "type" => 'question',
                "msg" => "获取题目成功",
                "info" => $info,
            ];
            Gateway::sendToGroup($room_id, json_encode($message));
        }

        //用户退出房间关闭房间等逻辑 todo ...
        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');
        $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::lpush('match_list',$data);

        $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);
    }
  

}