<?php


namespace App\Services;


use App\Facade\TableName;
use App\Http\logic\api\BaseApiLogic;
use App\Models\RecordScoreInfo;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

// 裂变逻辑
class Extensions extends BaseApiLogic
{

    // 领取充值额度
    public function receiveRechargeScore($UserID, $Type = 1)
    {
        $redis = Redis::connection();
        $register_invite_switches = $redis->get('register_invite_switches_' . $UserID);
        if ($register_invite_switches == 1) {
            // 您的推广赚金额度被冻结，请联系客服
            $this->error = 'O valor dos ganhos da sua promoção foi congelado, entre em contato com o atendimento ao cliente';
            return false;
        }

        $addScore = $this->recharge($UserID);
        if ($addScore == 0) {
            $this->error = 'No collectable limit';
            return false;
        }

        StoredProcedure::receiveRecharge($UserID, 1);
        StoredProcedure::receiveRecharge($UserID, 2);

        $Surplus = 0;
        $data = compact('addScore', 'Type', 'Surplus');
        return $data;
    }


    // 领取注册额度
    public function receiveRegisterScore($UserID, $clientType = 2, $type = 1)
    {
        $Type = $clientType;

        $redis = Redis::connection();
        $register_invite_switches = $redis->get('register_invite_switches_' . $UserID);

        // 自动审核开关是否开启。
        $AutoVerify = DB::connection('write')->table('QPAccountsDB.dbo.SystemStatusInfo')
            ->where('StatusName', 'AutoVerify')
            ->value('StatusValue');

        if (empty($AutoVerify) || $register_invite_switches == 1) {
            // 您的推广赚金额度被冻结，请联系客服
            $this->error = 'O valor dos ganhos da sua promoção foi congelado, entre em contato com o atendimento ao cliente';
            return false;
        }

        // 可领取额度
        $addScore = $this->register($UserID)['Register'] ?: 0;
        // 剩余额度
        $Surplus = 0;
        $Score = $addScore;

        $data = compact('addScore', 'Type', 'Surplus', 'Score');
        if ($addScore == 0) {
            $this->data = $data;
            $this->error = 'Quantidade insuficiente recebida';
            return false;
        }

        $this->addLog($UserID, $addScore, '', $type);
        
        return $data;

    }


    // 添加领取的记录，改变用户余额--可提现额度
    public function addLog($UserID, $addScore, $orderIds, $Type)
    {

        // 增加用户余额
        DB::connection('write')->table('QPTreasureDB.dbo.GameScoreInfo')
            ->where('UserID', $UserID)
            ->increment('Score', $addScore);


        // 减少自己身上的余额
        DB::table(TableName::agent() . 'register_invite')
            ->where('user_id', $UserID)
            ->decrement('score', $addScore);
        // 添加金币变化记录
        RecordScoreInfo::addScore($UserID, $addScore, 72);
        return true;
    }

    // 获取充值可领额度
    public function recharge($UserID)
    {
        $xiaji = StoredProcedure::recharge($UserID, 1);
        $xiaxiaji = StoredProcedure::recharge($UserID, 2);

        $TotalBalance1 = $xiaji[0]->TotalBalance ?? 0;
        $TotalBalance2 = $xiaxiaji[0]->TotalBalance ?? 0;


        $TotalBalance = $TotalBalance1 + $TotalBalance2;

        return $TotalBalance;
    }

    // 获取可提现额度
    public function remainingBalance($UserID)
    {
        $AccountWithDrawInfo = DB::connection('read')->table('QPAccountsDB.dbo.AccountWithDrawInfo')
            ->where('UserID', $UserID)
            ->selectRaw('Win,Lost')
            ->first();

        if (!$AccountWithDrawInfo) {
            $remainingBalance = 0;
        } else {
            # 可提现余额逻辑：win > 保底值  win + lost 取和，小于保底值 取win  第二步，跟用户余额比较，取小值
            $Score = DB::connection('read')->table('QPTreasureDB.dbo.GameScoreInfo')
                    ->where('UserID', $UserID)
                    ->selectRaw('Score')
                    ->first()->Score ?? 0;

            # win
            $r = $AccountWithDrawInfo->Win;
            # 保底值
            $StatusValue = DB::connection('read')->table('QPAccountsDB.dbo.SystemStatusInfo')
                    ->where('StatusName', 'WithDrawPoint')
                    ->select('StatusValue')
                    ->first()->StatusValue ?? 0;

            #  win + lost  和
            if ($r > $StatusValue) {
                $r = $AccountWithDrawInfo->Win + $AccountWithDrawInfo->Lost;
            }


            // 可提现余额大于用户总余额  默认 用户总余额
            if ($AccountWithDrawInfo->Win <= 0 || $r <= 0) {
                $remainingBalance = 0;
            } elseif ($Score < $r) {
                $remainingBalance = number_float($Score);
            } else {
                $remainingBalance = number_float($r);
            }
        }

        return $remainingBalance;
    }

    // 获取注册可领额度
    public function register($UserID, $Type = 1)
    {
        $Register = DB::table(TableName::agent() . 'register_invite')
            ->where('user_id', $UserID)
            ->value('score');

        // 自动审核开关
        $AutoVerify = DB::connection('write')->table('QPAccountsDB.dbo.SystemStatusInfo')
            ->where('StatusName', 'AutoVerify')
            ->value('StatusValue');
        $redis = Redis::connection();
        $register_invite_switches = $redis->get('register_invite_switches_' . $UserID);

        $Flag = false;
        if ($register_invite_switches == 1 || empty($AutoVerify) || $Register == 0) {
            $Flag = true;
        }

        $Register = empty($Register) ? 0 : $Register;

        return compact('Register', 'Flag');
    }

    // 来源玩家
    public function sourcePlayer($user_profit_log, &$value)
    {

        $UserID = $value->UserID;
        $Type = $value->Type;
        if ($Type == 1) {
            foreach ($user_profit_log as $val) {
                if ($val->UserID == $UserID && $val->Type == $Type) {
                    $value->count = $val->NoteCount;
                    $userArr = explode(',', trim($val->InvitationUserIDs));
                }
            }
        } else {
            $array = DB::connection('write')->table('agent.dbo.extension_user_profit_log')
                ->where('OrderID', 0)
                ->where('UserID', $UserID)
                ->where('Type', $Type)
                ->where('Status', 1)
                ->selectRaw('distinct(InvitationUserIDs)')
                ->get()->map(function ($val) {
                    return (array)$val;
                })->toArray();
            $userArr = array_column($array, 'InvitationUserIDs');
            $value->count = count($userArr);
        }

        if (!empty($userArr)) {
            $userTotalRecharge = DB::connection('read')->table('QPRecordDB.dbo.RecordUserTotalStatistics')
                ->whereIn('UserID', $userArr)
                ->where('Recharge', '>', 0)
                ->selectRaw('count(UserID) userCount,sum(Recharge) RechargeSum')
                ->first();
            $value->rechargeCount = $userTotalRecharge->userCount;
            $value->RechargeSum = number_float($userTotalRecharge->RechargeSum);
        }

        return $value;

    }
}
