<?php

namespace App\Game;

use App\Facade\TableName;
use App\Game\Services\BetbyService;
use App\Http\helper\NumConfig;
use App\IpLocation;
use App\Jobs\GameTask;
use App\Models\AccountsInfo;
use App\Models\Treasure\GameScoreInfo;
use App\Services\VipService;
use App\Util;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\DB;


class GlobalUserInfo extends Model
{
    /**
     * @var GlobalUserInfo
     */
    public static $me=null;
    public static function getLocale()
    {

        if(isset(self::$me)&&!empty(self::$me)&&!empty(self::$me->DefaultLanguage)){
            return substr(self::$me->DefaultLanguage,0,2);
        }else{
            return env('DEFAULT_LOCALE','en');
        }
    }
    public static function getLocaleByUserID($UserID,$default='en')
    {

        if(isset(self::$me)&&!empty(self::$me)&&!empty(self::$me->DefaultLanguage)&&self::$me->UserID==$UserID){
            return substr(self::$me->DefaultLanguage,0,2);
        }else{
            $user=self::getGameUserInfo('UserID',$UserID);
            $locale=$user->DefaultLanguage??substr( @$_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2 );
            if(!$locale||empty($locale)){
                $locale=env('DEFAULT_LOCALE','en');
            }

            return strstr(env('VALID_LOCALE','en,es,pt,ru'),$locale)?$locale:$default;
        }
    }

    /**
     * @param $request
     * @return GlobalUserInfo|null
     */
    public static function GetRecentLogin($request){
        $FF = $request->input("ff", "");
        $LastLogonIP=IpLocation::getRealIp();
        $ua=$request->userAgent();

        $data1=Redis::get('UpdateLoginCheck_'.$FF);
        $data2=Redis::get('UpdateLoginCheck_'.$LastLogonIP);

        if($data1){
            $data=json_decode($data1,true);
            if($data['LastLogonIP']==$LastLogonIP){
                return self::getGameUserInfo('UserID',$data['UserID']);
            }
        }
        if($data2){
            $data=json_decode($data2,true);
            if($data['FF']==$FF){
                return self::getGameUserInfo('UserID',$data['UserID']);
            }else if($data['ua']==$ua){
                return self::getGameUserInfo('UserID',$data['UserID']);
            }
        }
        $user=GlobalUserInfo::query()->where('LastLogonIP',$LastLogonIP)->where('FF',$FF)->first();
        return $user;
    }
    public static function UpdateLoginDate($request,$forceLogin=false)
    {
        if(self::$me) {
            $UserID=self::$me->UserID;
            $LastLogonDate = date('Y-m-d H:i:s');
            $LastLogonIP=IpLocation::getRealIp();
            $FPID = $request->input("bfp", "");
            $FF = $request->input("ff", "");
            if(!Redis::exists('UpdateLoginCheck_'.$UserID)||$forceLogin) {
                GameTask::dispatch(['UpdateLogin', [$UserID, $LastLogonDate, $LastLogonIP,$FPID,$FF]]);
                Util::WriteLog('24680dispatch', ['UpdateLogin', [$UserID, $LastLogonDate, $LastLogonIP,$FPID,$FF]]);
            }
            //无论是否通知后端更新，都要记录最新的数据，方便及时取回
            $ua=$request->userAgent();
            $saved=json_encode(compact('UserID','FPID','FF','LastLogonDate','LastLogonIP','ua'));
            Redis::setex('UpdateLoginCheck_'.$UserID,300,$saved);
            Redis::setex('UpdateLoginCheck_'.$FF,1200,$saved);
            Redis::setex('UpdateLoginCheck_'.$LastLogonIP,1200,$saved);
        }
    }


    protected $primaryKey = 'GlobalUID'; // Set the primary key
    public $incrementing = false; // Disable auto-increment
    public $timestamps = false; // If the table does not have 'created_at' and 'updated_at' columns


    protected $connection = 'mysql';

    // 指定表名，如果表名与类名的复数相同则不需要
    protected $table = 'webgame.GlobalUserInfo';

