<?php

namespace App\Console\Commands;

use App\Facade\TableName;
use App\Services\SuperballActivityService;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

/**
 * Superball 活跃活动：每分钟刷新奖池与展示统计（pool_amount、total_balls、completed_count）
 *
 * - pool_amount: 取当日游戏总流水的 1/10（来源：RecordGameRoomDayInfo.TotalBet）
 * - total_balls & completed_count: 按时间段做一些随机增长，用于前端展示实时热度
 */
class SuperballUpdatePoolAndStats extends Command
{
    protected $signature = 'superball:update-pool-stats';

    protected $description = 'Superball: update pool_amount (1/10 of total game turnover) and grow total_balls/completed_count every minute';

    /** @var SuperballActivityService */
    protected $service;

    public function __construct(SuperballActivityService $service)
    {
        parent::__construct();
        $this->service = $service;
    }

    public function handle(): int
    {
        $today = Carbon::today();
        $dateStr = $today->format('Y-m-d');
        $dateId = $today->format('Ymd');

        try {
            // 1. 计算当日总流水（TotalBet）并取 1/10 作为奖池
            $roomRow = DB::table('QPRecordDB.dbo.RecordGameRoomDayInfo')
                ->where('DateID', $dateId)
                ->where('SortID', -1)
                ->selectRaw('SUM(TotalBet) AS flowing_water_new')
                ->first();

            $flowing = $roomRow && isset($roomRow->flowing_water_new)
                ? (int)$roomRow->flowing_water_new
                : 0;

            // 奖池 = 总流水的 1/10（内部单位），向下取整
            $poolAmount = (int)floor($flowing / 4);

            // 2. 确保当日 superball_daily 记录存在（原子 MERGE，不持长锁）
            $this->service->getOrCreateDaily($dateStr);

            // 3. 计算本次要增加的 completed_count 和 total_balls
            $hour = intval(date('H'));
            if ($hour < 2) {
                $completedInc = mt_rand(5, 10);
                $multipliers = [1, 2, 3, 6];
            } else if ($hour <= 10) {
                $completedInc = mt_rand(10, 15);
                $multipliers = [6, 10];
            } else {
                $completedInc = mt_rand(15, 20);
                $multipliers = [10, 15];
            }

            // 用昨日注册用户数 / 500 作为系数，重新调整 completedInc
            $yesterdayDateId = Carbon::yesterday()->format('Ymd');
            $yesterdayRegCount = (int) DB::connection('read')
                ->table('QPRecordDB.dbo.RecordPlatformData')
                ->where('DateID', $yesterdayDateId)
                ->where('Channel', -1)
                ->value('RegPeple');
            $regFactor = $yesterdayRegCount > 0 ? ($yesterdayRegCount / 500) : 0.1;
            $regFactor = max(1, $regFactor);
            $completedInc = (int) ($completedInc * $regFactor);

            $multiplier = $multipliers[array_rand($multipliers)];
            $ballsInc = $completedInc * $multiplier;

            // 单条 UPDATE 原子累加，不需要事务包裹
            DB::connection('write')->table(TableName::agent() . 'superball_daily')
                ->where('pool_date', $dateStr)
                ->update([
                    'pool_amount' => $poolAmount,
                    'completed_count' => DB::raw("completed_count + {$completedInc}"),
                    'total_balls' => DB::raw("total_balls + {$ballsInc}"),
                    'updated_at' => now()->format('Y-m-d H:i:s'),
                ]);

            \Log::info("Superball pool ###$completedInc###$ballsInc");

            \Log::info("Superball pool stats updated for {$dateStr}, pool_amount={$poolAmount}"."--");
            return true;
        } catch (\Throwable $e) {
            \Log::error('Superball update pool stats failed: ' . $e->getMessage());
            \Log::error('Superball update pool stats', [
                'date' => $dateStr,
                'error' => $e->getMessage(),
            ]);
            return false;
        }
    }
}

