<?php

namespace App\Http\Controllers;

use App\Components\AsyncResponse;
use App\Services\CacheShelfService;
use App\Station;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Contracts\View\Factory;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\View\View;

class CacheShelfController extends Controller
{
    use AsyncResponse;

    /**
     * 缓存货架
     * @return Application|Factory|View
     */
    public function index()
    {
        $stations = Station::query()->with('stationType:name', 'parent:name')->whereNull('parent_id')->whereIn('station_type_id', function ($query) {
            /** @var Builder $query */
            $query->from('station_types')->selectRaw('id')->where('name', '缓存架');
        })->paginate(10);

        return view('station.cachingShelf.list.index', compact('stations'));
    }

    /**
     * 获取缓存货架上的任务列表
     * @param Request $request
     * @param string $id
     * @param CacheShelfService $service
     */
    public function getTasksApi(Request $request,string $id,CacheShelfService $service)
    {
        /** @var Station $station */
        $station = $service->getChildStation($id);
        $this->success($station);
    }

    /**
     * 缓存架亮灯
     * @param Request $request
     * @param CacheShelfService $service
     * @return mixed
     */
    public function lightOnApi(Request $request,CacheShelfService $service)
    {
        if($request['stationCode'] && $request['materialBoxCode'])
           return $service->createStationTask($request['stationCode'],$request['materialBoxCode']);
        return ['success' => false,'message' => '参数错误'];
    }

    /**
     * @param Request $request
     * @return array|bool[]
     */
    public function clearTaskApi(Request $request): array
    {
        $code = $request['station'];
        return app(CacheShelfService::class)->clearTask($code);
    }

}