    // Fillable attributes for mass assignment
    protected $fillable = [
        'GlobalUID', 'UserID', 'GameID','FF','FPID','LastFPID','ShortHashID', 'Accounts', 'Email', 'Phone', 'NickName', 'FaceID', 'LogonPass',
        'InsurePass', 'Gender', 'RegisterDate', 'RegisterIP',
        'RegisterLocation', 'DefaultLanguage', 'ServerRegion',
        'ThemeColor', 'Level', 'Exp', 'UserRight',
        'SpreaderID', 'LastLogonIP', 'LastLogonDate', 'ReferrType','Channel','RegionID','GpsAdid','FavoriteGames','PwaInstalled','Registed'
    ];

    // Attributes that should be cast to native types
    protected $casts = [
        'Gender'     => 'integer',
        'Level'      => 'integer',
        'Exp'        => 'integer',
        'UserRight'  => 'integer',
        'ThemeColor' => 'string', // Casting enum as string
    ];

    // Custom date attributes
    protected $dates = [
        'RegisterDate',
        'LastLogonDate'
    ];

    public static function faceidToAvatar($faceID)
    {
//        return "https://cdn.moeda777.com/24680/assets/avatar/2/avatar_$faceID.png";
        return "https://24680.imgix.net/24680/assets/avatar/5/avatar_$faceID.webp?auto=format,compress&cs=srgb";
    }

    /**
     * @param $key 'UserID', 'GlobalUID', 'Email', 'Phone'
     * @param $value
     * @return GlobalUserInfo
     */
    public static function getGameUserInfo($key, $value)
    {
        if(self::$useCache) {
            $cacheKey = "GlobalUserInfo:{$key}:{$value}";

            // 尝试从缓存获取
            $cached = Redis::get($cacheKey);
            if ($cached !== null && $cached !== false) {
                $data = json_decode($cached, true);
                if ($data) {
                    $instance = new self();
                    $instance->exists = true;
                    $instance->setRawAttributes($data, true);
                    return $instance;
                }
            }
        }

        // 从数据库查询
        $user = self::query()->where($key, $value)->first();

        if(self::$useCache) {
            // 缓存结果（300秒 = 5分钟）
            if ($user) {
                Redis::setex($cacheKey, 300, json_encode($user->getAttributes()));
            }
        }

        return $user;
    }

    /**
     * @param $key 'UserID', 'GlobalUID', 'Email', 'Phone'
     * @param $value
     * @return array|false
     */
    public static function getGameUserInfoToWeb($key, $value)
    {
        return self::toWebData(self::getGameUserInfo($key, $value));

    }

    /**
     * @param GlobalUserInfo $user
     * @return array|false
     */
    public static function toWebData(GlobalUserInfo $user,$makeBB=false)
    {
        if(is_array($user)){
            if(isset($user['Score'])) return $user;
            if(isset($user['UserID'])){
                $user = self::getGameUserInfo('UserID', $user['UserID']);
            }
        }
        $data = false;
        if ($user) {
            $u = $user->toArray();
            $existKey = ['UserID', 'GameID', 'GlobalUID','Email', 'Phone','DefaultLanguage', 'NickName', 'FaceID', 'Gender', 'RegisterDate', 'RegisterLocation', 'InsurePass', 'Level', 'Exp', 'UserRight','Channel','PwaInstalled'];
            $data = [];
            foreach ($existKey as $key) {
                if(isset($u[$key]))$data[$key] = $u[$key];
            }
            if (!empty($data['InsurePass'])) $data['InsurePass'] = 1;
            $data['sign'] = self::genGuuidSign($user);
            $data['img'] = self::faceidToAvatar($data['FaceID']);
            if (!intval($data['GameID'])) {
                $data['GameID'] = AccountsInfo::query()->select(['GameID'])->where('UserID', $data['UserID'])->first()->GameID;
                $user->GameID = $data['GameID'];
                $user->update(['GameID' => $data['GameID']]);
            }


            $scoreData = self::getScoreDataByUserID($data['UserID'],!WebChannelConfig::getByChannel($user->Channel)->isRealMoneyReg());

            $data['Score'] = $scoreData['Score'];
            $data['InsureScore'] = $scoreData['InsureScore'];
//            if($makeBB){
//                $data['bb']=['token'=>(new BetbyService())->getDefaultJWT($u)];
//            }
            $userRecharge = DB::table('QPAccountsDB.dbo.YN_VIPAccount')
                ->where('UserID', $data['UserID'])
                ->value('Recharge') ?? 0;

            $data['vip'] = VipService::calculateVipLevel($data['UserID'] ?? 0,$userRecharge);
            $data['vipExp'] = $userRecharge;
            //intval(GameScoreInfo::query()->select(['Score'])->where('UserID', $data['UserID'])->first()->Score) / 100;
        }
        return $data;
    }
    private static $userToScores=[];

