<?php

namespace App\Http\Controllers\Game;
use App\Facade\TableName;
use App\Game\GameCard;
use App\Game\GlobalUserInfo;
use App\Game\LogGamecardClick;
use App\Game\Services\OuroGameService;
use App\Game\Services\PgSoftService;
use App\Game\Services\PlatformService;
use App\Game\Services\PPlayService;
use App\Game\Services\ServerService;
use App\Http\helper\NumConfig;
use App\Models\AccountsInfo;
use App\Notification\TelegramBot;
use App\Util;
use App\Utility\SetNXLock;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class PPlayController extends Controller
{
    protected $ppSoftService;
    protected $client;
    protected $currency='BRL';

    public function __construct(PPlayService  $ppSoftService)
    {
        $this->ppSoftService = $ppSoftService;
        $this->client = new Client();
        $this->currency=env('CONFIG_24680_CURRENCY',$this->currency);
    }
    private function handleRequestException(\Exception $e)
    {
        TelegramBot::getDefault()->sendMsgWithEnv($e->getMessage().$e->getTraceAsString());
    }



    private function callSubApi($ext_player_id,$request)
    {

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

        try {
            // 获取当前请求的 GET 和 POST 数据
//            $getData = $request->query(); // 获取 GET 数据
            $postData = $request->post(); // 获取 POST 数据

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

    public function backLobby()
    {
        echo "<script>
parent.postMessage({cmd:\"back\"},\"*\");
</script>";
    }


    public function gameLunch(Request $request)
    {

        $gid=$request->input('gid');
        $user = $request->user();
        $userid=$user->UserID;

        if($user->Channel!=99){
            http_response_code(404);
            exit();
        }

        GameCard::$enableStateCheck=false;
        $gamecard=GameCard::where('gid',$gid)->first();

        $in_gameid=OuroGameService::getUserInGame($userid,$user->GlobalUID);
        if($in_gameid!=intval($gamecard->id)){
            Util::WriteLog('24680game',compact('in_gameid','gamecard','user'));
//            die;
        }



        $lang=GlobalUserInfo::getLocale();
        $supportLang = ['en','da','de','es','fi','fr','id','it','ja','ko','nl','no','pl','pt','ro','ru','sv','th','tr','vi','zh','my'];
        if(!in_array($lang,$supportLang)){
            $lang = 'en';
        }

        $rs = $this->ppSoftService->getLaunchURL($gid,$user->GlobalUID,$user->GlobalUID,$this->currency,$lang);
        if(@$rs['gameURL']){

            $gamecard=GameCard::where('gid',$gid)->where('brand','PP')->first();
            $gamecard->increment('play_num',1);
            //$this->logGameClick($gamecard->id,$userid);

            LogGamecardClick::recordClick($gamecard->id,$userid);

            echo "<script>
parent.postMessage({cmd:\"closeLoading\"},\"*\");
window.location.href='".$rs['gameURL']."';
</script>";
            exit();
        }else{
            echo "<script>alert('system wrong')</script>";
            exit();
        }
    }

    public function gameLogin(Request $request)
    {
        $gid = $request->input('gid','vs20olympx');
        $guid = $request->input('guid','0685128230-b53b-eb1a-0004688302');
        $uid = $request->input('uid','4688302');
        $lang=GlobalUserInfo::getLocale();
        $supportLang = ['en','da','de','es','fi','fr','id','it','ja','ko','nl','no','pl','pt','ro','ru','sv','th','tr','vi','zh','my'];
        if(!in_array($lang,$supportLang)){
            $lang = 'en';
        }
        $rs = $this->ppSoftService->getLaunchURL($gid,$guid,$guid,$this->currency,$lang);

        echo "<script>
window.location.href='".$rs['gameURL']."';
</script>";
//        var_dump($rs);
    }

    public function gameList()
    {
        $response = $this->ppSoftService->getCasinoGames();
        $gameList = $response['gameList'];
        foreach ($gameList as &$game) {
            unset($game['jurisdictions']);
        }


        return response()->json($gameList);
    }

    public function gameLobbyList()
    {
        $response = $this->ppSoftService->getLobbyGames();

        return response()->json($response);
    }

    public function authenticate(Request $request){
        $post = $request->all();
        Util::WriteLog('pp_authenticate',$post);
        if(!$this->ppSoftService->checkHash($post)){
            return response()->json(['error' => 5,'description' => 'Invalid hash code']);
        }
        $token = $post['token'];

        if(!ServerService::IsLocalUser($token)) {
            return $this->callSubApi($token,$request);
        }

        $user = GlobalUserInfo::getGameUserInfo('GlobalUID', $token);
        if (!$user) return response()->json(['error' => 2,'description' => 'Player not found ']);
        $response = [
            'userId' => $token,//$user->UserID,
            'currency' => $this->currency,
            'cash' => GlobalUserInfo::getScoreByUserID($user->UserID),
            'bonus' => 0,
            'error' => 0,
            'description' => 'Success'
        ];
        return response()->json($response);
    }

    public function balance(Request $request)
    {
        $post = $request->all();

        if(!ServerService::IsLocalUser($post['userId'])) {
            return $this->callSubApi($post['userId'],$request);
        }
        $UserID=ServerService::GlobalToUserID($post['userId']);

        Util::WriteLog('pp_balance',$post);
        if(!$this->ppSoftService->checkHash($post)){
            return response()->json(['error' => 5,'description' => 'Invalid hash code']);
        }
        $response = [
            'currency' => $this->currency,
            'cash' => GlobalUserInfo::getScoreByUserID($UserID),
            'bonus' => 0,
            'error' => 0,
            'description' => 'Success'
        ];
        return response()->json($response);
    }

    public function bet(Request $request)
    {
        $post = $request->all();


        if(!ServerService::IsLocalUser($post['userId'])) {
            return $this->callSubApi($post['userId'],$request);
        }
        $UserID=ServerService::GlobalToUserID($post['userId']);

        Util::WriteLog('pp_bet',$post);
        if(!$this->ppSoftService->checkHash($post)){
            return response()->json(['error' => 5,'description' => 'Invalid hash code']);
        }


        $transactionId = $post['reference'];
        $score = GlobalUserInfo::getScoreByUserID($UserID);

        $res = SetNXLock::getExclusiveLock('pp_bet'.$transactionId, 600);
        if (!$res) {
            Util::WriteLog('pp_bet_repeat',$post);
            return ['transactionId' => $transactionId,'currency' => $this->currency,'cash' => $score,'bonus' => 0,'usedPromo' => 0,'error' => 0,'description' => 'Success'];
        }

        if(round($post['amount'],2)>round($score,2)){
            return response()->json(['error' => 1,'description' => 'Insufficient balance']);
        }

        $bet = intval($post['amount']*NumConfig::NUM_VALUE);
        DB::connection('write')->table('QPTreasureDB.dbo.GameScoreInfo')->where('UserID', $UserID)->decrement('Score', $bet);
        PlatformService::platformBet('pp',$post['gameId'],$bet,$UserID);

        $betKey = 'pp_bet_amount_'.$transactionId;
        Redis::set($betKey,$bet);
        Redis::expire($betKey,600);

        return ['transactionId' => $transactionId,'currency' => $this->currency,'cash' =>round($score-$post['amount'],2),'bonus' => 0,'usedPromo' => 0,'error' => 0,'description' => 'Success'];
    }

    public function result(Request $request)
    {
        $post = $request->all();

        if(!ServerService::IsLocalUser($post['userId'])) {
            return $this->callSubApi($post['userId'],$request);
        }
        $UserID=ServerService::GlobalToUserID($post['userId']);


        Util::WriteLog('pp_result',$post);
        if(!$this->ppSoftService->checkHash($post)){
            return response()->json(['error' => 5,'description' => 'Invalid hash code']);
        }

        $transactionId = $post['reference'];

        $score = GlobalUserInfo::getScoreByUserID($UserID);
        $res = SetNXLock::getExclusiveLock('pp_result'.$transactionId, 600);
        if (!$res) {
            Util::WriteLog('pp_win_repeat',$post);
            return ['transactionId' => $transactionId,'currency' => $this->currency,'cash' => $score,'bonus' => 0,'error' => 0,'description' => 'Success'];
        }

        $betKey = 'pp_bet_amount_'.$transactionId;
        $bet = Redis::get($betKey)?:0;

        Redis::del($betKey);

        $win = $post['amount'];
        if(isset($post['promoWinAmount'])){
            if($post['promoWinAmount']>0){
                $win = round($post['promoWinAmount']+$post['amount'],2);
            }
        }

        PlatformService::platformWin($UserID,'pp',$post['gameId'],intval($win*NumConfig::NUM_VALUE),$bet,intval($score+$win)*NumConfig::NUM_VALUE);
        return ['transactionId' => $transactionId,'currency' => $this->currency,'cash' =>round($score+$win,2),'bonus' => 0,'error' => 0,'description' => 'Success'];
    }

    public function bonusWin(Request $request)
    {
        $post = $request->all();

        if(!ServerService::IsLocalUser($post['userId'])) {
            return $this->callSubApi($post['userId'],$request);
        }
        $UserID=ServerService::GlobalToUserID($post['userId']);

        Util::WriteLog('pp_bonusWin',$post);
        if(!$this->ppSoftService->checkHash($post)){
            return response()->json(['error' => 5,'description' => 'Invalid hash code']);
        }


        $transactionId = $post['reference'];

        $score = GlobalUserInfo::getScoreByUserID($UserID);
//        $res = SetNXLock::getExclusiveLock('pp_bonusWin'.$transactionId, 600);
//        if (!$res) {
//            Util::WriteLog('pp_bonusWin_repeat',$post);
//            return ['transactionId' => $transactionId,'currency' => $this->currency,'cash' => $score,'bonus' => 0,'error' => 0,'description' => 'Success'];
//        }
//
//        PlatformService::platformWin($UserID,'pp','bonusWin',intval($post['amount']*NumConfig::NUM_VALUE),0,intval($score+$post['amount'])*NumConfig::NUM_VALUE);
        return ['transactionId' => $transactionId,'currency' => $this->currency,'cash' =>round($score,2),'bonus' => 0,'error' => 0,'description' => 'Success'];
    }

    public function jackpotWin(Request $request)
    {
        $post = $request->all();

        if(!ServerService::IsLocalUser($post['userId'])) {
            return $this->callSubApi($post['userId'],$request);
        }
        $UserID=ServerService::GlobalToUserID($post['userId']);

        Util::WriteLog('pp_jackpotWin',$post);
        if(!$this->ppSoftService->checkHash($post)){
            return response()->json(['error' => 5,'description' => 'Invalid hash code']);
        }


        $transactionId = $post['reference'];

        $score = GlobalUserInfo::getScoreByUserID($UserID);
        $res = SetNXLock::getExclusiveLock('pp_jackpotWin'.$transactionId, 600);
        if (!$res) {
            Util::WriteLog('pp_jackpotWin_repeat',$post);
            return ['transactionId' => $transactionId,'currency' => $this->currency,'cash' => $score,'bonus' => 0,'error' => 0,'description' => 'Success'];
        }

        PlatformService::platformWin($UserID,'pp',@$post['gameId'],intval($post['amount']*NumConfig::NUM_VALUE),0,intval($score+$post['amount'])*NumConfig::NUM_VALUE);
        return ['transactionId' => $transactionId,'currency' => $this->currency,'cash' =>round($score+$post['amount'],2),'bonus' => 0,'error' => 0,'description' => 'Success'];
    }

    public function refund(Request $request)
    {
        $post = $request->all();
        if(!ServerService::IsLocalUser($post['userId'])) {
            return $this->callSubApi($post['userId'],$request);
        }
        $UserID=ServerService::GlobalToUserID($post['userId']);

        Util::WriteLog('pp_refund',$post);
        if(!$this->ppSoftService->checkHash($post)){
            return response()->json(['error' => 5,'description' => 'Invalid hash code']);
        }

        $transactionId = $post['reference'];
        $betKey = 'pp_bet_amount_'.$transactionId;
        $bet = Redis::get($betKey)?:0;
        if($bet){
            Redis::del($betKey);
            DB::connection('write')->table('QPTreasureDB.dbo.GameScoreInfo')->where('UserID', $UserID)->increment('Score', $bet);
        }

        return ['transactionId' => $transactionId,'error' => 0,'description' => 'Success'];
    }

    public function promoWin(Request $request)
    {
        $post = $request->all();

        if(!ServerService::IsLocalUser($post['userId'])) {
            return $this->callSubApi($post['userId'],$request);
        }
        $UserID=ServerService::GlobalToUserID($post['userId']);

        Util::WriteLog('pp_promoWin',$post);
        if(!$this->ppSoftService->checkHash($post)){
            return response()->json(['error' => 5,'description' => 'Invalid hash code']);
        }

        $transactionId = $post['reference'];

        $score = GlobalUserInfo::getScoreByUserID($UserID);
        $res = SetNXLock::getExclusiveLock('pp_promoWin'.$transactionId, 600);
        if (!$res) {
            Util::WriteLog('pp_promoWin_repeat',$post);
            return ['transactionId' => $transactionId,'currency' => $this->currency,'cash' => $score,'bonus' => 0,'error' => 0,'description' => 'Success'];
        }

        PlatformService::platformWin($UserID,'pp',@$post['gameId'],intval($post['amount']*NumConfig::NUM_VALUE),0,intval($score+$post['amount'])*NumConfig::NUM_VALUE);
        return ['transactionId' => $transactionId,'currency' => $this->currency,'cash' =>round($score+$post['amount'],2),'bonus' => 0,'error' => 0,'description' => 'Success'];

    }

}
