<?php

namespace App\Http\Controllers\Game;
use App\Facade\TableName;
use App\Game\GameCard;
use App\Game\GlobalUserInfo;
use App\Game\Services\OuroGameService;
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 App\Game\Services\AtmosferaService;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class AtmosferaController extends Controller
{
    protected $atmosferaService;

    public function __construct(AtmosferaService $atmosferaService)
    {
        $this->atmosferaService = $atmosferaService;
    }

    /**
     * 获取玩家余额
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     *
     * 请求参数:
     * - user_id (string): 玩家ID，必须是先前传递给create_user_ex方法的值
     * - merchant_id (integer): 商户ID
     * - session_id (string, 可选): 会话ID
     *
     * 调用示例:
     * {
     *   "user_id": "123654",
     *   "merchant_id": 1,
     *   "session_id": "session123"
     * }
     */
    public function getBalance(Request $request)
    {
        $post = $request->post();
        if(!$this->atmosferaService->checkSignature($post)){
            return response()->json(['result' => false,'err_code' => 1]);
        }
       // $data = json_decode($post['data'],true);

        $data = $post['data'];
        $AccountsInfoModel = new AccountsInfo();
        // 用户余额
        $score = $AccountsInfoModel->Score($data['user_id']);
        $response = ['result' => true,'err_code' => 0,'amount' => $score/100,'currency' => env('CONFIG_24680_CURRENCY')];
        return response()->json($response);
    }

    /**
     * 获取玩家账户详情
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     *
     * 请求参数:
     * - user_id (string): 玩家ID，必须是先前传递给create_user_ex方法的值
     * - merchant_id (integer): 商户ID
     * - session_id (string, 可选): 会话ID
     *
     * 调用示例:
     * {
     *   "user_id": "123654",
     *   "merchant_id": 1,
     *   "session_id": "session123"
     * }
     */
    public function getAccountDetails(Request $request)
    {
        $post = $request->post();
        if(!$this->atmosferaService->checkSignature($post)){
            return response()->json(['result' => false,'err_code' => 1]);
        }
        //$data = json_decode($post['data'],true);
        $data = $post['data'];
        $userInfo = DB::table(TableName::QPAccountsDB() . 'AccountsInfo')
            ->where('UserID', $data['user_id'])
            ->first();
        if(!$userInfo){
            return response()->json(['result' => false,'err_code' => 3]);
        }
        $response = ['result' => true,'err_code' => 0,'user_name' => $userInfo->NickName];
        return response()->json($response);
    }

    /**
     * 提现
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     *
     * 请求参数:
     * - user_id (string): 玩家ID，必须是先前传递给create_user_ex方法的值
     * - transaction_id (string): 在ATMOSFERA端的唯一事务标识
     * - currency (string): 货币ISO代码
     * - amount (numeric): 提现金额
     * - bonus_amount (numeric): 从玩家的奖金账户中提现的金额
     * - game_type (integer): 游戏标识符
     * - game_id (string): 游戏回合标识符
     * - merchant_id (integer): 商户ID
     * - session_id (string, 可选): 会话ID
     * - bonus_game (boolean): 如果为true，bonus_amount大于0且amount等于0
     * - bet_data (array): 包含下注信息的JSON编码数组
     *
     * 调用示例:
     * {
     *   "user_id": "123654",
     *   "transaction_id": "123456_0",
     *   "currency": "EUR",
     *   "amount": 0.25,
     *   "bonus_amount": 0,
     *   "game_type": 70,
     *   "game_id": "1234",
     *   "merchant_id": 1,
     *   "session_id": "session123",
     *   "bonus_game": false,
     *   "bet_data": [
     *     {"bet_id": 123, "nominal": 0.15, "content": "{\"numbers\":[34],\"pos\":\"34\"}"},
     *     {"bet_id": 124, "nominal": 0.1, "content": "{\"numbers\":[33],\"pos\":\"33\"}"}
     *   ]
     * }
     */
    public function withdraw(Request $request)
    {
        $post = $request->post();
        if(!$this->atmosferaService->checkSignature($post)){
            return response()->json(['result' => false,'err_code' => 1]);
        }
        //$data = json_decode($post['data'],true);

        $data = $post['data'];

        $UserID = $data['user_id'];
//        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;
//            }
//        }

        $res = SetNXLock::getExclusiveLock('bet'.$data['transaction_id'], 86400);
        if (!$res) {
            Util::WriteLog('atmosfera_bet_error',$data);
            return response()->json( ['result' => false,'err_code' => 4]);
        }

        $AccountsInfoModel = new AccountsInfo();
        // 用户余额
        $score = intval($AccountsInfoModel->Score($UserID));
        $bet = intval($data['amount']*NumConfig::NUM_VALUE);
        if($bet>$score){
            return response()->json( ['result' => false,'err_code' => 5]);
        }
        DB::connection('write')->table('QPTreasureDB.dbo.GameScoreInfo')->where('UserID', $UserID)->decrement('Score', $bet);

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

        PlatformService::platformBet('atmosfera',$data['game_type'],$bet,$UserID);
        $response = ['result' => true,'err_code' => 0,'balance' => ($score-$bet)/100,'bonus_balance' => 0,'operation_id' => $data['transaction_id']];
        return response()->json($response);
    }

    /**
     * 存款
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     *
     * 请求参数:
     * - user_id (string): 玩家ID，必须是先前传递给create_user_ex方法的值
     * - transaction_id (string): 在ATMOSFERA端的唯一事务标识
     * - currency (string): 货币ISO代码
     * - amount (numeric): 存款金额
     * - start_operation_id (string): 在withdraw方法中接收到的操作ID
     * - game_type (integer): 游戏标识符
     * - game_id (string): 游戏回合标识符
     * - game_data (string): 包含游戏结果信息的字符串或对象
     * - merchant_id (integer): 商户ID
     * - session_id (string, 可选): 会话ID
     * - bonus_game (boolean): 如果为true，表示奖金游戏
     * - bet_data (array): 包含下注信息的JSON编码数组
     *
     * 调用示例:
     * {
     *   "user_id": "123654",
     *   "transaction_id": "123457_0",
     *   "currency": "EUR",
     *   "amount": 1,
     *   "start_operation_id": "123",
     *   "game_type": 70,
     *   "game_id": "1234",
     *   "game_data": "{\"balls\":[3],\"cards\":null}",
     *   "merchant_id": 1,
     *   "session_id": "session123",
     *   "bonus_game": false,
     *   "bet_data": [
     *     {"bet_id": 123, "win_amount": 1, "jp_amount": 0},
     *     {"bet_id": 124, "win_amount": 0, "jp_amount": 0}
     *   ]
     * }
     */
    public function deposit(Request $request)
    {
        $post = $request->post();
        if(!$this->atmosferaService->checkSignature($post)){
            return response()->json(['result' => false,'err_code' => 1]);
        }
        //$data = json_decode($post['data'],true);
        $data = $post['data'];
        $UserID = $data['user_id'];





        $AccountsInfoModel = new AccountsInfo();
        // 用户余额
        $score = intval($AccountsInfoModel->Score($UserID));
        $res = SetNXLock::getExclusiveLock('win_'.$data['transaction_id'], 86400);
        if (!$res) {
            Util::WriteLog('atmosfera_win_error',$data);
            return response()->json(['result' => true,'err_code' => 0,'balance' => ($score)/100,'bonus_balance' => 0,'operation_id' => $data['transaction_id']]);
        }
        $win = intval($data['amount']*NumConfig::NUM_VALUE);
        $betKey = 'bet_amount_'.$data['start_operation_id'];
        $bet =  Redis::get($betKey)?:0;
        if(true){
            PlatformService::platformWin($UserID,'atmosfera',$data['game_type'],$win,$bet,$score+$win);
        }
        Redis::del($betKey);
        $response = ['result' => true,'err_code' => 0,'balance' => ($score+$win)/100,'bonus_balance' => 0,'operation_id' => $data['transaction_id']];
        return response()->json($response);
    }

    /**
     * 回滚
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     *
     * 请求参数:
     * - user_id (string): 玩家ID，必须是先前传递给create_user_ex方法的值
     * - transaction_id (string): 需要回滚的提现事务的唯一标识符
     * - merchant_id (integer): 商户ID
     * - session_id (string, 可选): 会话ID
     * - bonus_game (boolean): 如果为true，表示奖金游戏
     *
     * 调用示例:
     * {
     *   "user_id": "123654",
     *   "transaction_id": "123457_0",
     *   "merchant_id": 1,
     *   "session_id": "session123",
     *   "bonus_game": false
     * }
     */
    public function rollback(Request $request)
    {
        $post = $request->post();
        if(!$this->atmosferaService->checkSignature($post)){
            return response()->json(['result' => false,'err_code' => 1]);
        }
        //$data = json_decode($post['data'],true);
        $data = $post['data'];
        $UserID = $data['user_id'];

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

        $bet=0;
        $key='bet_amount_'.$data['transaction_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('atmosfera','',-$bet,$UserID);
                Redis::del('bet_amount_'.$data['transaction_id']);
            }
        }
        $score+=$bet;

        $response = ['result' => true,'err_code' => 0,'balance' => ($score)/100,'bonus_balance' => 0];

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

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

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

    public function token(Request $request)
    {
        $uid=$request->input('uid');
        $response = $this->atmosferaService->registerTokenEx($uid,0,'session123');

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

    public function checkUser(Request $request)
    {
        $uid=$request->input('uid');
        $response = $this->atmosferaService->checkUserEx($uid);

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

    public function gameLunch(Request $request)
    {
        $gid=$request->input('gid');
        $level=$request->input('level',1);
        $user = $request->user();
        $userid=$user->UserID;

        $response = $this->atmosferaService->checkUserEx($userid);
        if($response['result'] == false && $response['err_code'] == 20){
            $rs = $this->atmosferaService->createUserEx($userid,0);
            if($rs['result'] == false && $rs['err_code'] != 21){
                echo "<script>alert('system wrong')</script>";
                exit();
            }
        }


        $token = $this->atmosferaService->registerTokenEx($userid);

        if($token['result'] == false){
            echo "<script>alert('system wrong')</script>";
            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='pt';
        else if($lang=='ru')$clientLang='ru';
        else if($lang=='tr')$clientLang='tr';
        else $clientLang='en';;


        $links = [
            'atmosfera_auto' => 'https://game.atmob2b.net/24680/roulette_auto',
//            'atmosfera_black' => ['https://game.atmob2b.net/24680/blackjack_a','https://game.atmob2b.net/24680/blackjack_b','https://game.atmob2b.net/24680/blackjack_c','https://game.atmob2b.net/24680/blackjack_d','https://game.atmob2b.net/24680/blackjack_e'][random_int(0,4)],
            'atmosfera_black' => 'https://game.atmob2b.net/24680/blackjack_e',
            'atmosfera_black_a' => 'https://game.atmob2b.net/24680/blackjack_a',
            'atmosfera_black_b' => 'https://game.atmob2b.net/24680/blackjack_b',
            'atmosfera_black_c' => 'https://game.atmob2b.net/24680/blackjack_c',
            'atmosfera_black_d' => 'https://game.atmob2b.net/24680/blackjack_d',
            'atmosfera_black_e' => 'https://game.atmob2b.net/24680/blackjack_e',
            'atmosfera_cock' => 'https://game.atmob2b.net/24680/roulette_cocktail',
            'atmosfera_live' => 'https://game.atmob2b.net/24680/roulette_eng',
            'atmosfera_keno' => 'https://game.atmob2b.net/24680/keno',
            'atmosfera_music' => 'https://game.atmob2b.net/24680/musicwheel',
        ];
//        $links = [
//            'atmosfera_auto' => 'https://game.igramba.com/24680/roulette_auto',
//            'atmosfera_black' => 'https://game.igramba.com/24680/roulette_auto',
//            'atmosfera_cock' => 'https://game.igramba.com/24680/roulette_cocktail',
//            'atmosfera_live' => 'https://game.igramba.com/24680/roulette_eng',
//            'atmosfera_keno' => 'https://game.igramba.com/24680/keno',
//            'atmosfera_music' => 'https://game.igramba.com/24680/musicwheel',
//        ];

        $url = ($links[$gid]?:'https://game.igramba.com/24680/roulette_auto')."?lang=$clientLang&token={$token['token']}";

        echo "<script>
parent.postMessage({cmd:\"closeLoading\"},\"*\");
window.location.href='".$url."';
</script>";
        exit();
    }
}
