<?php


namespace App\Http\Controllers\Game;


use App\dao\Pay\AccountPayInfo;
use App\Facade\TableName;
use App\Game\AgentLinks;
use App\Game\AgentUser;
use App\Game\GlobalUserInfo;
use App\Game\Services\AgentService;
use App\Http\helper\NumConfig;
use App\Models\AccountsInfo;
use App\Services\ExtensionCopy;
use App\Services\Extensions;
use App\Util;
use App\Utility\SetNXLock;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Str;

// 裂变入口
// 数值统一要除 100
class ExtensionsController
{


    public static function customEncrypt($string) {

        $string = (string) $string;
        // 自定义加密逻辑，这里使用简单的替换算法
        $characters = 'e8fi0mKL9MNOno7pqaDE1FghGb|-3cduvwxyzA6BCHIJPjklQRS4TU2VWXrs5tYZ';
        $result = '';

        for ($i = 0; $i < strlen($string); $i++) {
            $char = $string[$i];
            $pos = strpos($characters, $char);
            $newPos = ($pos + 5) % strlen($characters); // 替换规则，这里偏移值为5，可以根据需求修改
            $result .= $characters[$newPos];
        }

        return $result;
    }



    public static function customDecrypt($string) {
        // 自定义解密逻辑，与加密逻辑相反
        $characters = 'e8fi0mKL9MNOno7pqaDE1FghGb|-3cduvwxyzA6BCHIJPjklQRS4TU2VWXrs5tYZ';
        $result = '';

        for ($i = 0; $i < strlen($string); $i++) {
            $char = $string[$i];
            $pos = strpos($characters, $char);
            $newPos = ($pos - 5 + strlen($characters)) % strlen($characters); // 解密的反向操作
            $result .= $characters[$newPos];
        }

        return $result;
    }

    private function getTurnplateActivity(Request $request)
    {
        $user = $request->user()??LoginController::checkLogin($request);
        $UserID = @$user->UserID ??  0;
        $GlobalUID = @$user->GlobalUID ??  "";
        $FPID=$request->input("bfp","");


        $where=[];
        if(!$where&&$UserID)$where=['UserID',$UserID];
        if(!$where&&!empty($GlobalUID))$where=['GlobalUID',$GlobalUID];
        if(!$where&&!empty($FPID))$where=['FPID',$FPID];


        if(empty($where)){
            $where=['UserID',0];
        }

        $activity = DB::table('agent.dbo.ActivityTurnplate')
            ->where([$where])
            ->first();
        //用UserID没拿到，那看指纹ID
        if(!$activity&&$UserID){
            $activity = DB::table('agent.dbo.ActivityTurnplate')
                ->where('FPID',$FPID)
                ->where('UserID',0)
                ->first();
            //顺便更新下
            if($activity&&$UserID){
                DB::table('agent.dbo.ActivityTurnplate')
                    ->where('FPID',$FPID)->update(['UserID'=>$UserID,'GlobalUID'=>$GlobalUID]);
            }
        }

        $insert = 0;
        if($activity){
            $turnplate = [
                'times' => $activity->NewTimes+$activity->OldTimes,
                'countdown' => $activity->Created+86400*3-time(),
                'total_amount' => 4000,
                'collect_amount' => intval($activity->Amount)
            ];
        }else{
            $turnplate = [
                'times' => 1,
                'countdown' => 86400*3,
                'total_amount' => 4000,
                'collect_amount' => 0
            ];
            $insert = 1;
        }
        if($insert){
            $data = [
                'UserID' => $UserID,
                'GlobalUID' => $GlobalUID,
                'FPID' => $FPID,
                'Amount' => $turnplate['collect_amount'],
                'NewTimes' => 1,
                'Created' => time(),
                'LastFreeTimes' => time()
            ];
            $ID=DB::table('agent.dbo.ActivityTurnplate')->insertGetId($data);
            $activity=DB::table('agent.dbo.ActivityTurnplate')->where('ID',$ID)->first();
        }
        return compact('activity','turnplate','user','where');
    }


    public function triggerInvite(Request $request)
    {
        $user = $request->user()??LoginController::checkLogin($request);
        $UserID = @$user->UserID ??  0;
        $activityController = new ActivityController();
        $activityController->triggerInvite($UserID);
        return apiReturnSuc();
    }

