<?php
namespace App\Http\Controllers\Game;


use App\Facade\TableName;
use App\Game\AgentLinks;
use App\Game\AgentUser;
use App\Game\GlobalUserInfo;
use App\Game\QuickAccountPass;
use App\Game\QuickAccountPassStore;
use App\Game\Services\AgentService;
use App\Game\Services\OuroGameService;
use App\Game\Services\PgSoftService;
use App\Game\Services\RouteService;
use App\Game\Services\ServerService;
use App\Game\WebChannelConfig;
use App\Http\Controllers\Api\AgentClickController;
use App\Http\Controllers\Controller;
use App\Http\helper\NumConfig;
use App\Http\logic\api\OrderLogic;
use App\Jobs\Order;
use App\Models\AccountsInfo;
use App\Models\AccountWithDrawInfo;
use App\Models\Treasure\GameScoreInfo;
use App\Notification\TelegramBot;
use App\Services\OrderServices;
use App\Services\PayMentService;
use App\Util;
use App\Utility\SetNXLock;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Validator;
use PDO;


// use Yansongda\Pay\Log;

class AgentController extends Controller
{
    protected $client;
    protected $url;
    public function __construct()
    {
        $this->client = new Client();
        $this->url=str_replace('https','http',env('APP_URL'));
    }
    public function modifyBindChannel(Request $request)
    {
        $GlobalUID=$request->GlobalUID;
        $Channel=$request->bindChannel;
        $gUser=GlobalUserInfo::getGameUserInfo('GlobalUID',$GlobalUID);
        $gUser->Channel=$Channel;
        $gUser->save();
        AgentLinks::where('GlobalUID',$GlobalUID)->update(['Channel'=>$Channel]);
        $UserID=ServerService::GlobalToUserID($GlobalUID);
        $user = AccountsInfo::where('UserID',$UserID)->first();
        AccountsInfo::where('UserID',$UserID)->update(['Channel'=>$Channel]);
        if ($user && $user->Channel != $Channel) {
            Log::info("用戶渠道修改", ['UserID'=>$UserID, 'orgChannel'=>$user->Channel, 'Channel'=>$Channel]);
            AgentClickController::changePlatformData($user->Channel, $Channel, $user->RegisterDate ? date('Ymd', strtotime($user->RegisterDate)) : date('Ymd'));
        }
    }
    public function newAgent(Request $request)
    {
        $guser=json_decode($request->gi,true);
        $newacc=json_decode($request->ai,true);
        $ua=json_decode($request->ua,true);
        $gs=json_decode($request->gs,true);

        unset($guser['ID']);

        $pdo = DB::connection('write')->getPdo();

        $pdo->setAttribute(PDO::SQLSRV_ATTR_DIRECT_QUERY, true);
        DB::connection('write')->unprepared("set identity_insert QPAccountsDB.dbo.AccountsInfo on;");
        DB::connection('write')->table('QPAccountsDB.dbo.AccountsInfo')->insert($newacc);
        DB::connection('write')->unprepared("set identity_insert QPAccountsDB.dbo.AccountsInfo off;");
        $pdo->setAttribute(PDO::SQLSRV_ATTR_DIRECT_QUERY, false);

//        DB::connection('write')->table('QPAccountsDB.dbo.UserAgent')->insert($ua);
        DB::connection('write')->table('QPTreasureDB.dbo.GameScoreInfo')->insert($gs);

        GlobalUserInfo::insert($guser);

        $GlobalUID=$guser['GlobalUID'];
        $UserID=$guser['UserID'];
        AgentService::SetUserAgent($GlobalUID, $UserID);
        return apiReturnSuc();
    }
    public function newAgentLink(Request $request)
    {
        AgentLinks::insert(json_decode($request->al,true));
        return apiReturnSuc();
    }
    public function getAgentLinkCode(Request $request)
    {
        return AgentLinks::getByCode($request->code);
    }
    public function getAgentLinks(Request $request)
    {
        $GlobalUID=$request->GlobalUID;
        return AgentLinks::where('GlobalUID',$GlobalUID)->get()->toArray();
    }
    public function getAgentPlayers(Request $request)
    {
        $GlobalUID=$request->GlobalUID;
        $date=$request->date;
        $sql=AgentUser::where('Higher1GUID',$GlobalUID)->select(['UserID','GlobalUID','LinkCode']);
        $datas=[];
        if($sql->exists()) {
            $users = $sql->get();



            $userids=$users->pluck('UserID')->toArray();
            $gusers=GlobalUserInfo::whereIn('UserID', $userids)->select(['GlobalUID','UserID','GameID','NickName','Phone','Email','RegisterDate','LastLogonDate'])->get()->toArray();

            $stats=DB::table('QPRecordDB.dbo.RecordUserTotalStatistics')->whereIn('UserID', $userids)->get()->toArray();


            $useridsToCode=$users->pluck('LinkCode','UserID')->toArray();

            foreach ($gusers as $guser){
                $guser=(array)$guser;
                $guser['contact_info']=$guser['Phone'].'/'.$guser['Email'];
                $guser['link_code']=$useridsToCode[$guser['UserID']];
                unset($guser['Phone'],$guser['Email']);
                $datas[$guser['UserID']]=$guser;


            }
            foreach ($stats as $stat){
                $stat=(array)$stat;
                $guser=&$datas[$stat['UserID']];
                $guser['deposits']=$stat['Recharge'];
                $guser['withdrawal']=$stat['Withdraw']/100;
                $guser['casino_bet']=$stat['TotalBet']/100??($stat['WinScore']+abs($stat['LostScore']))/100;
                $guser['casino_win']=($stat['WinScore']+$stat['LostScore'])/100;
                $guser['sport_bet']=0;
                $guser['sport_win']=0;
            }
        }
        return $datas;
//        'GameID',
//        'NickName',
//        'Subsite',
//        'contact_info',
//        'deposits',
//        'casino_bet',
//        'casino_win',
//        'sport_bet',
//        'sport_win',
//        'withdrawal',
//        'RegisterDate',
//        'LastLoginDate',
//        'created_at',
//        'updated_at',

    }
    public function createAccount(Request $request)
    {
        $getData = $request->query(); // 获取 GET 数据
        $postData = $request->post(); // 获取 POST 数据
        $postData['bfp']=md5(random_bytes(20));
        $postData['type']='guest';


        $response = $this->client->post(  $this->url. '/game/register', [
            'query' => $getData, // 传递 GET 数据
            'form_params' => $postData, // 传递 POST 数据
        ]);
        $res=json_decode($response->getBody(),true);
        return $res['data'];
    }
    public function getAccount(Request $request)
    {
        $uids=$request->uids;
        return GameScoreInfo::whereIn('UserID',$uids)->select(['UserID','Score'])->pluck('Score','UserID')->toArray();
    }
    public function updateAccountScore(Request $request){
        $GlobalUID=$request->GlobalUID;
        $addScore=intval($request->addScore);
        $UserID=GlobalUserInfo::GlobalToUserID($GlobalUID);
        $nowScore=GlobalUserInfo::getScoreByUserID($UserID)*NumConfig::NUM_VALUE;
        if($addScore+$nowScore<0){
            return ['error'=>1,'NowScore'=>$nowScore,'UserID'=>$UserID,'GlobalUID'=>$GlobalUID];
        }
        [$OrgScore,$NowScore]=OuroGameService::AddScore($UserID,$addScore,OuroGameService::REASON_updateAccount);
        return compact('OrgScore','NowScore','UserID','GlobalUID');
    }
    public function userPay(Request $request)
    {
        $sn=$request->sn;
        $GlobalUID=$request->GlobalUID;
        $Score=$request->Score;


        // 获取数据
        $userId = ServerService::GlobalToUserID($GlobalUID);

        $OldScore=GlobalUserInfo::getScoreByUserID($userId);

        //自动识别首冲
        $user_recharge = DB::table(TableName::QPAccountsDB() . 'YN_VIPAccount')
            ->where('UserID', $userId)
            ->value('Recharge') ?: 0;

        $service = new OrderServices();
        // 生成订单信息
        $logic = new OrderLogic();
        $giftid=0;

        $give=0;

        $OrgScore=$Score;

        if(!$user_recharge) {
            // 首冲赠送直接加上
            if($Score>=$service->FirstCharge){

                $give+=$service->FirstChargeGive;
                $giftid=$service->FirstGiftID;
                $Score-=$service->FirstCharge;
//                [$gear_give, $gear_total, $gear_price, $czReason, $cjReason] =
                $service->getPayInfo($giftid, $userId, $service->FirstCharge);

            }else{
                //最小充值起跳
                return ['error'=>1,'MinScore'=>$service->FirstCharge,'msg'=>'You need recharge at least '.$service->FirstCharge.''];
            }
        }

        //确定对应的梯度
        $gear = DB::table('agent.dbo.recharge_gear')
            ->where('favorable_price', '<=',$Score)
            ->where('status', 1)
            ->where('gift_id', 0)
            ->orderByDesc('favorable_price')->first();

        if($gear){
//            [$gear_give, $gear_total, $gear_price, $czReason, $cjReason] = $service->getPayInfo($giftid, $userId, $service->FirstCharge);
            $give+=$gear->give;
        }else if(!$giftid){
            //啥也没有
            $gear = DB::table('agent.dbo.recharge_gear')
                ->where('status', 1)
                ->where('gift_id', 0)
                ->orderBy('favorable_price')->first();
            //最小充值起跳
            return ['error'=>1,'MinScore'=>$gear->favorable_price,'msg'=>'You need recharge at least '.$gear->favorable_price.''];
        }


        $amount = $OrgScore * NumConfig::NUM_VALUE;
        $logic->orderCreate($sn, $amount, 'AgentSystem', $userId, '', $giftid,'','');




        $Recharge = $OrgScore;
        $favorable_price = $Recharge + $give;
        $czReason = 1;
        $cjReason = 45;


        // 增加充值记录
        [$NewScore] = $service->addRecord($userId, $OrgScore, $favorable_price, $sn, $giftid, $Recharge, $czReason, $give, $cjReason, '', '');
        // 成功处理回调
        Order::dispatch([$userId, $OrgScore, $NewScore, $favorable_price, $giftid, $sn]);

        // 修改订单状态
        $body = [
            'pay_status' => 1,
            'finished_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s'),
            'pay_at' => date('Y-m-d H:i:s')
        ];

