<?php

namespace App\Game\Services;

use App\Util;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;

class ServerService
{
    static $example=[
        'Bangladesh'=>'',
        'Pakistan'=>'',
        'Latin'=>'',
        'OrgBrazil'=>'',
        'Brazil'=>'',
        'Europe'=>'',
        'Russia'=>'',
        'Mexico'=>'',
        'Singapore'=>''
    ];
    static $codeToServer = [
        'eb1a' => [
            'Subsite'      => 'Brazil',
            'Country'      => 'Brazil',
            'Currency'     => 'BRL',
            'Lang'         => 'pt',
            'ServerRegion' => 'sa-east',
            'Api'          => 'https://testapi.usgamewin.com'
        ],
    ];

    public static function GetGlobalServerInfoByCode($code)
    {

        return self::$codeToServer[$code] ?? self::$codeToServer['90dd'];
    }

    public static function GetGlobalServerInfoBySubsite($subsite)
    {
        foreach (self::$codeToServer as $code => $server) {
            if ($server['Subsite'] == $subsite) {
                return $server;
            }
        }
        return self::$codeToServer['eb1a'];
    }

    public static function IsLocalUser($GlobalUID)
    {
        return self::GetGlobalServerInfoByGUID($GlobalUID)['ServerRegion'] == env('REGION_24680', 'sa-east');
    }

    /**
     * @param $GlobalUID
     * @return string[]
     */
    public static function GetGlobalServerInfoByGUID($GlobalUID)
    {

        ////"917c74999c-b53b-eb1a-0004478930"


        $codes = explode("-", $GlobalUID);
        $config = @self::$codeToServer[$codes[2]];
        if(!$config)return self::$codeToServer['eb1a'];
        return $config;

    }

    public static function GetApiByGUID($GlobalUID)
    {
        return self::GetGlobalServerInfoByGUID($GlobalUID)['Api'];
    }

    public static function GlobalToUserID($GlobalUID)
    {
        return intval(explode('-', $GlobalUID)[3]);
    }

    public static function GetLocalSign()
    {
        return substr(md5(env('REGION_24680', 'sa-east')),0,4);
    }
    public static function RedirectToSub($GlobalUID)
    {

        $apiurl = self::GetApiByGUID($GlobalUID);

        // 获取当前请求的 GET 和 POST 数据
//            $getData = $request->query(); // 获取 GET 数据
        $postData = $_POST; // 获取 POST 数据
        $client = new Client();

        $response = $client->post($apiurl . $_SERVER['REQUEST_URI'], [
            'verify'=>false,
            'form_params' => $postData, // 传递 POST 数据//                'query' => $getData, // 传递 GET 数据
        ]);
        $res = json_decode($response->getBody(), true);
//            Util::WriteLog('subserver',$res);
        return $res;

    }

}
