<?php


namespace App\Services;


use App\Events\BroadcastToStation;
use App\Station;
use App\StationTask;
use App\StationType;
use Exception;
use Illuminate\Support\Facades\Cache;
use App\Traits\ServiceAppAop;


class StationService
{
    use ServiceAppAop;
    protected $modelClass=Station::class;
    /** @var $stationTaskService StationTaskService */
    protected $stationTaskService;
    /**
     * @param string $typeName
     * @return Station
     * @throws Exception
     */
    function getStation_byType(string $typeName):Station{
        $station= Cache::remember('Station_typeName_'.$typeName,
            config('cache.expirations.rarelyChange'),
            function ()use($typeName) {
                $stationType= StationType::query()->where('name',$typeName)->orderBy('id')->get('id')->first();
                if(!$stationType) throw new Exception('指定站类型获取不到');
                return Station::query()->where('station_type_id',$stationType['id'])->first();
            });
        if(!$station)throw new Exception('默认站获取不到');
        return $station;
    }

    function getULineEntrance(Station $station):?Station{
        $station->loadMissing(['stationType','child']);
        if (($station['stationType']['name']??'')=='料箱出货口'){
            return $station;
        }
        if (($station['child']['stationType']['name']??'')=='料箱出货口'){
            return $station['child'];
        }
        return null;
    }

    function getULineExit(Station $station):?Station{
        $station->loadMissing(['stationType','child']);
        if ($station['stationType']['name']??''=='料箱入货口'){
            return $station;
        }
        if ($station['child']['stationType']['name']??''=='料箱入货口'){
            return $station['child'];
        }
        return null;
    }


    function broadcast($station_id, ?StationTask $stationTask){
        if($stationTask)
            $json = $stationTask->toJson();
        else
            $json =[];
        LogService::log('海柔请求','broadcastBinMonitor',
            $station_id.'|'.$json);
        broadcast(new BroadcastToStation($station_id, $json));
    }

    function broadcastBinMonitor($station_id, ?StationTask $stationTask){
        if(!$stationTask)return;
        $this->instant($this->stationTaskService,'StationTaskService');
        if($stationTask['status']=='完成')
            $stationTask=$this->stationTaskService->getCurrent_shouldProcess_ByStationId($stationTask['station_id']);
        if($stationTask)
            $stationTask->loadMissing([
                "stationTaskCommodities.commodity.barcodes",
                "stationTaskCommodities.materialBox",
                "stationTaskBatches.batch",
                "stationTaskMaterialBoxes.materialBox",
            ]);
        $this->broadcast($station_id, $stationTask);
    }

}