    private static $userToScoresData=[];

    public static function getScoreByUserID($userID)
    {
        if(!isset(self::$userToScores[$userID])) {
            $scoreObj=GameScoreInfo::query()->select(['Score'])->where('UserID', $userID)->first();
            if($scoreObj)self::$userToScores[$userID] = intval($scoreObj->Score) / NumConfig::NUM_VALUE;
            else self::$userToScores[$userID]=0;
        }
        return self::$userToScores[$userID];
    }


    public static function getScoreDataByUserID($userID,$changeInsureScore=true)
    {
        if(!isset(self::$userToScoresData[$userID])) {
            $scoreObj=GameScoreInfo::query()->select(['Score','InsureScore'])->where('UserID', $userID)->first();
            if($scoreObj){
                self::$userToScoresData[$userID]['Score'] = intval($scoreObj->Score) / NumConfig::NUM_VALUE;
                self::$userToScoresData[$userID]['InsureScore'] = intval($scoreObj->InsureScore) / NumConfig::NUM_VALUE;
                $user_recharge = DB::table(TableName::QPAccountsDB() . 'YN_VIPAccount')
                    ->where('UserID', $userID)
                    ->value('Recharge') ?: 0;
                self::$userToScoresData[$userID]['Recharge'] = $user_recharge;
                if(!$user_recharge&&$changeInsureScore){
                    self::$userToScoresData[$userID]['Score'] = 0;
                    self::$userToScoresData[$userID]['InsureScore'] = intval($scoreObj->Score) / NumConfig::NUM_VALUE;
                }
            }else{
                self::$userToScoresData[$userID]['Score'] = 0;
                self::$userToScoresData[$userID]['Recharge'] = 0;
                self::$userToScoresData[$userID]['InsureScore'] = 0;
            }
        }
        return self::$userToScoresData[$userID];
    }


    public static function GlobalToUserID($GlobalUID)
    {
        return intval(explode('-', $GlobalUID)[3]);
    }
    public static function genGuuidSign($user)
    {
        return Crypt::encryptString($user->GlobalUID . '|' . (time() + 86400 * 365) . '|' . substr(md5($user->LogonPass), 0, 6));
    }
    public function addFavoGame($gameid)
    {
        $gids=explode(',',$this->FavoriteGames);
        array_unshift($gids,$gameid);
        if(count($gids)>20){
            array_pop($gids);
        }
        $this->update(['FavoriteGames'=>implode(',',$gids)]);
    }
    public function removeFavoGame($gameid)
    {
        $gids=explode(',',$this->FavoriteGames);
        foreach($gids as $key=>$gid){
            if($gid==$gameid){
                array_splice($gids,$key,1);
            }
        }
        $this->update(['FavoriteGames'=>implode(',',$gids)]);

    }

    /**
     * 模型启动方法，注册事件监听
     */
    protected static function boot()
    {
        parent::boot();
        if(!self::$useCache)return;
        // 监听 saved 事件（包括 created 和 updated）
        static::saved(function ($user) {
            $user->clearUserCache();
        });

        // 监听 deleted 事件
        static::deleted(function ($user) {
            $user->clearUserCache();
        });
    }
    public static $useCache=false;

    /**
     * 清除用户缓存
     */
    private function clearUserCache()
    {
        if(!self::$useCache)return;
        $keys = ['UserID', 'GlobalUID', 'Email', 'Phone','Accounts','FPID'];
        foreach ($keys as $key) {
            if (isset($this->attributes[$key]) && !empty($this->attributes[$key])) {
                $cacheKey = "GlobalUserInfo:{$key}:{$this->attributes[$key]}";
                Redis::del($cacheKey);
            }
        }
    }
}
