<?php

namespace App\Http\Controllers\Game;


use App\Facade\TableName;
use App\Game\Config\GameBasicConfig;
use App\Game\GameCard;
use App\Game\GlobalUserInfo;
use App\Game\LogGamecardClick;
use App\Game\Route;
use App\Game\Services\OuroGameService;
use App\Game\Services\PlatformService;
use App\Http\Controllers\Api\ApiController;
use App\Http\Controllers\Controller;
use App\Models\AccountsInfo;
use App\Services\IpCheck;
use App\Util;
use App\Utility\SetNXLock;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;


// use Yansongda\Pay\Log;

class OnlyGameController extends Controller
{
    public function gameLunch(Request $request)
    {


        $gid=$request->input('gid');
        $level=$request->input('level',1);
        $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();
        $clientLang='en';
        if($lang=='pt')$clientLang='pt';
        else if($lang=='es')$clientLang='es';
        else $clientLang='en';;

        $api = 'https://int.onlyplay.net/api/get_frame';

        $AccountsInfoModel = new AccountsInfo();
        // 用户余额
        $score = $AccountsInfoModel->Score($userid);

        $baseInfo = [
            'game_bundle' => $gid,
            'callback_url' => GameBasicConfig::$ApiServer,
            'partner_id' => 949,
            'user_id' => strval($userid),
            'balance' => intval($score),
            'currency' => env('CONFIG_24680_CURRENCY'),
            'decimals' => 2,
            'lang' => $clientLang,
            'token' => sha1(time())
        ];
        $baseInfo['sign'] = $this->_sign($baseInfo);

        $headers = [
            'Content-Type' => 'application/json',
        ];
        $retryTimes=0;

        $rs=null;
        while ($rs==null&&$retryTimes<3) {

            try {
                $rs = Util::curlPost2($api, json_encode($baseInfo), true, $headers);
                $rs = json_decode($rs, true);
            }catch (\Exception $e){

            }
            usleep(100*1000);
            $retryTimes++;
        }

        $url = $rs['url'];
        if($url){

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

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

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


    }

    private function _sign($params)
    {
        $secretKey = 'j7OEDKE4Gd1r1PYO7rni13wA3iapu1QPVoG6NoklJoe74j3hCAh84NutR1JG';
        ksort($params);

        $sign_string = '';

        foreach ($params as $key => $value) {
            if(is_array($value)){
                $value = json_encode($value);
            }
            if($value === true){
                $value = 1;
            }

            if($value === false){
                $value = 0;
            }

            $sign_string .= $key.$value;
        }

        $sign = sha1($sign_string . $secretKey);

        return $sign;
    }

    private function _checkSign($data){
        //return true;
        Util::WriteLog('callback_data',$data);
        if(!is_array($data) ||!@$data['sign']){
            Util::WriteLog('24680_sign_error',$data);
            return false;
        }

        $sign = $data['sign'];
        unset($data['sign']);
        return  $sign==$this->_sign($data);
    }

    public function platformInfo(Request $request)
    {
        $post = $request->post();
        //Util::WriteLog('game_test_data',$post);
        if (!is_array($post)) {
            $post = \GuzzleHttp\json_decode($post, true);
        }
        if(!$this->_checkSign($post)){
            return ['success' => false,'code' => 3100,'message' => 'Sent data is not secure, wrong sign'];
        }
        $UserID = $post['user_id'];
        $AccountsInfoModel = new AccountsInfo();
        // 用户余额
        $score = $AccountsInfoModel->Score($UserID);
        return ['success' => true,'balance' => intval($score)];
    }

    public function platformBet(Request $request)
    {
        $post = $request->post();
        if (!is_array($post)) {
            $post = \GuzzleHttp\json_decode($post, true);
        }
        if(!$this->_checkSign($post)){
            return ['success' => false,'code' => 3100,'message' => 'Sent data is not secure, wrong sign'];
        }
        $UserID = $post['user_id'];

        $AccountsInfoModel = new AccountsInfo();
        // 用户余额
        $score = intval($AccountsInfoModel->Score($UserID));

        $res = SetNXLock::getExclusiveLock('bet'.$post['tx_id'], 86400);
        if (!$res) {

            Util::WriteLog('24680_bet_error',$post);
            return ['success' => true,'balance' => intval($score)];
            //return ['success' => false,'code' => 2401,'message' => 'Session not found or expired.'];
        }


        GameCard::$enableStateCheck=false;
        $gamecard=GameCard::where('gid',$post['game_bundle'])->first();
        $in_gameid = OuroGameService::getUserInGame($UserID);
        if(!$gamecard){
            $gamecard="notfind :::: ".$post['game_bundle'];
            Util::WriteLog('24680game', compact('in_gameid', 'gamecard', 'UserID'));
        }else {

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




        $bet = intval($post['amount']);
        if($bet>$score){
            return ['success' => false,'code' => 5001,'message' => 'Insufficient funds'];
        }
        DB::connection('write')->table('QPTreasureDB.dbo.GameScoreInfo')->where('UserID', $UserID)->decrement('Score', $bet);

        //用户cancel的时候
        Redis::set('bet_amount_'.$post['tx_id'],$bet);
        Redis::expire('bet_amount_'.$post['tx_id'],120);

        PlatformService::platformBet('only',$post['game_bundle'],$bet,$UserID);

        Util::WriteLog('24680_only_bet_success',array_merge($post, ['success' => true,'balance' => intval($score)-$bet]));

        return ['success' => true,'balance' => intval($score)-$bet];
    }

    public function platformWin(Request $request)
    {
        $post = $request->post();
        if (!is_array($post)) {
            $post = \GuzzleHttp\json_decode($post, true);
        }
        if(!$this->_checkSign($post)){
            return ['success' => false,'code' => 3100,'message' => 'Sent data is not secure, wrong sign'];
        }



        $UserID = $post['user_id'];
        $AccountsInfoModel = new AccountsInfo();
        // 用户余额
        $score = intval($AccountsInfoModel->Score($UserID));

        $res = SetNXLock::getExclusiveLock('win_'.$post['tx_id'], 86400);
        if (!$res) {
            Util::WriteLog('24680_win_error',$post);
            //return ['success' => false,'code' => 2401,'message' => 'Session not found or expired.'];
            return ['success' => true,'balance' => intval($score)];
        }

        $betKey = 'bet_amount_'.$post['ref_tx_id'];

        $win = intval($post['amount']);
        $bet =  Redis::get($betKey)?:0;
        if(true){
            PlatformService::platformWin($UserID,'only',$post['game_bundle'],$win,$bet,$score+$win);
        }

        Redis::del($betKey);

        Util::WriteLog('24680_only_win_success',array_merge($post,  ['success' => true,'balance' => intval($score)+$win]));

        return ['success' => true,'balance' => intval($score)+$win];
    }

    public function platformCancel(Request $request)
    {
        $post = $request->post();
        if (!is_array($post)) {
            $post = \GuzzleHttp\json_decode($post, true);
        }
        if(!$this->_checkSign($post)){
            return ['success' => false,'code' => 3100,'message' => 'Sent data is not secure, wrong sign'];
        }

        $UserID = $post['user_id'];
        $AccountsInfoModel = new AccountsInfo();
        // 用户余额
        $score = intval($AccountsInfoModel->Score($UserID));

        $bet=0;
        $key='bet_amount_'.$post['ref_tx_id'];
        if(Redis::exists($key)){
            $bet=Redis::get($key);
            if($bet>0){
                DB::connection('write')->table('QPTreasureDB.dbo.GameScoreInfo')->where('UserID', $UserID)->increment('Score', $bet);
                PlatformService::platformBet('only',$post['game_bundle'],-$bet,$UserID);
            }
            Redis::del($key);
        }
        $score+=$bet;

        Util::WriteLog('24680_only_cancel_success',array_merge($post,  ['success' => true,'balance' => intval($score)]));
        return ['success' => true,'balance' => intval($score)];
    }

    public function roundInfo(Request $request){
        $api = 'https://int.onlyplay.net/api/get_frame';

        $baseInfo = [
            'round_id' => $request->input('round'),
            'partner_id' => 949,
            'date' => date('Y-m-d')
        ];
        $baseInfo['sign'] = $this->_sign($baseInfo);

        $headers = [
            'Content-Type' => 'application/json',
        ];

        $rs = Util::curlPost2($api,json_encode($baseInfo),true,$headers);

        dd($rs);
    }

}
