<?php

namespace App\Providers;

use App\Authority;
use App\CustomerLog;
use App\CustomerLogStatus;
use App\Policies\CustomerLogPolice;
use App\Policies\CustomerLogStatusesPolice;
use App\Services\CacheService;
use App\Services\UserService;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Schema;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        // 'App\Model' => 'App\Policies\ModelPolicy',
        CustomerLog::class => CustomerLogPolice::class,

        CustomerLogStatus::class => CustomerLogStatusesPolice::class,

    ];

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();
        $isSuperAdmin = null;
        if(!Schema::hasTable('users')){return;}
        /** @var CacheService $cacheService */
        $cacheService = app('CacheService');
        Gate::before(function ($user)use(&$isSuperAdmin) {
            if($isSuperAdmin===null){
                $isSuperAdmin=$user->isSuperAdmin();
            }
            if ($isSuperAdmin) {
                Cache::put('isSuperAdmin'.$user['id'], true);
            }else{
                Cache::put('isSuperAdmin'.$user['id'], false);
            }
        });
        if(!Schema::hasTable('authorities')){return;}
        $authorities=$cacheService->getOrExecute('authorities',function (){
            return Authority::with('roles')->get();
        });
        foreach($authorities as $authority) {
            Gate::define($authority->alias_name, function($user) use ($authority,$cacheService) {
                if(Cache::get('isSuperAdmin'.$user['id'])){
                    if($authority['permission']=='允许'){
                        return true;
                    }
                }
                $authorityRoles=$cacheService->getOrExecute("authority{$authority['id']}->roles",function ()use($authority){
                    return $authority->roles;
                });
                /** @var UserService $userService */
                $userService = app('UserService');
                return $userService->hasRoles($user,$authorityRoles);
            });
        }
    }
}