    public function turnplate(Request $request){

        $data=$this->getTurnplateActivity($request);
        $activity=$data['activity'];
        $turnplate=$data['turnplate'];
        $user=$data['user'];
        $where=$data['where'];
        $FPID=$request->bfp??"";
        $UserID=0;
        $GlobalUID="";
        if($activity) {
            try {
                $UserID = intval($activity->UserID ?? 0);
                $FPID = $activity->FPID;
                $GlobalUID = $activity->GlobalUID;
//                $activityController = new ActivityController();
//                $activityController->triggerInvite($UserID);

            } catch (\Exception $exception) {
                Log::error("turnplate:" . $exception->getMessage(), compact('data', 'user', 'where'));
            }
        }
        $redisKey = 'turnplate_index_'.$where[1];

        $res = SetNXLock::getExclusiveLock($redisKey, 5);

        if (!$res) {
            return apiReturnFail(['web.turnplate.toofast','Requested too frequently']);
        }

        $myRecord = [];
        $dao = new AccountPayInfo();

        $myRecordList = DB::connection('write')->table('agent.dbo.ActivityTurnplateHistory')->where('State',1)->where([$where])->get();

        if($myRecordList && $UserID){
            $account = new AccountsInfo();
            $myInfo = $account->getUserPhone($UserID);
            $userInfo = DB::table(TableName::QPAccountsDB() . 'AccountsInfo')
                ->where('UserID', $UserID)
                ->first();
            if($userInfo) {
                $nickname = $userInfo->NickName;
                foreach ($myRecordList as $itemM) {
                    $myRecord[] = ['phone' => $myInfo ?: '', 'name' => $nickname, 'amount' => 40];
                }
            }
        }
        if (Redis::exists('turnplate_record1')) {
            $record = Redis::get('turnplate_record1');
            $record = json_decode($record,true);
        } else{
            $record = [];
            for($i=0;$i<50;$i++){
                $record[] = ['phone' => rand(1234, 9876) . '' . rand(1234, 9876) . '' . rand(12, 98), 'name' => rand(1, 100) > 10 ? $dao->randUserName('') : 'U' . rand(1234, 9876), 'amount' => rand(40,2000)];

            }

            Redis::set('turnplate_record1',json_encode($record));
            Redis::expire('turnplate_record1', 100);
        }



        $numbers = [];
        $link = AgentService::getShareLink($GlobalUID??"",'WheelFree100');

        SetNXLock::release($redisKey);
        return apiReturnSuc(compact('turnplate', 'record','link','numbers','myRecord'));
    }

    public function kanOp(Request $request){
//        return;
        //这里需要实现一个逻辑，就是我砍一刀我刚才拿配置还没注册
        $data=$this->getTurnplateActivity($request);
        $activity=$data['activity'];
        $turnplate=$data['turnplate'];
        $user=$data['user'];
        $where=$data['where'];
        $UserID=intval($activity->UserID);
        $FPID=$activity->FPID;
        $GlobalUID=$activity->GlobalUID;


        if($activity->State == 2){
//            return apiReturnFail('invalid state');
            return apiReturnFail(['web.turnplate.invalid','Invalid state']);
        }

//        if($activity->Created<time()-86400*3){
////            return apiReturnFail('expired');
//            return apiReturnFail(['web.turnplate.expired','Activity Expired']);
//        }
        $type=1;
        $result = 0;
        $money = $activity->Amount;
        $newTimes = $activity->NewTimes;
        $oldTimes = $activity->OldTimes;
        if($newTimes+$oldTimes<1){
            return apiReturnFail(['web.turnplate.notimes','No times']);

        }

        $redisKey = 'turnplate_kan_'.$UserID;
        $res = SetNXLock::getExclusiveLock($redisKey, 5);
        if (!$res) {
            return apiReturnFail(['web.turnplate.toofast','Requested too frequently']);

        }

        if($activity->TotalKan == 0){
            $result = rand(3000,3600);
            $type = 2;
        }else{
            $type=1;
            $result = 0;
        }

        DB::connection('write')->table('agent.dbo.ActivityTurnplate')->where('UserID', $UserID)->update(['NewTimes'=> $newTimes?$activity->NewTimes-1:$activity->NewTimes,'OldTimes'=> (!$newTimes)?$activity->OldTimes-1:$activity->OldTimes,'Amount' => $money+$result,'State' =>$money+$result>=4000?1:0,'TotalKan' => $activity->TotalKan+1 ]);
        SetNXLock::release($redisKey);
        return apiReturnSuc(['type' => $type,'bonus' => $result,'times' => $oldTimes+$newTimes-1,'collect_amount' => intval($money+$result)]);

    }


