<?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\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 substr( @$_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2 );
        }
    }
    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;
        }
    }
    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();
            if(!Redis::exists('UpdateLoginCheck_'.$UserID)||$forceLogin) {
                Redis::setex('UpdateLoginCheck_'.$UserID,600,$UserID);
                $FPID = $request->input("bfp", "");
                GameTask::dispatch(['UpdateLogin', [$UserID, $LastLogonDate, $LastLogonIP,$FPID]]);
                Util::WriteLog('24680dispatch', ['UpdateLogin', [$UserID, $LastLogonDate, $LastLogonIP]]);
            }
        }
    }


    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','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','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/2/avatar_$faceID.png?auto=format,compress&cs=srgb";
    }

    /**
     * @param $key 'UserID', 'GlobalUID', 'Email', 'Phone'
     * @param $value
     * @return GlobalUserInfo
     */
    public static function getGameUserInfo($key, $value)
    {
        return self::query()->where($key, $value)->first();

    }

    /**
     * @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)
    {
        $data = false;
        if ($user) {
            $u = $user->toArray();
            $existKey = ['UserID', 'GameID', 'GlobalUID','Email', 'Phone','DefaultLanguage', 'NickName', 'FaceID', 'Gender', 'RegisterDate', 'RegisterLocation', 'InsurePass', 'Level', 'Exp', 'UserRight','Channel','Registed'];
            $data = [];
            foreach ($existKey as $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']);

            $data['Score'] = $scoreData['Score'];
            $data['InsureScore'] = $scoreData['InsureScore'];
            if($makeBB){
                $data['bb']=['token'=>(new BetbyService())->getDefaultJWT($u)];
            }
            //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)
    {
        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){
                    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)]);

    }
}
