<?php

namespace App\Home\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use GatewayWorker\Lib\Gateway;
use GuzzleHttp\Client;
use App\Model\User;
use App\Model\Room;
use App\Model\RoomUser;
use ErrorException;

class UserController extends Controller
{

    /**
     * 获取用户信息
     */
    public function Info(Request $request)
    {
        $cmcc_id = $request->input('user_id');
        $mt = $request->input('mt');
        if(!$cmcc_id || !$mt){
            $response['code'] = 400;
            $response['msg'] = '缺少参数';
            return response()->json($response);
        }

        //获取当前系统是否存在
        $user = User::select('user_id', 'avatar', 'name', 'win_count', 'lose_count')->where("cmcc_id", $cmcc_id)->orWhere("user_id", $cmcc_id)->first();
        if(!$user){
            //请求用户信息
            $client = new Client([
                'verify' => false,
            ]);
            $ip = '211.139.191.175';
            $port = '38083';
            $req_time = date('YmdHis');
            $sign = md5($cmcc_id . $req_time . $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/uc/queryusergameinfo",[
            //     'form_params' => [
            //         'username' => $user->name,
            //     ]
            // ]);
            // $cmcc_user = $response->getBody()->getContents();

            //判断请求结果 todo ...

            //记录用户信息
            $date = date("Y-m-d H:i:s");
            $user_id = User::insertGetId([
                "name" => "测试用户_" . $cmcc_id,
                "avatar" => "https://picsum.photos/200/200/?image=". rand(1, 300),
                "cmcc_id" => $cmcc_id,
                "mt" => $cmcc_id,
                "win_count" => 0,
                "lose_count" => 0,
                "is_login" => 0,
                "is_robot" => 0,
                "created_at" => $date,
                "updated_at" => $date,
            ]);
            $user = User::select('user_id', 'avatar', 'name', 'win_count', 'lose_count')->where("cmcc_id", $cmcc_id)->first();
        }     

        if($user->win_count == 0 || ($user->win_count == 0 && $user->lose_count == 0)){
            $win_rate = 0;
        }else{
            $win_rate = $user->win_count / ($user->win_count + $user->lose_count);
        }

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

        //设置session
        $request->session()->put('user_id', $user->user_id);
        $response['code'] = 0;
        $response['msg'] = '获取用户信息成功';
        $response['info'] = $info;
        return response()->json($response);
    }

    /**
     * 绑定Socket
     */
    public function Bind(Request $request)
    {
        if(!$request->session()->has('user_id')){
            $response['code'] = 400;
            $response['msg'] = '请先登录';
            return response()->json($response);
        }

        $user_id = $request->session()->get('user_id');
        $client_id = $request->input('client_id');
        //注册地址
        Gateway::$registerAddress = '127.0.0.1:1238';
        //异地登录机制
        $user = User::where("user_id", $user_id)->first();
        // var_dump($user,$client_id);exit;
        if($user->client_id && $user->client_id != $client_id){
            $message = [
                "type" => "replace_login",
                "msg" => "用户在其他地方登录了，当前用户端断开连接",
            ];
            try {
                $is_online = Gateway::isOnline($user->client_id);
                if($is_online){
                    Gateway::sendToClient($user->client_id, json_encode($message));
                    //断开旧ID
                    Gateway::closeClient($user->client_id);
                }
            } catch (ErrorException $e) {
                
            }
        }
        //绑定用户ID
        Gateway::bindUid($client_id, $user_id);
        //更新用户最新client_id
        $update_data['client_id'] = $client_id;
        User::where("user_id", $user_id)->update($update_data);
        $response['info']['in_game'] = 0;   //是否还在对战中
        //判断用户是否还在对战
        $room_id = RoomUser::where([
            "user_id" => $user_id,
            "state" => 1,
        ])->value("room_id");
        //查看房间状态
        $is_end = Room::where("room_id", $room_id)->value("is_end");
        if($room_id && !$is_end){
            Gateway::joinGroup($client_id, $room_id);
            $response['info']['in_game'] = 1;
        }elseif($room_id && $is_end){
            unset($update_data);
            $update_data['state'] = 2;
            //更新一下房间状态
            RoomUser::where([
                "user_id" => $user_id,
                "room_id" => $room_id,
                "state" => 1,
            ])->update($update_data);
        }

        $response['code'] = 0;
        $response['msg'] = '服务连接成功';
        return response()->json($response);
    }

}