<?php

namespace App\Domains\Permission\Commands;

use Illuminate\Console\Command;
use App\Domains\Permission\Services\PermissionService;

class PermissionSeederCommand extends Command
{
    protected $signature = 'permission:create
            {name : The name of the permission}
            {title? : The title of the permission}
            {--pid= : The permission parent id}';

    protected $description = '创建接口权限';

    public function handle()
    {
        $attributes = [
            'name' => $this->argument('name'),
            'title' => $this->argument('title', ''),
            'description' => $this->argument('title', ''),
            'parent_id' => $this->option('pid'),
            'status' => 1,
        ];
 
        $routes = $this->getLaravel()->router->getRoutes();
        $aliases = array_pluck($routes, 'action.as');

        if (!in_array($attributes['name'], $aliases)) {
            $this->confirm('Permission name not in routes.Are you sure creating?');
        }

        try {
            $permission = app(PermissionService::class)->store($attributes);
        } catch (\Exception $e) {
            $this->error('Create Fail #:'. $e->getMessage());
            return;
        }

        if (!$permission) {
            $this->error('Create Fail.');
        }

        $permission = $permission->toArray();
        unset($permission['children']);

        $this->info('Created Success.');
        $this->table(array_keys($permission), [array_values($permission)]);
    }
}
