<?php

namespace App\Http\Controllers\Game;


use App\Game\BetBy\ErrorItem;
use App\Game\BetBy\PlayerDetails;
use App\Game\GlobalUserInfo;
use App\Game\Services\BetbyService;
use App\Game\Services\OuroGameService;
use App\Game\Services\PlatformService;
use App\Game\Services\ServerService;
use App\Notification\TelegramBot;
use App\Util;
use App\Utility\SetNXLock;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;
use App\Game\BetBy\TransactionItem;
use App\Game\BetBy\BetSlipItem;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class BetbyCenterController extends Controller
{
    protected $betbyService;
    protected $client;
    public function __construct(BetbyService $betbyService)
    {
        $this->client = new Client();
        $this->betbyService = $betbyService;
    }

    /**
     * Ping接口
     * 该方法用于检查服务的连通性。它返回当前服务器时间戳。
     *
     * @return JsonResponse
     */
    public function ping()
    {
//        $this->telLog($_SERVER);
        return response()->json(['timestamp' => time()]);
    }

    private function telLog($arg)
    {
//        $this->Log($arg);
        (new TelegramBot())->sendMsgWithEnv(json_encode($arg));
    }

    private function Log($arg)
    {
        Util::WriteLog('betby', $arg);
    }

    private function decode(Request $request)
    {


        $this->Log($request->all());
        try {
            $data = $this->betbyService->decodePayload($request->payload);
        } catch (\Exception $e){
            return false;
        }

        $this->Log(compact('data'));

        if ($data['aud'] != $this->betbyService->brandId || $data['iss'] != $this->betbyService->operatorId) {
            return false;
        }
        return Util::objectToArray($data['payload']);
    }
    private  $errors = ['1005' => ['code' => 1005, 'message' => 'Player is blocked'],
                        '1006' => ['code' => 1006, 'message' => 'Player not found'],
                        '1007' => ['code' => 1007, 'message' => 'Session is expired'],
                        '2001' => ['code' => 2001, 'message' => 'Not enough money'],
                        '2002' => ['code' => 2002, 'message' => 'Invalid currency'],
                        '2004' => ['code' => 2004, 'message' => 'Bad request'],
                        '2005' => ['code' => 2005, 'message' => 'Invalid JWT token'],
                        '24'   => ['code' => 24, 'message' => 'Message'],
                        '3001' => ['code' => 3001, 'message' => 'Bonus not found'],
                        '4001' => ['code' => 4001, 'message' => 'Player limits exceeded'],
                        '4002' => ['code' => 4002, 'message' => 'Maximum bonus bet limit exceeded']];

    private function getError($code)
    {
        Util::WriteLog('betbyerr', $code);
        return response()->json($this->errors[$code], 400);
    }
    /**
     * 处理请求异常
     *
     * @param RequestException $e 异常对象
     * @return array 错误信息
     */
    private function handleRequestException(RequestException $e): array
    {
        $response = $e->getResponse();
        if ($response) {
            $body = json_decode($response->getBody(), true);
            if (isset($body['error'])) {

                $this->telLog($body);
                return [
                    'error' => new ErrorItem($body['error'])
                ];
            }
        }
        return [
            'error' => new ErrorItem(['name' => 'UnknownError', 'description' => 'An unknown error occurred.'])
        ];
    }

    private function callSubApi($ext_player_id,$method,$data)
    {

        $apiurl=ServerService::GetApiByGUID($ext_player_id);

        try {
            $response = $this->client->post($apiurl . '/game/bbsub/'.$method, [
                'verify'=>false,
                'headers' => ['Content-Type' => 'application/json'],
                'json' => ['payload' => $data]
            ]);
            $data = json_decode($response->getBody(),true);
            $this->Log($data);

            return response()->json( $data,isset($data['code'])?400:200);
        } catch (RequestException $e) {
            return $this->handleRequestException($e);
        }
    }
    /**
     * Bet Make接口
     * 该方法用于处理用户下注请求。
     *
     * 请求参数:
     * - `amount` (integer): 金额
     * - `currency` (string): 货币
     * - `player_id` (string): 玩家ID
     * - `session_id` (string): 会话ID
     * - `bonus_id` (string, 可选): 奖金ID
     * - `bonus_type` (string, 可选): 奖金类型
     * - `transaction` (array): 交易信息
     * - `betslip` (array): 投注信息
     * - `potential_win` (integer): 潜在赢利金额
     * - `potential_comboboost_win` (integer, 可选): 潜在奖金赢利金额
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function betMake(Request $request)
    {

        //{"data":{"iat":1721234686,"exp":1721234986,"jti":"d245e3d473ba4393a4bbca47de0aa117","iss":"2424946715804176387","aud":"2424948766365847552","payload":{"amount":100,"currency":"BRL","player_id":"917c74999c-b53b-eb1a-0004478930","session_id":"1315946882","transaction":{"id":"2425239357104460126","betslip_id":"2425239357104460126","player_id":"2425378291990007812","operator_id":"2424946715804176387","operator_brand_id":"2424948766365847552","ext_player_id":"917c74999c-b53b-eb1a-0004478930","timestamp":1721234686.7508757,"amount":100,"currency":"BRL","operation":"bet","cross_rate_euro":"0.167429"},"betslip":{"id":"2425239357104460126","timestamp":1721234686.739,"player_id":"2425378291990007812","operator_id":"2424946715804176387","operator_brand_id":"2424948766365847552","ext_player_id":"917c74999c-b53b-eb1a-0004478930","currency":"BRL","sum":100,"type":"1\/1","k":"2.3","is_quick_bet":false,"bets":[{"id":"2425239357104460127","event_id":"2424813655611805741","sport_id":"1","tournament_id":"2291720548469837854","category_id":"1666080098480164864","live":true,"sport_name":"Soccer","category_name":"Mexico","tournament_name":"U23 Liga MX","competitor_name":["Necaxa U23","Rayados de Monterrey U23"],"market_name":"Total","outcome_name":"over 9","scheduled":1721228400,"odds":"2.3"}],"accept_odds_change":true},"potential_win":230,"potential_comboboost_win":0},"nbf":1721234681}}
        $data = $this->decode($request);
        if(!$data)return $this->getError(2005);
        if(!isset($data['transaction'])){
            return $this->getError(2004);
        }
        $transaction = new TransactionItem($data['transaction']);
        $betslip = new BetSlipItem($data['betslip']);

        //我们开始扩第二个站的时候，这里要进行分片逻辑了。。。要根据player_id通知其他服务器
        //"917c74999c-b53b-eb1a-0004478930"
        $ext_player_id=$transaction->ext_player_id??$betslip->ext_player_id;

        return $this->callSubApi($ext_player_id,"make",$data);

    }

    /**
     * Bet Commit接口
     * 该方法用于确认下注交易。
     *
     * 请求参数:
     * - `bet_transaction_id` (string): 交易ID
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function betCommit(Request $request)
    {
        $data = $this->decode($request);

        // TODO: 在此处实现具体的确认逻辑

        return response()->json();
    }

    /**
     * Bet Settlement接口
     * 该方法用于结算下注交易。
     *
     * 请求参数:
     * - `bet_transaction_id` (string): 交易ID
     * - `status` (string): 状态
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function betSettlement(Request $request)
    {
        $data = $this->decode($request);

        // TODO: 在此处实现具体的结算逻辑

        $betLid = @$data['bet_transaction_id'];
        Redis::del('bet_amount_'.$betLid);

        return response()->json();
    }

    /**
     * Bet Refund接口
     * 该方法用于处理退款请求。
     *
     * 请求参数:
     * - `bet_transaction_id` (string): 交易ID
     * - `reason` (string): 退款原因
     * - `bonus_id` (string, 可选): 奖金ID
     * - `transaction` (array): 交易信息
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function betRefund(Request $request)
    {
        $data = $this->decode($request);

        $transaction = new TransactionItem($data['transaction']);


        $ext_player_id=$transaction->ext_player_id;

        return $this->callSubApi($ext_player_id,"refund",$data);
    }

    /**
     * Bet Win接口
     * 该方法用于处理用户赢取奖金的请求。
     *
     * 请求参数:
     * - `amount` (integer): 金额
     * - `currency` (string): 货币
     * - `is_cashout` (boolean): 是否兑现
     * - `bet_transaction_id` (string): 交易ID
     * - `transaction` (array): 交易信息
     * - `is_snr_lost` (boolean, 可选): 是否为“无风险免费投注”失利
     * - `selections` (array): 投注选择项
     * - `odds` (string, 可选): 赔率
     * - `bonus_id` (string, 可选): 奖金ID
     * - `bonus_type` (string, 可选): 奖金类型
     * - `comboboost_multiplier` (string, 可选): 奖金乘数
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function betWin(Request $request)
    {
        $data = $this->decode($request);

        $transaction = new TransactionItem($data['transaction']);

        $ext_player_id=$transaction->ext_player_id;

        return $this->callSubApi($ext_player_id,"win",$data);
    }

    /**
     * Bet Lost接口
     * 该方法用于处理用户投注失败的请求。
     *
     * 请求参数:
     * - `bet_transaction_id` (string): 交易ID
     * - `amount` (integer): 金额
     * - `currency` (string): 货币
     * - `transaction` (array): 交易信息
     * - `selections` (array): 投注选择项
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function betLost(Request $request)
    {
        $data = $this->decode($request);

        $transaction = new TransactionItem($data['transaction']);

        $ext_player_id=$transaction->ext_player_id;

        return $this->callSubApi($ext_player_id,"lost",$data);
    }

    /**
     * Bet Discard接口
     * 该方法用于处理丢弃投注的请求。
     *
     * 请求参数:
     * - `ext_player_id` (string): 玩家外部ID
     * - `transaction_id` (string): 交易ID
     * - `reason` (string): 丢弃原因
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function betDiscard(Request $request)
    {
        $data = $this->decode($request);


        $ext_player_id=$data['ext_player_id'];

        return $this->callSubApi($ext_player_id,"discard",$data);
    }

    /**
     * Bet Rollback接口
     * 该方法用于处理回滚投注的请求。
     *
     * 请求参数:
     * - `bet_transaction_id` (string): 交易ID
     * - `parent_transaction_id` (string): 父交易ID
     * - `transaction` (array): 交易信息
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function betRollback(Request $request)
    {
        $data = $this->decode($request);

        $transaction = new TransactionItem($data['transaction']);


        $ext_player_id=$transaction->ext_player_id;

        return $this->callSubApi($ext_player_id,"rollback",$data);
    }
}
