<?php

namespace App\Console\Commands;

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

class RecordServerGameCountYesterday extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'record_server_game_count_yesterday';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '按天统计游戏人数-游戏房间去重过的用户';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {

        // 今日执行昨日数据
        $DateID = Carbon::yesterday()->format('Ymd');
        // 查找按天去重玩过游戏的人
        $list = DB::connection('write')->table(TableName::QPRecordDB() . 'RecordUserGameDayCount')
            ->where('DateID', $DateID)
            ->selectRaw('count(UserID) UserCount,GameID,sum(Cnt) Cnt')
            ->groupBy('GameID')
            ->get();

        foreach ($list as $value) {
            DB::connection('write')->table(TableName::QPRecordDB() . 'RecordServerGameCount')
                ->updateOrInsert(['DateID' => $DateID, 'GameID' => $value->GameID], ['DateID' => $DateID, 'GameID' => $value->GameID, 'Cnt' => $value->Cnt, 'UserCount' => $value->UserCount]);
        }

        // 计算并更新游戏RTP数据
        $this->calculateAndStoreGameRtp();
    }

    /**
     * 计算并存储游戏RTP数据
     * 从RecordGameRoomDayInfo和RoomStockDay两张表中获取最近60天的数据
     * 根据GameID分类求和PayTotalBet和PayWinLost，计算RTP并存储到Redis
     */
    private function calculateAndStoreGameRtp()
    {
        try {
            // 计算最近60天的DateID范围
            $endDate = date('Ymd', strtotime('-1 day')); // 昨天
            $startDate = date('Ymd', strtotime('-60 days')); // 60天前

            // 使用JOIN查询两张表中DateID和GameID相同，SortID=1的数据
            // 按GameID分组求和PayTotalBet和PayWinLost
            $gameStats = DB::connection('write')
                ->table(TableName::QPRecordDB() . 'RecordGameRoomDayInfo as r')
                ->join(TableName::QPPlatformDB() . 'RoomStockDay as rs', function($join) {
                    $join->on('r.DateID', '=', 'rs.DateID')
                         ->on('r.GameID', '=', 'rs.GameID')
                         ->on('r.SortID', '=', 'rs.SortID');
                })
                ->where('r.SortID', 1)
                ->whereBetween('r.DateID', [$startDate, $endDate])
                ->select(
                    'r.GameID',
                    DB::raw('SUM(r.PayTotalBet) as PayTotalBet'),
                    DB::raw('SUM(rs.PayWinLost) as PayWinLost')
                )
                ->groupBy('r.GameID')
                ->get();

            // 计算所有数据的总和
            $totalPayTotalBet = 0;
            $totalPayWinLost = 0;
            
            foreach ($gameStats as $item) {
                $totalPayTotalBet += ($item->PayTotalBet ?? 0);
                $totalPayWinLost += ($item->PayWinLost ?? 0);
            }
            
            // 计算所有数据相加的RTP值作为g0
            $totalRtp = intval((($totalPayTotalBet - $totalPayWinLost) / max($totalPayTotalBet, 1)) * 100);
            $gameRtp = ["g0" => $totalRtp];

            // 计算每个GameID的RTP
            foreach ($gameStats as $item) {
                $gameId = $item->GameID;
                $payTotalBet = $item->PayTotalBet ?? 0;
                $payWinLost = $item->PayWinLost ?? 0;
                
                // RTP计算公式: ((PayTotalBet-PayWinLost)/max(PayTotalBet,1))*100
                $rtp = intval((($payTotalBet - $payWinLost) / max($payTotalBet, 1)) * 100);
                $rtp = ($rtp<=80)?80:$rtp;
                $rtp = ($rtp>=120)?120:$rtp;
                $gameRtp["g" . $gameId] = $rtp;
            }

            // 将结果存储到Redis的SomeConfigSpecial键中
            Redis::set("SomeConfigSpecial", json_encode($gameRtp));

//            $this->info('游戏RTP数据计算完成并已存储到Redis');
            \Log::info('游戏RTP数据更新成功', [
                'date_range' => [$startDate, $endDate],
                'game_count' => count($gameRtp) - 1, // 减去默认的g0
                'rtp_data' => $gameRtp
            ]);

        } catch (\Exception $e) {
//            $this->error('计算游戏RTP数据时发生错误: ' . $e->getMessage());
            \Log::error('计算游戏RTP数据失败', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
        }
    }
}
