<?php


namespace App\Services;


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

class StationTaskService
{
    /** @var StationTaskChildService $stationTaskChildService  */
    private $stationTaskChildService;
    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 二维数组，第一维是对应注册的任务
     * @return array
     */
    function registerSubTasks(Collection $tasks, Collection $subTaskLists): array
    {
        $this->stationTaskChildService=app('StationTaskChildService');
        $taskChildren_toInsert=collect();
        foreach ($subTaskLists as $i=>$subTaskList){
            foreach ($subTaskList as $subTask){
                $tableName=(function()use($subTask){
                    switch (get_class($subTask)){
                        case StationTaskBatch::class: return 'station_task_batches';
                        case StationTaskCommodity::class: return 'station_task_commodities';
                        case StationTaskMaterialBox::class: return 'station_task_material_boxes';
                        default:
                            throw new \Exception('任务类型没有定义相应的模型类');
                    }
                })();
                $paramToInsert = [
                    'station_task_id' => $tasks[$i]['id'],
                    'station_task_table_type' => $tableName,
                    'station_task_table_id' => $subTask['id'],
                ];
                $taskChild=$this->stationTaskChildService->get($paramToInsert)->frist();
                if(!$taskChild)
                    $taskChildren_toInsert->push($paramToInsert);
            }
        }
        $this->stationTaskChildService->insert($taskChildren_toInsert->toArray());
    }

}
