<?php
// +----------------------------------------------------------------------
// | [ WE CAN DO IT MORE SIMPLE  ]
// +----------------------------------------------------------------------
// | Copyright (c) 2018-2020 rights reserved.
// +----------------------------------------------------------------------
// | 
// +----------------------------------------------------------------------
// | Date: 2020-08-30 14:59
// +----------------------------------------------------------------------
namespace app\system\middleware;

use app\model\system\Admin as AdminModel;
use app\model\system\AdminRole;
use app\model\system\RolePath;
use app\Request;
use Firebase\JWT\ExpiredException;
use Firebase\JWT\JWT;
use library\exceptions\AuthException;
use library\interfaces\MiddlewareInterface;
use library\utils\AdminLogUtils;
use think\facade\Cache;
use think\facade\Config;

class AdminCkeckRoleMiddleware implements MiddlewareInterface
{
    public function handle(Request $request, \Closure $next)
    {
        $adminInfo = $request->adminInfo;
        $rules     = (new AdminRole())->getRoleId($adminInfo['role_id']);
        if ($rules['is_system']) {
            $log = \config('log');
            //记录日志
            if($log['LOG']) {
                (new AdminLogUtils($request))
                    ->path(app()->getAppPath() . "/route")
                    ->log();
            }
            return $next($request);
        }
        $rolePathData = RolePath::getMoule($rules['module']);
        if (empty($rolePathData)) {
            //无权限
            throw new AuthException('无法操作当前功能，无操作权限', -66);
        }
        $rolePathAr = array_column($rolePathData, 'role_path');
        $rAr        = [];
        foreach ($rolePathAr as $v) {
            $r   = explode(',', $v);
            $vAr = array_filter($r, function ($item) {
                return !empty($item) ? true : false;
            });
            if (!empty($vAr)) {
                $vAr = array_values($vAr);
                $rAr = array_merge($rAr, $vAr);
            }
        }
        $pathinfo = $request->pathinfo();
        $bool     = false;
        foreach ($rAr as $v) {
            if (trim($v) == trim($pathinfo)) {
                $bool = true;
            }
        }
        if (!$bool) {
            throw new AuthException('无法操作当前功能，无操作权限', -66);
        }
        $log = \config('log');
        //记录日志
        if($log['LOG']) {
            (new AdminLogUtils($request))
                ->path(app()->getAppPath() . "/route")
                ->log();
        }
        return $next($request);
    }

}