<?php


namespace App\Models;


use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class ExtensionUserProfitLog
{
    public function add($UserID, $Type, $InvitationUserID, $Level)
    {

        // 获取深度 -- 邀请用户
        $NoteCount = $this->addLog($UserID, $Type, $InvitationUserID, $Level);

        // 查询用户产生总得金额--匹配档位
        $verify = $this->verify($UserID, $Type);

        $toGold = $verify['TotalScore'] ?? 0;   // 待审额度

        $totalScore = $verify['allScore'] ?? 0;   // 审核通过 + 待审
        $Status = $verify['Status'] ?? 0;

        // 查询配置
        $config = DB::connection('write')->table('agent.dbo.extension_config')
            ->where('quota_min', '<=', $totalScore)
            ->where('quota_max', '>=', $totalScore)
            ->where('type', $Type)
            ->first();

        $addScore = 0;
        if ($config) {


            if ($Type == 1) {
                if ($Level == 1 && $NoteCount >= $config->level_quota_number) {
                    $addScore = mt_rand($config->level_quota_min, $config->level_quota_max);
                } elseif ($Level == 2 && $NoteCount >= $config->two_level_quota_number) {
                    $addScore = mt_rand($config->two_level_quota_min, $config->two_level_quota_max);
                }
            }

            if ($Type == 2) { // 对局 =》 获取局数
                $redis = Redis::connection('test');
                $NoteCount = $redis->get($InvitationUserID);

                if ($Level == 1 && $NoteCount % $config->level_quota_number == 0) {
                    $addScore = mt_rand($config->level_quota_min, $config->level_quota_max);
                } elseif ($Level == 2 && $NoteCount % $config->two_level_quota_number == 0) {
                    $addScore = mt_rand($config->two_level_quota_min, $config->two_level_quota_max);
                }
            }

            Log::channel('invitation')->info($UserID . ' 第一步的随机值：' . $addScore);

            if ($addScore > 0) {


                // 读取上限配置
                $upperLimit = DB::connection('write')->table('QPAccountsDB.dbo.SystemStatusInfo')
                        ->where('StatusName', 'UpperLimit')
                        ->first()->StatusValue ?? 0;

                Log::channel('invitation')->info($UserID . ' 读取上限配置：' . $upperLimit);


                // 查询是否审核通过，没有审核通过走默认配置
                if ($Status == 0) {

                    Log::channel('invitation')->info($UserID . ' 值 ' . ($toGold + $addScore));


                    // 默认配置1 达到90%-96%这个“达成额度”区间以后，每次生效增长额度按照3%*真实生效额度来增加


                    $upperLimitMin = $upperLimit * 0.9;
                    $upperLimitMax = $upperLimit * 0.96;

//                    if ($toGold >= $upperLimitMin && $toGold <= $upperLimitMax) {
//                        $addScore = $addScore * 0.03;
//                        Log::channel('invitation')->info($UserID . ' 默认配置1 ' . $addScore);
//                    }


                    // 默认配置2 达到96%-99%这个“达成额度”区间以后，每次生效增长额度按照1%*真实生效额度来增加.

                    $upperLimitMin = $upperLimit * 0.96;
                    $upperLimitMax = $upperLimit * 0.99;


//                    if ($toGold > $upperLimitMin && $toGold <= $upperLimitMax) {
//                        $addScore = $toGold + ($addScore * 0.01);
//                        Log::channel('invitation')->info($UserID . ' 默认配置1 ' . $addScore);
//                    }


                    // 默认配置3 达到99%-99.99%这个“达成额度”区间以后，增长为0。反正要防止用户永远也达不到100%的额度。
                    $upperLimitMin = $upperLimit * 0.99;
                    $upperLimitMax = $upperLimit * 0.9999;

//                    if ($toGold > $upperLimitMin && $toGold <= $upperLimitMax) {
//                        $addScore = 0;
//                        Log::channel('invitation')->info($UserID . ' 默认配置1 ' . $addScore);
//                    }

                    // 极端判断
//                    if ($toGold + $addScore > $upperLimit * 0.99 && $toGold < $upperLimit * 0.9) {
//                        $addScore = ($upperLimit * 0.9) - $toGold;
//                    } elseif ($toGold + $addScore > $upperLimit * 0.99 && $toGold < $upperLimit * 0.96) {
//                        $addScore = ($upperLimit * 0.96) - $toGold;
//                    } elseif ($toGold + $addScore > $upperLimit * 0.99 && $toGold < $upperLimit * 0.99) {
//                        $addScore = ($upperLimit * 0.99) - $toGold;
//                    } elseif ($toGold + $addScore > $upperLimit) {
//                        $addScore = 0;
//                    }

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

                    if ($autoVerify == 0) {
                        // 极端判断
                        if ($toGold + $addScore > $upperLimit * 0.99 && $toGold < $upperLimit * 0.99) {
                            $addScore = ($upperLimit * 0.99) - $toGold;
                        } elseif ($toGold + $addScore > $upperLimit) {
                            $addScore = 0;
                        }
                        Log::channel('invitation')->info($UserID . ' 默认配置4 ' . $addScore);
                    }

                } else {
//                    if ($addScore > $upperLimit) {
//                        $addScore = $upperLimit * 0.9;
//                    }
                }


                Log::channel('invitation')->info($UserID . ' 要修改的分数 ' . $addScore);

                // 修改分数
                if ($Type == 1) {
                    DB::connection('write')->table('agent.dbo.extension_user_profit_log')
                        ->where('UserID', $UserID)
                        ->where('Status', 0)
                        ->where('Type', $Type)
                        ->where('Level', $Level)
                        ->update(['toGold' => DB::raw("toGold + $addScore"), 'Status' => 1]);
                } else {
                    DB::connection('write')->table('agent.dbo.extension_user_profit_log')
                        ->where('InvitationUserIDs', $InvitationUserID)
                        ->where('Status', 0)
                        ->where('Type', $Type)
                        ->where('Level', $Level)
                        ->update(['toGold' => DB::raw("toGold + $addScore"), 'Status' => 1]);
                }

                DB::connection('write')->table('agent.dbo.extension_verify')
                    ->where('UserID', $UserID)
                    ->where('Type', $Type)
                    ->update(['TotalScore' => DB::raw("TotalScore + $addScore")]);

                // 生成订单
                if ($toGold + $addScore >= $upperLimit) {
                    $data = [
                        'UserID' => $UserID,
                        'Score' => $upperLimit,
                        'CreateAt' => date('Y-m-d H:i:s'),
                        'Type' => $Type,
                        'OverflowScore' => abs($upperLimit - ($toGold + $addScore))
                    ];
                    $orderID = DB::connection('write')->table('agent.dbo.extension_user_profit_order')->insertGetId($data);

                    DB::connection('write')->table('agent.dbo.extension_user_profit_log')
                        ->where('UserID', $UserID)
                        ->where('Type', $Type)
                        ->where('OrderID', 0)
                        ->update(['OrderID' => $orderID]);

                    // 修改记录
                    DB::connection('write')->table('agent.dbo.extension_verify_log')
                        ->where('UserID', $UserID)
                        ->where('OrderID', 0)
                        ->where('Type', $Type)
                        ->update(['UpdateTime' => date('Y-m-d H:i:s'), 'OrderID' => $orderID, 'FinalScore' => $upperLimit]);

                    // 改变完成审核金额度
                    DB::connection('write')->table('agent.dbo.extension_verify')
                        ->where('UserID', $UserID)
                        ->where('Type', $Type)
                        ->update(['FinalScore' => DB::raw("FinalScore + $upperLimit"), 'TotalScore' => DB::raw("TotalScore - $upperLimit"), 'Status' => 0]);

                    Log::channel('invitation')->info($UserID . ' 生成订单 ' . \GuzzleHttp\json_encode($data));
                }
            }
        }

    }




    public function addLog($UserID, $Type, $InvitationUserID, $Level)
    {

        $NoteCount = 1;

        // 查询有没有添加过
        if ($Type == 1) {
            $first = DB::connection('write')->table('agent.dbo.extension_user_profit_log')
                ->where('UserID', $UserID)
                ->where('Status', 0)
                ->where('Type', $Type)
                ->where('Level', $Level)
                ->first();
            if ($first) {

                $data['NoteCount'] = $first->NoteCount + 1;
                $data['InvitationUserIDs'] = $first->InvitationUserIDs . ',' . $InvitationUserID;
                $data['UpdateAt'] = date('Y-m-d H:i:s');
                $NoteCount = $first->NoteCount + 1;
            } else {

                $data['NoteCount'] = $NoteCount;
                $data['InvitationUserIDs'] = $InvitationUserID;
                $data['UpdateAt'] = date('Y-m-d H:i:s');
                $data['CreateAt'] = date('Y-m-d H:i:s');
                $data['Type'] = $Type;
            }


            $where = [
                'UserID' => $UserID,
                'Status' => 0,
                'Type' => $Type,
                'Level' => $Level,
            ];

            DB::connection('write')->table('agent.dbo.extension_user_profit_log')->updateOrInsert($where, $data);

        } else {
            $first = DB::connection('write')->table('agent.dbo.extension_user_profit_log')
                ->where('InvitationUserIDs', $InvitationUserID)
                ->where('UserID', $UserID)
                ->where('Status', 0)
                ->where('Type', $Type)
                ->where('Level', $Level)
                ->first();
            if (!$first) {
                $data['NoteCount'] = $NoteCount;
                $data['InvitationUserIDs'] = $InvitationUserID;
                $data['UpdateAt'] = date('Y-m-d H:i:s');
                $data['CreateAt'] = date('Y-m-d H:i:s');
                $data['Type'] = $Type;
                $data['UserID'] = $UserID;
                $data['Level'] = $Level;
                DB::connection('write')->table('agent.dbo.extension_user_profit_log')->Insert($data);
            }
        }

        return $NoteCount;
    }

    // 审核表信息
    protected function verify($UserID, $Type)
    {
        $exists = DB::connection('write')->table('agent.dbo.extension_verify')
            ->where('UserID', $UserID)
            ->where('Type', $Type)
            ->selectRaw('IsNull(FinalScore+TotalScore,0) allScore,Status,TotalScore')
            ->first();

        $allScore = $TotalScore = 0;
        $Status = $exists->Status ?? 0; # 审核状态

        if ($exists) {

            $allScore = $exists->allScore;
            $TotalScore = $exists->TotalScore;

        } else {

            // 添加审核记录
            DB::connection('write')->table('agent.dbo.extension_verify')
                ->insert([
                    'UserID' => $UserID,
                    'FinalScore' => 0,
                    'TotalScore' => $allScore,
                    'Type' => $Type,
                    'Status' => 0,
                ]);

        }

        return compact('allScore', 'TotalScore', 'Status');
    }
}
