<?php
/**
 * Author: luzheng.liu
 * Time: 2020/8/26 18:54
 */

namespace app\common\until;


use app\index\exception\ApiException;
use app\index\exception\TokenException;
use Firebase\JWT\ExpiredException;
use Firebase\JWT\JWT;

class Token {

    public $jwtKey = '';

    public $expTime = 3600;

    public function __construct() {
        $this->jwtKey = env('app.jwt_key','Rn4zNAX9e3li5dfI6mBuWLvbacTZqUr3');
    }


    public function getToken(int $userId,string $visitor = '') {
        $payload = [
            "iat"    => time(),
            "exp"    => time() + (3600 * 24 * 7),
            "userId" => $userId,
            "visitor"=> $visitor
        ];
        $token = JWT::encode($payload, $this->jwtKey);
        return $token;
    }

    public function decodeToken(): array {
        $token = request()->header('token') ?: request()->get('token');
        if (empty($token)) {
            throw new ApiException('token不能为空');
        }

        try {
            $decoded = JWT::decode($token, $this->jwtKey, ['HS256']);
        } catch (ExpiredException $e) {
            throw new TokenException('token到期，请刷新');
        } catch (\Exception $e) {
            throw new ApiException('token无效' . $e->getMessage());
        }
        $tokenInfo = (array)$decoded;

        if (time() - $tokenInfo['exp'] > 3600) {
            $GLOBALS['refreshToken'] = $this->getToken($tokenInfo['usrId']);
        }
        return (array)$decoded;
    }
}