<?php

namespace App\Game;

use App\Facade\TableName;
use App\Game\Services\RouteService;
use Illuminate\Database\Eloquent\Model;

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


class BigWinner extends Model
{
    protected $connection = 'mysql';
    protected $table = 'webgame.big_winners'; // 指定模型对应的表名

    // 指定可以被批量赋值的属性
    protected $fillable = ['img', 'gtype', 'uid', 'nick', 'lv', 'win', 'wintime'];

    // 指定日期时间转换
    protected $dates = ['wintime'];

    public static function FindWinnerFromGame()
    {
        $rekey='check_bigwinner';
        if(Redis::ttl($rekey)>60){
            return;
        }
//        if(Redis::exists($rekey))return;

        Redis::set($rekey, 1);
        Redis::expire($rekey, 360);
        // 获取当前时间和24小时前的时间
        $now = Carbon::now();
        $startTime = $now->subHours(24)->toDateTimeString();
        $currentMonth = $now->format('Ym');
        if($now->subHours(24)->format("Ym")!=$currentMonth&& $now->format('H')<4){
            $currentMonth=$now->subHours(24)->format("Ym");
        }

        $scoreTableName = TableName::QPTreasureDB() . 'YN_RecordScoreInfo_' . $currentMonth;
        $accountTableName = TableName::QPAccountsDB() . 'AccountsInfo'; // 假设 AccountInfo 表名是固定的

        $sql = "
    WITH RankedScores AS (
        SELECT
            rs.UserID,
            rs.ChangeScore,
            rs.UpdateTime,
            ROW_NUMBER() OVER (PARTITION BY rs.UserID ORDER BY rs.ChangeScore DESC) AS rn
        FROM $scoreTableName AS rs WITH (NOLOCK)
        WHERE rs.UpdateTime >= ?
    )
    SELECT TOP 50
        rs.UserID as uid,
        rs.ChangeScore as win,
        rs.UpdateTime as wintime,
        ai.NickName as nick,
        ai.FaceID as img
    FROM RankedScores AS rs
    JOIN $accountTableName AS ai WITH (NOLOCK) ON rs.UserID = ai.UserID
    WHERE rs.rn = 1 and rs.ChangeScore>10
    ORDER BY rs.ChangeScore DESC";
        try {
            $topUsers = DB::select($sql, [$startTime]);
            if (count($topUsers) > 20) {
                DB::connection('mysql')->statement('TRUNCATE TABLE ' . (new BigWinner())->table);
            }
            $userids = [];
            foreach ($topUsers as &$user) {
                $user = (array)$user;
                if (isset($userids[$user['uid']])) continue;
                $userids[$user['uid']] = 1;
                $user['win'] = $user['win'] / 100;
                $user['img'] = GlobalUserInfo::faceidToAvatar($user['img']);
                BigWinner::query()->insert($user);
//            (new BigWinner($user))->save();
            }
            self::clearCache();
        }catch (\Exception $e) {
            \Log::error($e);
        }


    }
    public static function clearCache()
    {
//        $state=RouteService::getStateConfig();
        $cacheKey = 'BigWinner24680';
        Redis::del($cacheKey);
    }
    public static function getCache()
    {
        $cacheKey = 'BigWinner24680';

        $cache=Redis::get($cacheKey);
        if($cache)return json_decode($cache, true);
        $gtypes=self::select('gtype')->distinct()->pluck('gtype');
        $data=self::orderBy('wintime', 'desc')->get();
        $cache=compact('gtypes','data');
        Redis::set($cacheKey,json_encode($cache));
        return $cache;

    }
}
