<?php
namespace app\admin\middleware;

use app\admin\model\SystemMenu;
use app\admin\model\SystemRole;
use Webman\Http\Request;
use Webman\Http\Response;
use Webman\MiddlewareInterface;

class AdminAuthMiddleware implements MiddlewareInterface
{
    public function process(Request $request, callable $handler) : Response
    {
        try {
            $admin_info = $request->admin_info;
            //非超级管理员 鉴权处理
            if($admin_info->admin_is_boos != 1)
            {
                if(empty($admin_info->admin_roles))
                {
                    throw new \Exception('管理员暂未配置权限');
                }
                $rules = SystemRole::getRuleList(explode(',', $admin_info->admin_roles));
                if(empty($rules))
                {
                    throw new \Exception('管理员暂未配置角色');
                }
                $menu_list_ids = array();
                foreach ($rules as $row)
                {
                    $menu_list_ids = empty($menu_list_ids) ? explode(',', $row['role_rules']) : array_merge($menu_list_ids, explode(',', $row['role_rules']));
                }
                if(empty($menu_list_ids))
                {
                    throw new \Exception('没有权限访问1');
                }
                $menu_list = array();
                $menu_list = SystemMenu::getMenuListRule(array_unique($menu_list_ids));
                if(empty($menu_list))
                {
                    throw new \Exception('没有权限访问2');
                }
                $rule_path = $request->path();
                if(!in_array($rule_path, array_column($menu_list, 'menu_route')))
                {
                    throw new \Exception(json_encode($menu_list));
                }
            }
            return $handler($request);
        }catch (\Exception $exception){
            throw new \Exception($exception->getMessage(), $exception->getCode());
        }
    }
}
