<?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\PgSoftTestService;
use App\Game\Services\PlatformService;
use App\Http\helper\NumConfig;
use App\Models\AccountsInfo;
use App\Util;
use App\Utility\SetNXLock;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class PgSoftTestController extends Controller
{
    protected $pgSoftService;
    protected $Currency='';
    public function __construct(PgSoftTestService $pgSoftService)
    {
        $this->pgSoftService = $pgSoftService;
        $this->Currency = env('CONFIG_24680_CURRENCY');
    }


    public function gameLunch(Request $request)
    {

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

        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;
        }

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

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

        $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';
        }

        echo "<script>
parent.postMessage({cmd:\"closeLoading\"},\"*\");
</script>";

        header("Cache-Control: no-cache, no-store, must-revalidate");
        //header("Pragma: no-cache"); // HTTP 1.0
        header("Expires: 0"); // 禁止客户端缓存

        return $this->pgSoftService->getLaunchURLHTML($gid,$user->GlobalUID,$request->ip(),$lang);
    }

    public function gameList()
    {
        $response = $this->pgSoftService->getGamesList();

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

    public function VerifySession(Request $request)
    {
        $post = $request->all();
        Util::WriteLog('pg_token',$post);
        if(!$this->pgSoftService->VerifySession(@$post['operator_token'], @$post['secret_key'])){
            return response()->json(['data' => null,'error' => ['code' => 1034,'message' => 'invalid session']]);
        }
        $playerId = @$post['operator_player_session'];
        $user = GlobalUserInfo::getGameUserInfo('GlobalUID', $playerId);
        if(!$user) return response()->json(['data' => null,'error' => ['code' => 1034,'message' => 'invalid session']]);
        Util::WriteLog('pg_token',$user);
        Util::WriteLog('pg_token',['data' => ['player_name' => $playerId,'nickname' => $user->NickName,'currency' => $this->Currency],'error' => null]);
        return response()->json(['data' => ['player_name' => $playerId,'nickname' => $user->NickName,'currency' => $this->Currency],'error' => null]);
    }

    public function balance(Request $request)
    {

        $post = $request->all();
        Util::WriteLog('pg_balance',$post);
        if(!$this->pgSoftService->VerifySession(@$post['operator_token'], @$post['secret_key'])){
            return response()->json(['data' => null,'error' => ['code' => 1034,'message' => 'invalid session']]);
        }
        $playerId = @$post['player_name'];
        $user = GlobalUserInfo::getGameUserInfo('GlobalUID', $playerId);
        if(!$user) return response()->json(['data' => null,'error' => ['code' => 1034,'message' => 'invalid session']]);

        $score = GlobalUserInfo::getScoreByUserID($user->UserID);
        Util::WriteLog('pg_balance',['data' => ['currency_code' => $this->Currency,'balance_amount' => $score,'updated_time' => Util::getUnixTimestampMillis()],'error' => null]);
        return response()->json(['data' => ['currency_code' => $this->Currency,'balance_amount' => $score,'updated_time' => Util::getUnixTimestampMillis()],'error' => null]);
    }


    public function cashTransferInOut(Request $request)
    {
        $post = $request->all();
        Util::WriteLog('pg_inout',$post);
        if(!$this->pgSoftService->VerifySession(@$post['operator_token'], @$post['secret_key'])){
            return response()->json(['data' => null,'error' => ['code' => 1034,'message' => 'invalid session']]);
        }


        $playerId = @$post['player_name'];
        $user = GlobalUserInfo::getGameUserInfo('GlobalUID', $playerId);
        if(!$user) return response()->json(['data' => null,'error' => ['code' => 1034,'message' => 'invalid session']]);

        Util::WriteLog('pg_inout',$user);

        if(@$post['currency_code'] != $this->Currency){
            return response()->json(['data' => null,'error' => ['code' => 1034,'message' => 'invalid session']]);
        }

        $transactionId = $post['transaction_id'];
        $score = GlobalUserInfo::getScoreByUserID($user->UserID);
        $isBet = @$post['is_wager'];
        $bet = $post['bet_amount'];
        $win = $post['win_amount'];
        $transfer = $post['transfer_amount'];
        if(round($transfer,2) != round($win - $bet,2)){
            Util::WriteLog('pg_inout',['transfer_error' => 1, 'data' => ['transfer_amount' => $transfer,'win' => $win,'bet' => $bet],'error' => null]);

            return response()->json(['data' => null,'error' => ['code' => 3073,'message' => 'BetFailedException']]);
        }

        if(isset($post['real_transfer_amount'])){
            if($transfer != $post['real_transfer_amount']){
                return response()->json(['data' => null,'error' => ['code' => 3107,'message' => 'BetFailedException']]);
            }
        }



        $exists = Redis::exists('pg_inout_'.$transactionId);
        if ($exists) {
            Util::WriteLog('pg_inout',Redis::get('pg_inout_'.$transactionId));

            return response()->json(json_decode(Redis::get('pg_inout_'.$transactionId),true));
            //return response()->json(['data' => ['currency_code' => $this->Currency,'balance_amount' => $score,'updated_time' => (int)$post['updated_time']],'error' => null]);
        }

        if($bet>0){
            if($score<$bet){
                Util::WriteLog('pg_inout',['yichu' => 1,'data' => ['currency_code' => $this->Currency,'balance_amount' => $score,'updated_time' => (int)$post['updated_time']],'error' => null]);

                Redis::setex('pg_inout_'.$transactionId,300,json_encode(['data' => null,'error' => ['code' => 3202,'message' => 'NotEnoughBalanceException']]));

                return response()->json(['data' => null,'error' => ['code' => 3202,'message' => 'NotEnoughBalanceException']]);
            }
            PlatformService::platformBet('pg',@$post['game_id'],intval($bet*100),$user->UserID);
        }

        if($transfer){
            if($transfer+$score<0){
                $transfer = -$score;
            }
            DB::connection('write')->table('QPTreasureDB.dbo.GameScoreInfo')->where('UserID', $user->UserID)->increment('Score', $transfer*NumConfig::NUM_VALUE);
            $score = round($score + $transfer,2);

            PlatformService::platformWin($user->UserID,'pg',@$post['game_id'],intval($win*NumConfig::NUM_VALUE),intval($bet*NumConfig::NUM_VALUE),intval($score*NumConfig::NUM_VALUE),false);
        }


        if(isset($post['real_transfer_amount'])){
            $output = ['data' => ['currency_code' => $this->Currency,'balance_amount' => $score,'updated_time' => (int)$post['updated_time'],'real_transfer_amount' =>  round($post['real_transfer_amount'],2)],'error' => null];
        }else{
            $output = ['data' => ['currency_code' => $this->Currency,'balance_amount' => $score,'updated_time' => (int)$post['updated_time']],'error' => null];
        }

        Redis::setex('pg_inout_'.$transactionId,88600,json_encode($output));
        Util::WriteLog('pg_inout',$output);

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


    }


    public function cashAdjustment(Request $request)
    {
        $post = $request->all();
        Util::WriteLog('pg_adjust',$post);
        if(!$this->pgSoftService->VerifySession(@$post['operator_token'], @$post['secret_key'])){
            return response()->json(['data' => null,'error' => ['code' => 1034,'message' => 'invalid session']]);
        }


        $playerId = @$post['player_name'];
        $user = GlobalUserInfo::getGameUserInfo('GlobalUID', $playerId);
        if(!$user) return response()->json(['data' => null,'error' => ['code' => 1034,'message' => 'invalid session']]);

        Util::WriteLog('pg_adjust',$user);

        if(@$post['currency_code'] != $this->Currency){
            return response()->json(['data' => null,'error' => ['code' => 1034,'message' => 'invalid session']]);
        }

        $transactionId = $post['adjustment_transaction_id'];
        $score = GlobalUserInfo::getScoreByUserID($user->UserID);
        $transfer = $post['transfer_amount'];
        if($transfer+$score<0){
            return response()->json(['data' => null,'error' => ['code' => 3202,'message' => 'BetFailedException']]);
        }

        if(isset($post['real_transfer_amount'])){
            if($transfer != $post['real_transfer_amount']){
                return response()->json(['data' => null,'error' => ['code' => 3107,'message' => 'BetFailedException']]);
            }
        }



        $exists = Redis::exists('pg_adjust_'.$transactionId);
        if ($exists) {
            return response()->json(json_decode(Redis::get('pg_adjust_'.$transactionId),true));
        }


        if($transfer){
            DB::connection('write')->table('QPTreasureDB.dbo.GameScoreInfo')->where('UserID', $user->UserID)->increment('Score', $transfer*NumConfig::NUM_VALUE);
        }

        $output = ['data' => ['currency_code' => $this->Currency, 'adjust_amount' => $transfer, 'balance_before' => $score, 'balance_after' => round($transfer+$score,2), 'updated_time' => (int)$post['adjustment_time']],'error' => null];
        if(isset($post['real_transfer_amount'])){
            $output['data']['real_transfer_amount'] = round($post['real_transfer_amount'],2);
        }

        Redis::setex('pg_adjust_'.$transactionId,88600,json_encode($output));


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

    public function cashUpdateBetDetail()
    {
        return response()->json(['data' => ['is_success' => 1],'error' => null]);
    }

}
