<?php


namespace App\Services;


use App\Batch;
use App\StationTask;
use App\StationTaskBatch;
use App\StationTaskChild;
use App\StationTaskCommodity;
use App\StationTaskMaterialBox;
use Illuminate\Support\Collection;
use App\Traits\ServiceAppAop;


class StationTaskService
{
    use ServiceAppAop;
    protected $modelClass=StationTask::class;
    /** @var StationTaskChildService $stationTaskChildService  */
    private $stationTaskChildService;
    /** @var StationService $stationService  */
    private $stationService;
    /** @var BatchService $batchService  */
    private $batchService;
    public function __construct()
    {
        $this->stationTaskChildService=null;
    }

    function create(int $amountToCreate):Collection
    {

        $stationTasks=collect();
        for ($i=0;$i<$amountToCreate;$i++){
            $stationTasks->push(StationTask::query()->create(['status'=>'待处理']));
        }
        return $stationTasks;
    }

    /**
     * 两个列表一一对应，每个task注册一组子任务: [task,task...],[[subTask,subTask],[subTask,subTask]....]
     * @param Collection $tasks
     * @param Collection $subTaskLists 二维数组，第一维是对应注册的任务
     */
    function registerSubTasks(Collection $tasks, iterable $subTaskLists)
    {
        $this->instant($this->stationTaskChildService,'StationTaskChildService');
        $taskChildren_toInsert=collect();
        foreach ($subTaskLists as $i=>$subTaskList){
            foreach ($subTaskList as $subTask){
                $paramToInsert = [
                    'station_task_id' => $tasks[$i]['id'],
                    'station_taskable_type' => get_class($subTask),
                    'station_taskable_id' => $subTask['id'],
                ];
                $taskChild_existed=$this->stationTaskChildService->get($paramToInsert)->first();
                if(!$taskChild_existed){
                    $taskChildren_toInsert->push($paramToInsert);
                    $subTask['station_task_id']=$tasks[$i]['id'];
                    $subTask->save();
                }
            }
        }
        $this->stationTaskChildService->insert($taskChildren_toInsert->toArray());
    }

    function getCurrent_shouldProcess_ByStationId($station_id):?StationTask
    {
        $stationTask=$this->get(['id'=>$station_id,'status'=>['处理中','待处理','异常']]);
        return $stationTask->sortBy('id')->first();
    }

    function registerStations(Collection $tasks, array $station_ids)
    {
        $this->instant($this->stationService,'StationService');
        foreach ($tasks as $i=>$task){
            $task['station_id'] = $station_ids[$i];
            $task->save();
        }
    }

    function getProcessing()
    {
        return StationTask::query()
            ->where(['status'=>'处理中'])
            ->first();
    }
    function markProcessing_byIds($ids)
    {
        if(!$ids)$ids=[];
        if(!is_array($ids))$ids=[$ids];

        $hasProcessing=StationTask::query()
            ->whereNotIn('id', $ids)
            ->where(['status'=>'处理中'])
            ->get('id')->isNotEmpty();

        $status = '处理中';
        if($hasProcessing)
            $status = '处理队列';

        StationTask::query()
            ->whereIn('id',$ids)
            ->update(['status'=>$status]);
    }
    function markProcessed_byIds($ids)
    {
        if(!$ids)$ids=[];
        if(!is_array($ids))$ids=[$ids];
        StationTask::query()
            ->whereIn('id',$ids)
            ->update(['status'=>'完成']);
    }

    function markProcessing($stationTask_orCollection)
    {
        if (get_class($stationTask_orCollection)==StationTask::class){
            $stationTask_orCollection = collect([$stationTask_orCollection]);
        }
        $this->markProcessing_byIds(
                data_get($stationTask_orCollection, '*.station_id')
            );
    }
    function markProcessed($stationTask_orCollection)
    {
        $this->instant($this->batchService, 'BatchService');
        if (get_class($stationTask_orCollection)==StationTask::class){
            $stationTask_orCollection = collect([$stationTask_orCollection]);
        }
        $ids_stationTasks = data_get($stationTask_orCollection, '*.id')??[];
        $this->markProcessed_byIds(
            $ids_stationTasks
        );
        $stationTaskBatches=StationTaskBatch::query()->whereIn('station_task_id',$ids_stationTasks);
        $this->batchService->updateWhereIn('id', data_get($stationTaskBatches, '*.batch_id')??[], ['status' => '已处理']);
    }
}