    public function kanBonus(Request $request) {
        $UserID = $request->user() ?$request->user()->UserID :  0;
        $start = 0;
        $end = 0;
        $activity = DB::table('agent.dbo.ActivityTurnplate')
            ->where('UserID',$UserID)->first();
//        if($activity->State != 1){
//
//            return apiReturnFail(['web.turnplate.invalid','Invalid state']);
//
//        }

        $redisKey = 'turnplate_bonus_'.$UserID;
        $res = SetNXLock::getExclusiveLock($redisKey, 5);
        if (!$res) {
            return apiReturnFail(['web.turnplate.toofast','Requested too frequently']);
        }

        $exchangeScore = intval($activity->Amount ?? 0);
        if ($exchangeScore < 4000) {
            SetNXLock::release($redisKey);
            return apiReturnFail(['web.turnplate.no_amount','No reward can be collected now']);
        }

        $withdrawInfo = DB::table(TableName::QPAccountsDB() . 'AccountWithDrawInfo')
            ->where('UserID', $UserID)
            ->first();
        if (!$withdrawInfo) {
            SetNXLock::release($redisKey);
            return apiReturnFail(['web.turnplate.withdraw_info_missing','Please complete withdrawal info first']);
        }

//        $taxRate = DB::table(TableName::QPAccountsDB() . 'SystemStatusInfo')
//            ->where('StatusName', 'WithDrawTax')
//            ->value('StatusValue') ?? 0;
//        $tax = (int) round($exchangeScore * intval($taxRate) / 10000);
//        $withDrawAmount = max($exchangeScore - $tax, 0);
//        $orderId = 'TP' . date('YmdHis') . strtoupper(Str::random(4));

        $insertData = json_decode(json_encode($activity), true);
        $insertData['updated'] = time();
        unset($insertData['id']);

        $writeConn = DB::connection('write');
        $recordTable = TableName::QPRecordDB() . 'RecordUserTotalStatistics';

        $historyWithDraw = intval($withdrawInfo->HistoryWithDraw ?? 0);
        $winAmount = intval($withdrawInfo->Win ?? 0);
        $newHistory = max(0, $historyWithDraw - $exchangeScore);
        $newWin = $winAmount + $exchangeScore;

        try {
            $writeConn->beginTransaction();

            $writeConn->table('agent.dbo.ActivityTurnplate')
                ->where('UserID', $UserID)
                ->delete();

            $writeConn->table('agent.dbo.ActivityTurnplateHistory')->insert($insertData);

            $writeConn->table(TableName::QPAccountsDB() . 'OrderWithDraw')->insert([
                'UserID' => $UserID,
                'AccountsBank' => $withdrawInfo->AccountsBank ?? '',
                'PhoneNumber' => $withdrawInfo->PhoneNumber ?? '',
                'IFSCNumber' => $withdrawInfo->IFSCNumber ?? '',
                'BankUserName' => $withdrawInfo->BankUserName ?? '',
                'EmailAddress' => $withdrawInfo->EmailAddress ?? '',
                'PANNumber' => $withdrawInfo->PANNumber ?? '',
                'AdhaarNumber' => $withdrawInfo->AdhaarNumber ?? '',
                'WithDraw' => $exchangeScore,
                'State' => 1,
                'AiCheckState' => 0,
                'BankNO' => $withdrawInfo->BankNO ?? '',
                'ServiceFee' => 0,
                'CreateDate' => now(),
                'BranchBank' => $withdrawInfo->BranchBank ?? '',
                'OrderId' => $activity->id,
                'PixNum' => $withdrawInfo->PixNum ?? '',
                'PixType' => $withdrawInfo->PixType ?? 1,
                'score_type' => 2
            ]);

            $writeConn->table(TableName::QPAccountsDB() . 'AccountWithDrawInfo')
                ->where('UserID', $UserID)
                ->update([
                    'HistoryWithDraw' => $newHistory,
                    'Win' => $newWin,
                ]);

            $stats = $writeConn->table($recordTable)->where('UserID', $UserID)->first();
            if ($stats) {
                $writeConn->table($recordTable)
                    ->where('UserID', $UserID)
                    ->update(['DrawBase' => intval($stats->DrawBase ?? 0) + $exchangeScore]);
            } else {
                $writeConn->table($recordTable)
                    ->insert(['UserID' => $UserID, 'DrawBase' => $exchangeScore]);
            }

            // 邀请人发起提现后，解除其下所有被邀请人的绑定关系
            AgentUser::query()
                ->where('Higher1ID', $UserID)
                ->update([
                    'Higher1GUID' => null,
                    'Higher1ID'   => 0,
                    'Higher2GUID' => null,
                    'Higher2ID'   => 0,
                    'Higher3GUID' => null,
                    'Higher3ID'   => 0,
                    'Higher4GUID' => null,
                    'Higher4ID'   => 0,
                    'LinkCode'    => '',
                ]);

            $writeConn->commit();
        } catch (\Throwable $e) {
            $writeConn->rollBack();
            SetNXLock::release($redisKey);
            Log::error('turnplate bonus failed', [
                'user_id' => $UserID,
                'error' => $e->getMessage()
            ]);
            return apiReturnFail(['web.turnplate.bonus_fail','failed'], [], 500);
        }

//        select @AccountsBank = AccountsBank,@BankUserName = BankUserName,@Switch=Switch,
//         @PhoneNumber = PhoneNumber,@IFSCNumber = IFSCNumber,@EmailAddress = EmailAddress,
//         @PANNumber = PANNumber,@AdhaarNumber = AdhaarNumber,@BankNO = BankNO,@BranchBank = BranchBank,@PixNum=PixNum,@PixType=PixType
//        from QPAccountsDB.dbo.AccountWithDrawInfo where UserID = @UserID

//        insert into QPAccountsDB.dbo.OrderWithDraw (UserID,AccountsBank,PhoneNumber,IFSCNumber,
//            BankUserName,EmailAddress,PANNumber,AdhaarNumber,WithDraw,[State],AiCheckState,BankNO,ServiceFee,CreateDate,BranchBank,OrderId,PixNum,PixType)
//        values(@UserID,@AccountsBank,@PhoneNumber,@IFSCNumber,@BankUserName,@EmailAddress,@PANNumber,@AdhaarNumber,@ExchangeScore-@TAX,1,
//            0,@BankNO,@TAX,GETDATE(),@BranchBank,@OrderId,@PixNum,@PixType)


        //update QPAccountsDB.dbo.AccountWithDrawInfo set HistoryWithDraw = HistoryWithDraw-@ExchangeScore,Win=Win+@ExchangeScore where UserID = @UserID
        //
        //        UPDATE QPRecordDB.dbo.RecordUserTotalStatistics SET DrawBase=DrawBase+@ExchangeScore WHERE UserID=@UserID





        SetNXLock::release($redisKey);
        return apiReturnSuc(['Amount' => 0]);
    }


