<?php

namespace App\Http\Controllers\Admin;

use App\Facade\TableName;
use App\Http\helper\NumConfig;
use App\Services\SuperballActivityService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

/**
 * Superball 活跃活动后台统计（仅查询，无导出）
 * - 每日数据（含真实完成人数、真实球数）
 * - 用户任务完成情况
 * - 用户奖励领取情况
 */
class SuperballController extends BaseController
{
    /**
     * 每日总体数据（含真实用户完成人数、真实球数）
     * GET /admin/superball/daily
     */
    public function daily(Request $request)
    {
        // 不需要日期筛选，直接按日期倒序分页
        $list = DB::table(TableName::agent() . 'superball_daily')
            ->orderBy('pool_date', 'desc')
            ->paginate(30);

        $dates = $list->pluck('pool_date')->all();
        $realCompleted = [];
        $realBalls = [];
        if (!empty($dates)) {
            $realCompleted = DB::table(TableName::agent() . 'superball_user_task')
                ->whereIn('task_date', $dates)
                ->where('status', 1)
                ->selectRaw('task_date, COUNT(DISTINCT user_id) as cnt')
                ->groupBy('task_date')
                ->pluck('cnt', 'task_date')
                ->all();
            $realBalls = DB::table(TableName::agent() . 'superball_user_balls')
                ->whereIn('ball_date', $dates)
                ->selectRaw('ball_date, COUNT(*) as cnt')
                ->groupBy('ball_date')
                ->pluck('cnt', 'ball_date')
                ->all();
        }

        foreach ($list as $row) {
            $row->real_user_completed_count = (int)($realCompleted[$row->pool_date] ?? 0);
            $row->real_total_balls = (int)($realBalls[$row->pool_date] ?? 0);
            $row->pool_amount_display = number_float($row->pool_amount / NumConfig::NUM_VALUE);
            $totalBalls = (int)($row->total_balls ?? 0);
            $row->base_reward_per_ball_display = $totalBalls > 0
                ? number_float($row->pool_amount / NumConfig::NUM_VALUE / $totalBalls)
                : '0.00';

            // 用户中奖球总数：直接使用 superball_daily.lucky_count 字段
            $row->winning_balls_count = (int)($row->lucky_count ?? 0);

            // 幸运奖励合计 = 今日中奖球数量 * 每个中奖球奖励（注意是活动配置的中奖奖励，不是基础奖励）
            $perLuckyDisplay = SuperballActivityService::LUCKY_REWARD_PER_BALL; // 已是展示单位
            if ($row->winning_balls_count > 0 && $perLuckyDisplay > 0) {
                $row->total_lucky_reward_display = number_format(
                    $perLuckyDisplay * $row->winning_balls_count,
                    2,
                    '.',
                    ''
                );
            } else {
                $row->total_lucky_reward_display = '0.00';
            }
        }

        return view('admin.superball.daily', compact('list'));
    }

