<?php
// 文件路径: app/Game/AgentService.php

namespace App\Game\Services;

use App\Game\AgentLinks;
use App\Game\AgentUser;
use App\Game\AgentUserRecord;
use App\Game\GlobalUserInfo;
use App\Http\helper\NumConfig;
use Carbon\Carbon;
use DB;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class AgentService
{
    /**
     * @param $GlobalUID
     * @param $UserID
     * @param $code
     * @return AgentUser
     */
    public static function SetUserAgent($GlobalUID,$UserID,$code=null)
    {
        $agentUser=AgentUser::query()->where('GlobalUID',$GlobalUID)->first();
        if($agentUser){
            return $agentUser;
        }
        $higher1GUID = null;
        $higher2GUID = null;
        $higher3GUID = null;
        $higher4GUID = null;
        $higher1ID = 0;
        $higher2ID = 0;
        $higher3ID = 0;
        $higher4ID = 0;

        // 如果提供了分享 code
        if ($code) {
            $link = AgentLinks::getByCode($code);
            if ($link) {
                $link->increment('RegNum',1);
                $higher1GUID = $link->GlobalUID;
                $higher1ID = $link->UserID;

//                // 查询上级的上级
//                $Inviter = AgentUser::where('GlobalUID', $higher1GUID)->first();
//                if ($Inviter) {
//                    $higher2GUID = $Inviter->Higher1GUID;
//                    $higher2ID = $Inviter->Higher1ID;
//                    if($higher2GUID){
//                        AgentUser::query()->where("GlobalUID",$higher2GUID)->increment('downCount2',1);
//                    }
//
//                    $higher3GUID = $Inviter->Higher2GUID;
//                    $higher3ID = $Inviter->Higher2ID;
//
//                    if($higher3GUID){
//                        AgentUser::query()->where("GlobalUID",$higher3GUID)->increment('downCount3',1);
//                    }
//
//                    $higher4GUID = $Inviter->Higher3GUID;
//                    $higher4ID = $Inviter->Higher3ID;
//
//                    if($higher4GUID){
//                        AgentUser::query()->where("GlobalUID",$higher4GUID)->increment('downCount4',1);
//                    }
//                }else{
//                    $Inviter=AgentUser::create(['GlobalUID' => $higher1GUID,
//                                       'UserID' => $higher1ID]);
//                    $Inviter->increment('downCount1',1);
//
//                }
            }
        }

        // 插入 AgentUser 记录
        $agentUser=AgentUser::create([
            'GlobalUID' => $GlobalUID,
            'UserID' => $UserID,
            'LinkCode' => $code ?? '',
            'Higher1GUID' => $higher1GUID,
            'Higher2GUID' => $higher2GUID,
            'Higher3GUID' => $higher3GUID,
            'Higher4GUID' => $higher4GUID,
            'Higher1ID' => $higher1ID,
            'Higher2ID' => $higher2ID,
            'Higher3ID' => $higher3ID,
            'Higher4ID' => $higher4ID,
            'downCount1' => 0,
            'downCount2' => 0,
            'downCount3' => 0,
            'downCount4' => 0,
        ]);

        // 为新用户创建默认的 Campaign 和 Code
        AgentLinks::getDefaultCampaign($GlobalUID);
        return $agentUser;
    }
    public static function recordPerformance($userId, $amount=0,$type=2)
    {
        try {
            // 获取用户的邀请链
            $user = AgentUser::query()->where('UserID', $userId)->first();


            if(!$user){
                $guser=GlobalUserInfo::getGameUserInfo('UserID',$userId);
                if(!$guser)return;
                $user=self::SetUserAgent($guser->GlobalUID,$userId);
            }

//        $invitationChain= [];
//        if($user->Higher1ID)$invitationChain[]=[$user->Higher1GUID,$user->Higher1ID];
//        if($user->Higher2ID)$invitationChain[]=[$user->Higher2GUID,$user->Higher2ID];
//        if($user->Higher3ID)$invitationChain[]=[$user->Higher3GUID,$user->Higher3ID];
//        if($user->Higher4ID)$invitationChain[]=[$user->Higher4GUID,$user->Higher4ID];
//        $hasReward=$user->TotalReward;

            // 更新 UserAgent 表
            if($user->Higher1ID) {
                $update = [];
                $reward = 10;
                $activity = DB::table('agent.dbo.ActivityTurnplate')
                    ->where('UserID', $user->Higher1ID)
                    ->first();
                if(!$activity){
                    return false;
                }
                if ($type == 1){
                    if($activity->RegisterRewardLimit<200){
                        $reward = rand(10,min(50,max(200-intval($activity->RegisterRewardLimit),10)));
                        $update = ['Amount' => $activity->Amount+$reward,'RegisterRewardLimit' => $activity->RegisterRewardLimit+$reward];
                    }else{
                        return false;
                    }

                }else{
                    $reward = rand(20,50);
                    $update = ['Amount' => $activity->Amount+$reward];
                }
                // BonusLog 入库
                DB::connection('write')->table('agent.dbo.ShareBonusLog')->insert([
                    'UserID'     => $userId,
                    'Higher1ID'  => $user->Higher1ID,
                    'Reward'     => $reward,
                    'Type'       => $type,
                    'ActivityID' => $activity->id,
                    'CreateTime' => Carbon::now()->format('Y-m-d H:i:s'),
                ]);

                if ($update)
                    DB::connection('write')->table('agent.dbo.ActivityTurnplate')->where('UserID', $user->Higher1ID)->update($update);
//            $user->increment('TotalReward', $amount);
            }

            return true;

        } catch (\Exception $exception){
            return false;
        }



        // 遍历上级邀请者并更新业绩
//        foreach ($invitationChain as $level => [$Guid,$Uid]) {
//
//            $_real_level=$level+1;
//            $HigerGUID=null;
//            $HigerID=0;
//            if($_real_level<count($invitationChain)){
//                [$HigerGUID,$HigerID]=$invitationChain[$_real_level];
//            }
//
//            // 记录到 AgentUserRecord 表
//           AgentUserRecord::findOrCreateAndUpdate($Guid,$Uid,$_real_level, $amount,$HigerGUID,$HigerID);
//
//
//        }
//        1、每个用户充值后，您可以获得1R$
//        2、当用户充值总额超过100R$，他们被视为优质用户，每个优质用户你可以获得5R$
//        3、您将收到所有用户存入金额1%的现金返还，每个用户最多可以获得100R$
        if($user->Higher1GUID){
            $parentUser=AgentUser::query()->where('GlobalUID', $user->Higher1GUID)->first();
            //$parentUser->RewardLimit  默认值为100，可以调节
            if($parentUser&&$user->LinkRewards<$parentUser->RewardLimit*NumConfig::NUM_VALUE) {


                //找到具体活动链接
                if ($user->LinkCode) {
                    $link = AgentLinks::getByCode($user->LinkCode);
                } else {
                    $link = AgentLinks::getDefaultCampaign($user->Higher1GUID);
                }
                //新付费
                if ($hasReward == 0) {
                    $link->increment('PayUserNum', 1);
                    $link->increment('PayRewards', 1 * NumConfig::NUM_VALUE);
                    $user->increment('LinkRewards', 1 * NumConfig::NUM_VALUE);
                }
                //超过100R$
                if ($hasReward < 100 * NumConfig::NUM_VALUE && $hasReward + $amount >= 100 * NumConfig::NUM_VALUE) {
                    $link->increment('PayRewards', 5 * NumConfig::NUM_VALUE);
                    $user->increment('LinkRewards', 5 * NumConfig::NUM_VALUE);
                }
                //1% $user->RewardRate 默认值100 /10000 =1%
                $link->increment('PayTotal', $amount);
                $link->increment('PayRewards', $amount *$user->RewardRate / 10000);
                $user->increment('LinkRewards', $amount *$user->RewardRate / 10000);
            }
        }
    }



    public static function getShareLink($GlobalUID=null,$ActName='Default')
    {
        if(!$GlobalUID){
            if(GlobalUserInfo::$me){
                $GlobalUID=GlobalUserInfo::$me->GlobalUID;
            }else{
                $GlobalUID='';
            }
        }
        $h5link = env('H5_LINK', 'https://www.usslot777.com/');


        $httpserver = $_SERVER['HTTP_ORIGIN']
            ?? ($_SERVER['HTTP_REFERER'] ?? $h5link);

        $httpserver = rtrim($httpserver, '/');

        $h5link = $httpserver.'/';

        if($ActName=='WheelFree100') {
            $link = $h5link .'?act='. self::encodeAct($GlobalUID, $ActName);
        }else{
            $link = $h5link .'act='.self::encodeAct($GlobalUID, $ActName);
        }
        return $link;
    }
    public static function encodeAct($GlobalUID,$ActName)
    {
        if(empty($GlobalUID))return Str::random(6);
        $link=AgentLinks::getCampaign($GlobalUID,$ActName);
        return $link->Code;

    }

    /**
     * @param Request $request
     * @return AgentLinks|int
     */
    static public function decodeAct(Request $request)
    {
        $act = $request->input("act","");
        if(empty($act)){
            return 0;
        }
//        $act=self::customDecrypt($act);
//        $act=explode("|",$act);
//        if(count($act)<2){
//            return -1;
//        }
//        [$ActName,$SpreadID,$SpreadGUID]=$act;
        $agentLink=AgentLinks::getByCode($act);
        if(!$agentLink)return -1;

        return $agentLink;
    }


    private static function getLevelName($level)
    {
        $levels = ['top', 'second', 'third', 'fourth'];
        return $levels[$level] ?? 'unknown';
    }
}
