<?php

namespace App\Http\Middleware;

use App\Models\RoleUser;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Services\RoleUserService;
use App\Services\RoleService;
use App\Services\MenuService;

class CheckButtonPermission
{
    public function handle(Request $request, Closure $next)
    {
        $user = $request->user;
        $userId = $user->id;
        if($userId == 1){
            return $next($request);
        }
        $roleUserList = RoleUserService::findAll(['user_id' => $userId]);
        $roleIds = collect($roleUserList)->pluck('role_id')->toArray();
        if(empty($roleIds)){
            $roleIds = [-1];
        }

        // 当前访问的路由
        $currentUri = ltrim($request->route()->uri(), '/');
        
        $menuInfo = MenuService::findOne(['uri' => $currentUri, 'type' => MenuService::model()::TYPE_BUTTON ,'status' => MenuService::model()::STATUS_SHOW]);
        if(empty($menuInfo)){
            return $next($request);
        }
        
        $roles = RoleService::model()::with(['menus'=> function ($query) {
            $query->where('type', MenuService::model()::TYPE_BUTTON);
        }])->whereIn('id',$roleIds)->get();
        $allMenusUris = [];

        foreach ($roles as $role) {
            if (!empty($role['menus_uris'])) {
                $allMenusUris = array_merge($allMenusUris, $role['menus_uris']);
            }
        }
        
        if(in_array($currentUri,$allMenusUris)){
            return $next($request);
        }else{
            return response()->json([
                'code' => -1,
                'timestamp' => time(),
                'msg' => '无权限访问',
                'data' => []
            ]);
        }
    }

}