<?php


namespace App\Models;


class UserSession extends BaseModel
{
    protected $table = 'user_session';
    protected $fillable = ['user_id', 'token', 'expire_time'];
    
    public $timestamps = true;
    protected $dateFormat = 'U'; // U 代表 UNIX 时间戳（int）

    // 2. 修改创建时间字段名为 create_time
    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'update_time';
    
    public static function setToken($userId)
    {
        $time = time();
        $userSession = UserSession::where('user_id', $userId)->first();

        //获取token延长过期的时间
        $expireTime = $time + 3600 * 24 * 7;
        $token = create_token($userId);
        //token处理
        if ($userSession) {
            
            //重新获取token
            $userSession->token = $token;
            $userSession->expire_time = $expireTime;
            $userSession->update_time = $time;
            $userSession->save();
        } else {
            //找不到在该终端的token记录，创建token记录
            $userSession = UserSession::create([
                'user_id' => $userId,
                'token' => $token,
                'expire_time' => $expireTime
            ]);
        }
        return $token;
    }
}

