<?php

namespace app\http\middleware;

use app\model\SysUser;
use app\Request;
use app\service\admin\LoginService;
use Closure;
use think\exception\ValidateException;
use think\Middleware;
use think\Response;

/**
 * 权限校验中间件
 */
class AuthMiddleware extends Middleware
{
    /*
     * 请求接口白名单列表
     */
    protected array $whiteList = [];

    public function handle(Request $request, Closure $next)
    {
        /*
         * 权限校验
         */
        $authorization = (string)$request->header('authorization', '');
        $authorization = str_replace('Bearer ', '', $authorization);
        $loginSrv = new LoginService();
        if (!in_array($request->pathinfo(), $this->whiteList, true)) {
            try{
                $auth = $loginSrv->checkUserAccessToken($authorization);
            }catch (ValidateException $e){
                return json(['code' => 401, 'message' => $e->getMessage()]);
            }
        } else {
            $auth = $loginSrv->getVisitor($request);
            return json(['code' => 401, 'message' => '禁止访问']);
        }
        /*
         * 注入获取用户信息的function
         */
        $auth::macro('getUser', function () use ($auth) {
            return SysUser::cache("sysUserInfo:{$auth->userId}", 180, 'sysUserInfoLists')->findOrFail($auth->userId);
        });

        return $next($request->setAuth($auth));
    }

//    /**
//     * 结束调度
//     * @中间件支持定义请求结束前的回调机制，你只需要在中间件类中添加end方法。
//     * @param Response $response
//     */
//    public function end(Response $response)
//    {
//        // 回调行为
//    }
}