<?php

namespace app\entity;

use app\model\SysRole;
use Firebase\JWT\JWT;
use Hashids\Hashids;
use think\Collection;
use think\Entity;

/**
 * 系统用户实体
 * @see \app\model\SysUser
 * @property SysRole[]|Collection $roles
 * @property array $authorities
 */
class SysUser extends Entity
{
    /**
     * 获取菜单列表
     * @param bool $buildTree
     * @return array
     */
    public function getMenus(bool $buildTree = false): array
    {
        return $buildTree ? list_build_tree($this->authorities, 'menuId', 'parentId') : $this->authorities;
    }

    /**
     * 生成AccessToken
     * @return string
     */
    public function getAccessToken(): string
    {
        $jwtConfig = (array)config('admin.jwt_config', []);
        $jwtKey = (string)config('admin.jwt_key', '');
        $hashids = new Hashids($jwtKey, 8);
        return JWT::encode([
            ...$jwtConfig,
            'iat' => time(),
            'exp' => time() + 3600,
            'uid' => $hashids->encode($this->user_id),
        ], $jwtKey, 'HS256');
    }
}