        DB::connection('write')->table('agent.dbo.order')
            ->where('order_sn', $sn)
            ->update($body);

        return ['success'=>1,'Score'=>$NewScore,'GlobalUID'=>$GlobalUID,'UserID'=>$userId];

    }
    public function userPayout(Request $request)
    {
        $sn=$request->sn;
        $GlobalUID=$request->GlobalUID;
        $score=$request->Score;
        $agentID=$request->agentID;

        $UserID=ServerService::GlobalToUserID($GlobalUID);


        if(!$score||is_float($score)||$score<=0){
            return apiReturnFail(['web.withdraw.score_fail', 'Amount must be an integer value.']);
        }
        $winfo=AccountWithDrawInfo::query()->where('UserID', $UserID)->first();
        if(!$winfo){

            $data = [
                "UserID"          => $UserID,
                "BankNO"          => "$agentID",
                "AccountsBank"    => "$agentID",
                "BankUserName"    => "$agentID",
                "PhoneNumber"     => "$agentID",
                "IFSCNumber"      => "$agentID",
                "EmailAddress"    => "$agentID",
                "Achieves"        => $agentID,
                "PANNumber"       => "$agentID",
                "AdhaarNumber"    => "$agentID",
                "HistoryWithDraw" => 0,
                "BranchBank"      => "$agentID",
                "Win"             => 0,
                "Lost"            => 0,
                "Switch"          => 1,
                "PixNum"          => "$agentID",
                "PixType"         => 66
            ];
            AccountWithDrawInfo::insert($data);

        }


        $dbh = DB::connection()->getPdo();

        $score=$score*NumConfig::NUM_VALUE;

        $sql="DECLARE  @return_value int
        EXEC  @return_value = QPAccountsDB.dbo.GSP_GR_GetWithDraw '$UserID','$score'
        SELECT 'ReturnValue' = @return_value";

//        echo $sql;die;
        $stmt = $dbh->prepare($sql);

        $stmt->execute();


        $retval = $stmt->fetch(\PDO::FETCH_ASSOC);

        try {


//        set @ret = 1	--可提额度不足
//        set @ret = 2	--低于最低可提现金额
//        set @ret = 3	--高于最高可提现金额
//        set @ret = 4	--超过每天提现次数上限
//        set @ret = 5	--身上钱不够
//        set @ret = 6	--开在游戏里面
//        set @ret = 7	--未充值的用户TX额度
            if (isset($retval['ReturnValue'])) {
                $ReturnValue = $retval['ReturnValue'];
                // set @ret = 1 -- Insufficient withdrawal amount
// set @ret = 2 -- Lower than the minimum withdrawal amount
// set @ret = 3 -- Higher than the maximum withdrawal amount
// set @ret = 4 -- Exceeded the daily withdrawal limit
// set @ret = 5 -- Not enough money on hand
// set @ret = 6 -- Opened in the game
// set @ret = 7 -- Undeposited user TX amount
                $errors = [
                    [],
                    ['web.withdraw.no_withdraw_value', "The withdrawable amount is not enough,you need play more games"],
                    ['web.withdraw.too_low', 'Lower than the minimum withdrawal amount'],
                    ['web.withdraw.too_high', 'Higher than the maximum withdrawal amount'],
                    ['web.withdraw.day_max', 'Exceeded the daily withdrawal limit'],
                    ['web.withdraw.no_enouth_score', 'Not enough money on hand'],
                    ['web.withdraw.in_game', 'Sorry, You\'re in game for now'],
                    ['web.withdraw.no_deposit', ' You need deposit first!'],
                ];
                return apiReturnFail($errors[$ReturnValue], [], $ReturnValue == 7 ? 777 : 301);

            }
        }catch (\Exception $e){
            TelegramBot::getDefault()->sendProgramNotify("Agent Withdraw Error:", var_export($retval,true).':'.$e->getTraceAsString());
        }
        $order = DB::table('QPAccountsDB.dbo.OrderWithDraw')->where('UserID', $UserID)->orderByDesc('RecordID')->first();
        if($order) {
            DB::table('QPAccountsDB.dbo.OrderWithDraw')
                ->where('OrderId', $order->OrderId)
                ->update(['BranchBank' => $sn,'ServiceFee'=>0,'WithDraw'=>$order->WithDraw+$order->ServiceFee, 'PixNum' => $sn,'BankUserName'=>'Agent Order'.$agentID]);
            $retval['order'] = $order;
        }else{
            TelegramBot::getDefault()->sendProgramNotify("Agent Withdraw Error:", var_export($retval,true));
        }
        return apiReturnSuc($retval);
    }

}