    /**
     * 用户任务完成情况（含用户系数、球号码与数量、预计奖励，按更新时间逆序）
     * GET /admin/superball/user-tasks
     */
    public function userTasks(Request $request)
    {
        $date = $request->input('date');
        // 前端输入的是 AccountsInfo 的 GameID，这里按 GameID 反查出 UserID 过滤
        $userId = trim((string)$request->input('user_id', ''));
        $tier = strtoupper(trim((string)$request->input('tier', '')));
        $status = $request->input('status', '');

        $query = DB::table(TableName::agent() . 'superball_user_task as t')
            ->leftJoin('QPAccountsDB.dbo.AccountsInfo as a', 't.user_id', '=', 'a.UserID')
            ->leftJoin(TableName::agent() . 'superball_user_multiplier as m', 't.user_id', '=', 'm.user_id')
            ->leftJoin(TableName::agent() . 'superball_tier_config as c', 't.tier', '=', 'c.tier')
            ->leftJoin(TableName::agent() . 'superball_daily as d', 't.task_date', '=', 'd.pool_date')
            ->selectRaw('t.*, a.GameID as game_id, m.multiplier, c.ball_count as tier_ball_count, d.pool_amount, d.total_balls as daily_total_balls');

        if ($date) {
            $query->where('t.task_date', $date);
        }
        if ($userId !== '') {
            $query->where('a.GameID', $userId);
        }
        if ($tier && in_array($tier, ['A', 'B', 'C', 'D', 'E'], true)) {
            $query->where('t.tier', $tier);
        }
        // 仅当明确选择 未领球(0) 或 已领球(1) 时才按状态筛选，避免空值被当成 0
        if ($status !== '' && $status !== null && in_array((string)$status, ['0', '1'], true)) {
            $query->where('t.status', (int)$status);
        }

        $query->orderBy('t.updated_at', 'desc');
        $list = $query->paginate(20);

        $userIds = $list->pluck('user_id')->unique()->values()->all();
        $ballsByKey = [];
        $taskDates = $list->pluck('task_date')->unique()->values()->all();
        if (!empty($userIds) && !empty($taskDates)) {
            $balls = DB::table(TableName::agent() . 'superball_user_balls')
                ->whereIn('user_id', $userIds)
                ->whereIn('ball_date', $taskDates)
                ->orderBy('user_id')->orderBy('ball_index')
                ->get();
            foreach ($balls as $b) {
                $k = $b->user_id . '_' . $b->ball_date;
                if (!isset($ballsByKey[$k])) {
                    $ballsByKey[$k] = ['numbers' => [], 'count' => 0];
                }
                $ballsByKey[$k]['numbers'][] = (int)$b->number;
                $ballsByKey[$k]['count']++;
            }
        }

        foreach ($list as $row) {
            $row->user_multiplier = $row->multiplier !== null ? (float)$row->multiplier : 1.0;
            $k = $row->user_id . '_' . $row->task_date;
            $ballInfo = $ballsByKey[$k] ?? ['numbers' => [], 'count' => 0];
            $row->ball_numbers_text = implode(',', $ballInfo['numbers']);
            $row->ball_count_actual = $ballInfo['count'];
            $ballCount = $ballInfo['count'] > 0 ? $ballInfo['count'] : (int)($row->tier_ball_count ?? 0);
            $dailyTotal = (int)($row->daily_total_balls ?? 0);
            if ($dailyTotal > 0 && $row->pool_amount !== null) {
                $basePerBall = (int)$row->pool_amount / $dailyTotal;
                $row->estimated_reward_display = number_float(($basePerBall * $ballCount * $row->user_multiplier) / NumConfig::NUM_VALUE);
            } else {
                $row->estimated_reward_display = '0.00';
            }
        }

        return view('admin.superball.user_tasks', compact('list', 'date', 'userId', 'tier', 'status'));
    }

    /**
     * 用户奖励领取情况
     * GET /admin/superball/prizes
     */
    public function prizes(Request $request)
    {
        $date = $request->input('date');
        $gameId = (int)$request->input('game_id', 0);
        $userId = 0;

        // 通过 GameID 从 AccountsInfo 获取对应的 UserID
        if ($gameId > 0) {
            $userInfo = DB::table('QPAccountsDB.dbo.AccountsInfo')
                ->where('GameID', $gameId)
                ->select('UserID')
                ->first();
            if ($userInfo) {
                $userId = $userInfo->UserID;
            }
        }

        $query = DB::table(TableName::agent() . 'superball_prize_log as p')
            ->leftJoin('QPAccountsDB.dbo.AccountsInfo as a', 'p.user_id', '=', 'a.UserID')
            ->selectRaw('p.*, a.GameID, a.NickName')
            ->orderBy('p.settle_date', 'desc')
            ->orderBy('p.user_id');

        if ($date) {
            $query->where('p.settle_date', $date);
        }
        if ($userId > 0) {
            $query->where('p.user_id', $userId);
        }

        $list = $query->paginate(50);

        foreach ($list as $row) {
            $row->total_amount_display = number_float($row->total_amount / NumConfig::NUM_VALUE);
            $row->base_amount_display = number_float($row->base_amount / NumConfig::NUM_VALUE);
            $row->lucky_amount_display = number_float($row->lucky_amount / NumConfig::NUM_VALUE);
        }

        return view('admin.superball.prizes', compact('list', 'date', 'gameId'));
    }
}
