<?php


namespace App\Http\Controllers\Game;


use App\dao\Pay\AccountPayInfo;
use App\Facade\TableName;
use App\Game\AgentLinks;
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){
            if($activity->Created<time()-86400*3 && $activity->State == 0){ //超过3天
                $turnplate = [
                    'times' => 1,
                    'countdown' => 86400*3,
                    'total_amount' => 10000,
                    'collect_amount' => 0
                ];

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

                DB::connection('write')->table('agent.dbo.ActivityTurnplateHistory')->insert($insertData);
                DB::connection('write')->table('agent.dbo.ActivityTurnplate')->where('UserID', $UserID)->delete();

            }else{
                if($activity->LastFreeTimes+86400-3600<time()){
                    $activity->OldTimes += 1;
                    DB::connection('write')->table('agent.dbo.ActivityTurnplate')->where('UserID', $UserID)->update(['OldTimes'=> $activity->OldTimes,'LastFreeTimes' => time()]);
                }
                $turnplate = [
                    'times' => $activity->NewTimes+$activity->OldTimes,
                    'countdown' => $activity->Created+86400*3-time(),
                    'total_amount' => 10000,
                    'collect_amount' => intval($activity->Amount)
                ];
            }
        }else{
            $turnplate = [
                'times' => 1,
                'countdown' => 86400*3,
                'total_amount' => 10000,
                '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 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;

            } 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' => 100];
                }
            }
        }
        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' => 100];

            }

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



        if (Redis::exists('turnplate_numbers_1_'.$FPID)) {
            $numbers = Redis::get('turnplate_numbers_1_'.$FPID);
            $numbers = json_decode($numbers,true);
        } else{
            $numbers = [];
//            for($i=0;$i<50;$i++){
//                array_push($numbers,'55'.rand(1234,9876).''.rand(1234,9876).''.rand(12,98));
//            }
            $result=DB::connection('write')->select("SELECT TOP 20 ap.PhoneNum
    FROM
        QPAccountsDB.dbo.AccountPhone ap
    INNER JOIN
        QPAccountsDB.dbo.AccountsInfo ai ON ap.UserID = ai.UserID
    WHERE
        DATEDIFF(day, ai.LastLogonDate, GETDATE()) > 7
    ORDER BY
        NEWID()");
            $numbers=array_map(function($item){
                return '55'.trim($item->PhoneNum);
            },$result);
            Redis::set('turnplate_numbers_1_'.$FPID,json_encode($numbers));
            Redis::expire('turnplate_numbers_1_'.$FPID, 86400*3);
        }
//        $httpserver=$_SERVER['HTTP_ORIGIN']??(@$_SERVER['HTTP_REFERER']?trim($_SERVER['HTTP_REFERER'],"/"):"https://24680.com");
//        $link = $httpserver .'/#/cashwheel?act='.self::encodeAct($GlobalUID,'WheelFree100');
        $link = AgentService::getShareLink($GlobalUID??"",'WheelFree100');

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

    public function kanOp(Request $request){
        //这里需要实现一个逻辑，就是我砍一刀我刚才拿配置还没注册
        $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 != 0){
//            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(9400,9600);
            $type = 2;
        }else{
            if($newTimes){
                if($money<=9600){
                    $type=2;
                    $result = rand(150,200);
                }elseif ($money>=9601 && $money<=9800){
                    if(rand(0,100)>=50){
                        $type=2;
                        $result = rand(20,100);
                    }else{
                        $type=4;
                        $result = 100;
                    }
                }elseif ($money>=9801 && $money<=9950){
                    if(rand(0,100)>=0){
                        $type=2;
                        $result = rand(2,12);
                    }else{
                        $type=1;
                        $result = 0;
                    }
                }elseif ($money>=9951 && $money<=9999){
                    if(rand(0,100)>=0){
                        $type=2;
                        $result = min(rand(1,2),10000-$money);
                    }else{
                        $type=1;
                        $result = 0;
                    }
                }
            }else{
                if($money<=9600){
                    $type=2;
                    $result = rand(150,200);
                }elseif ($money>=9601 && $money<=9800){
                    if(rand(0,100)>=50){
                        $type=2;
                        $result = rand(10,50);
                    }else{
                        $type=1;
                        $result = 0;
                    }
                }elseif ($money>=9801 && $money<=9950){
                    if(rand(0,100)>=60){
                        $type=2;
                        $result = rand(1,2);
                    }else{
                        $type=1;
                        $result = 0;
                    }
                }elseif ($money>=9951 && $money<=9999){
                    $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>=10000?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']);
        }


        DB::connection('write')->table('agent.dbo.ActivityTurnplate')->where('UserID', $UserID)->delete();

        $insertData = json_decode(json_encode($activity),true);
        $insertData['updated'] = time();
        DB::connection('write')->table('agent.dbo.ActivityTurnplateHistory')->insert($insertData);

        //领钱
        DB::connection('write')->table('QPTreasureDB.dbo.GameScoreInfo')->where('UserID', $UserID)->increment('Score', 10000);

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


    public function kanShare(Request $request) {

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


    }





}
