<?php

namespace App\Home\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use GatewayWorker\Lib\Gateway;

class UserController extends Controller
{

    /**
     * 用户首页
     */
    public function Index(Request $request)
    {
        if(!$request->session()->has('user_id')){
            return redirect('Home/User/Login');
        }
        return view('home.user');
    }

    /**
     * 登陆页面
     */
    public function Login(Request $request)
    {
        if($request->session()->has('user_id')){
            return redirect('Home/User/Index');
        }
        return view('home.login');
    }

    /**
     * 登陆
     */
    public function doLogin(Request $request)
    {
        if(!$request->session()->has('user_id')){
            $user_id = uniqid();
            $request->session()->put('user_id', $user_id);
        }else{
            $user_id = $request->session()->get('user_id');
        }

        $username = $request->input('username');
        $user_id = $request->session()->get('user_id');
        $request->session()->put('username', $username);
        $avatar = rand(1,4);
        $request->session()->put('avatar', "/img/tx{$avatar}.jpg");

        $response['code'] = 0;
        $response['msg'] = '登陆成功';
        return response()->json($response);
    }

    /**
     * 获取用户信息
     */
    public function Info(Request $request)
    {
        if(!$request->session()->has('user_id')){
            $response['code'] = 400;
            $response['msg'] = '请先登录';
            return response()->json($response);
        }
        
        $data['user_id'] = $request->session()->get('user_id');
        $data['username'] = $request->session()->get('username');
        $data['avatar'] = $request->session()->get('avatar');
        $response['code'] = 0;
        $response['info'] = $data;
        $response['msg'] = '获取成功';
        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';
        $client_ids = Gateway::getClientIdByUid($user_id);
        if(count($client_ids) > 1){
            $response['code'] = 400;
            $response['msg'] = '禁止多个客户端链接';
            return response()->json($response);
        }
        // client_id与uid绑定
        Gateway::bindUid($client_id, $user_id);
        if($request->session()->has('room_id')){
            $room_id = $request->session()->get('room_id');
            Gateway::joinGroup($client_id, $room_id);
        }
        $response['code'] = 0;
        $response['msg'] = '服务连接成功';
        return response()->json($response);
    }

}