<?php


namespace App\Services;


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

class StationService
{
    /**
     * @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 broadcast($station_id, $json_data){
        broadcast(new BroadcastToStation($station_id,$json_data));
    }

    function broadcastBinMonitor($station_id, StationTask $stationTask){
        $stationTask->loadMissing(["taskCommodities.commodity.barcodes","taskCommodities.materialBox","taskBatches.batch"/*,"taskMaterialBoxes.box"*/]);
        $stationTask->toJson();
        $this->broadcast($station_id, $stationTask->toJson());
        //...
        //$stationTask->stationTaskBatch
        //$stationTask->stationTaskMaterialBox
        //$stationTask->stationTaskCommodities   //'待处理',   '处理中' blue,'完成',green
        //$batch= $stationTask->stationTaskBatch->batch
        //$orders= $batch->....
        //.....
        //$json_data=['batch','stationCommodities','stationMaterialBin','$currentStationTaskCommodity']
        //$this->broadcast($station_id, $json_data)
    }

    function broadcastBinChange($station_id, StationTask $stationTask, int $currentStationTaskCommodity_id){
        //...
        //$stationTask->stationTaskBatch
        //$stationTask->stationTaskMaterialBox
        //$stationTask->stationTaskCommodities   //'待处理',   '处理中' blue,'完成',green
        //$batch= $stationTask->stationTaskBatch->batch
        //$orders= $batch->....
        //.....
        //$json_data=['batch','stationCommodities','stationMaterialBin','$currentStationTaskCommodity']
        //$this->broadcast($station_id, $json_data)
    }

    function broadcastBinMonitorWarning($warnText, $station_id, StationTask $stationTask){
        //...
        //...
        //$json_data=['warn']
        //$this->broadcast($station_id, $json_data)
    }

}
