<?php


namespace App\Services;


use App\Batch;
use App\StationRuleBatch;
use App\StationTaskBatch;
use App\StationType;
use Carbon\Carbon;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;
use App\Traits\ServiceAppAop;
use Illuminate\Support\Facades\DB;


class StationRuleBatchService
{
    use ServiceAppAop;
    protected $modelClass=StationRuleBatch::class;
    function getByBatch(?Batch $batch): ?StationRuleBatch
    {
        LogService::log(__METHOD__,'getByBatch','波次任务分配1.21：'.json_encode($batch));
        $batchType = $batch['type'] ?? 'null';
        $ownerId = $batch['owner_id'] ?? 'null';
        if(!$this->isLocationOfRobot($batch))return null;
        LogService::log(__METHOD__,'getByBatch','波次任务分配1.22：'.($this->isLocationOfRobot($batch)));
        $batch->loadMissing('stationTaskBatch');
//        if($batch['stationTaskBatch'])return null;//? 这行有啥用?
        return Cache::remember('stationRuleBatch_batchType_'.$batchType.'_ownerId_'.$ownerId, config('cache.expirations.rarelyChange'),function()use($batch){
            $builder= StationRuleBatch::query()->with('stationType')
                ->where('owner_id',$batch['owner_id']);
            if($batch['type']
                && $batch['type']!='无'){
                $builder=$builder->where('batch_type',$batch['type']);
            }
            LogService::log(__METHOD__,'getByBatch','波次任务分配1.23：');
            return $builder->first();
        });
    }
    function isLocationOfRobot(?Batch $batch): bool
    {
        if(!$batch)return false;
        $sql = "select count(*) as count from order_commodities where location like 'IDE%' and order_id in (select id from orders where batch_id in (select id from batches where id = ?))";
        $billDetails = DB::select(DB::raw($sql),[$batch['id']]);
        return $billDetails[0]->count>0;
    }

    function getStationType_toBeTask(Batch $batch): ?StationType{
        $stationRuleBatch=$this->getByBatch($batch);
        if(!$stationRuleBatch)return null;
        return $stationRuleBatch['stationType'];
    }

    /**
     * @param Collection $batches
     * @return Collection Batches
     */
    function getBatches_shouldProcess(Collection $batches): Collection
    {
        LogService::log(__METHOD__,'shouldProcess','波次任务分配1.1：'.json_encode($batches));
        $batches_toProcess=collect();
        $batches_inTask=StationTaskBatch::query()->whereIn('batch_id',data_get($batches,'*.id'))->get();
        LogService::log(__METHOD__,'shouldProcess','波次任务分配1.2：'.json_encode($batches_inTask));
        $batches=$batches->whereNotIn('id',data_get($batches_inTask,'*.id')??[]);
        foreach ($batches as $batch){
            $stationRuleBatch=$this->getByBatch($batch);
            if(!$stationRuleBatch)continue;
            if(Cache::tags(['波次防重叠'.$batch['id']])->get($batch['id']))
                continue;
            if($batch->created_at>Carbon::now()->subDay())
                $batches_toProcess->push($batch);
            Cache::tags([ '波次防重叠'.$batch['id']])->put($batch['id'],true,config('haiRou.波次防重叠时间_秒'));
        }
        LogService::log(__METHOD__,'shouldProcess','波次任务分配1.3：'.json_encode($batches_toProcess));
        return $batches_toProcess;
    }
}
