<?php
namespace App\Domains\Artisan\Services;

use App\Core\Service;
use App\Exceptions\NotAllowedException;
use Illuminate\Support\Facades\Artisan;
use Dipper\Foundation\Exceptions\HttpException;
use App\Domains\Artisan\Repositories\ArtisanRepository;

class ArtisanService extends Service
{
    protected $artisanRepository;

    /**
     * 构造函数
     *
     * @return void
     */
    public function __construct(ArtisanRepository $artisanRepository)
    {
        $this->artisanRepository = $artisanRepository;
    }

    /**
     * 命令执行记录
     *
     * @return void
     */
    public function index(array $conditions = [])
    {
        $limit = $conditions['limit'] ?? 20;

        $artisans = $this->artisanRepository->withConditions($conditions)->applyConditions()->paginate($limit);

        return $artisans;
    }

    /**
     * 执行.
     *
     * @return \Illuminate\Http\Response
     */
    public function call($command, array $parameters = [])
    {
        $commands = array_keys(Artisan::all());

        if (!in_array($command, $commands)) {
            throw new NotAllowedException('非法的命令');
        }

        try {
            Artisan::call($command, $parameters);
            $this->artisanRepository->create([
                'command' => $command,
                'parameters' => $parameters,
            ]);
        } catch (\Exception $e) {
            throw new HttpException($e->getMessage());
        }


        return res(true, '执行成功');
    }
}