    public function kanShare(Request $request) {
        return;

        $user = LoginController::checkLogin($request);

        $UserID = @$user->UserID ??  0;
        $GlobalUID = $user->GlobalUID ??  "";
        $FPID=$request->input("bfp","");
        $start = 0;
        $end = 0;

        $act = AgentService::decodeAct($request);
        if(is_numeric($act)) {
            if ($act == 0) {
                return apiReturnFail(['web.activity.invalid_act', 'No act found']);
            } else if ($act == -1) {
                return apiReturnFail(['web.activity.invalid_act', 'Invalid String']);
            }
        }


//        $httpserver=$_SERVER['HTTP_ORIGIN']??trim($_SERVER['HTTP_REFERER'],"/");
//        $link = $httpserver .'/?act='.$this->customEncrypt("tp|".$UserID."|".$GlobalUID);
        $SpreadID =$act->UserID;
        if(intval($SpreadID)<10000 || $UserID == $SpreadID){
//            var_dump($UserID,$SpreadID);
            return apiReturnFail(['web.activity.invalid_act_uid','Invalid UserID']);
        }


        $redisKey = 'turnplate_share_'.$UserID;
        $res = SetNXLock::getExclusiveLock($redisKey, 5);
        if (!$res) {
            return apiReturnFail(['web.turnplate.to_many_request','Too many request']);
        }


        $activity = DB::table('agent.dbo.ActivityTurnplate')
            ->where('UserID',$SpreadID)->first();

        if($activity){
            //检查是否帮助过
//            $where=[['HelpUserID',$SpreadID]];
//            $where[]=$UserID?['UserID',$UserID]:['FPID',$FPID];
            $findUserID=$UserID;
            if($UserID==0)$findUserID=999999999;
            $alreadyHelp=DB::table("agent.dbo.ActivityTurnplateHelpRecord")
                ->whereRaw("HelpUserID='$SpreadID' and (UserID=$findUserID or FPID='$FPID')")->exists();
            if($alreadyHelp){
                return apiReturnFail(['web.turnplate.already_help','Already Help']);
            }
            DB::table("agent.dbo.ActivityTurnplateHelpRecord")->insert([
                'UserID' => $UserID,
                'GlobalUID' => $GlobalUID,
                'FPID' => $FPID,
                'HelpUserID' => $SpreadID,
                'HelpFPID' => $activity->FPID,
                'HelpGlobalUID' => $activity->GlobalUID,
            ]);
            //给帮助的+1
            DB::connection('write')->table('agent.dbo.ActivityTurnplate')->where('UserID',$SpreadID)->update(['OldTimes' => $activity->OldTimes+1]);

            SetNXLock::release($redisKey);
            $helpUser=GlobalUserInfo::getGameUserInfo('GlobalUID',$activity->GlobalUID);

            return apiReturnSuc(['NickName'=>$helpUser->NickName,'GameID'=>$helpUser->GameID,'GlobalUID'=>$helpUser->GlobalUID],['turnplate.help_success',"Thanks for your help ,$helpUser->NickName get new chance!"]);
        }else{
            SetNXLock::release($redisKey);
            return apiReturnFail(['web.activity.wrong_act','Invalid act string.']);
        }


    }





}
