<?php

namespace Tests\Services\StationTaskBatchService;

use App\Batch;
use App\Owner;
use App\Services\StationTaskBatchService;
use App\Services\StationTaskService;
use App\StationRuleBatch;
use App\StationTask;
use App\StationTaskBatch;
use App\StationTaskChild;
use App\StationType;
use Tests\TestCase;

class CreateByBatchesTest extends TestCase
{
    /** @var StationTaskBatchService $service */
    private $service;
    /** @var StationTaskService $service */
    private $stationTaskService;
    private $data = [];
    const AmountOfBatch=3;

    public function setUp(): void
    {
        parent::setUp();
        $this->service = app('StationTaskBatchService');
        $this->stationTaskService = app('StationTaskService');
        $this->data['owner'] =
            factory(Owner::class)
                ->create();
        $this->data['batches'] =
            factory(Batch::class,
                self::AmountOfBatch)
                ->create([
                    'status'=>'未处理',
                    'owner_id'=>$this->data['owner']['id']
                ]);
        $this->data['stationRuleBatch'] =
            factory(StationRuleBatch::class)
                -> create([
                    'owner_id'=>$this->data['owner']['id'],
                ]);
        $this->data['stationTask'] =
            $this->stationTaskService->create(self::AmountOfBatch);
    }

    public function testReturned()
    {
        ($isReturningRightAmount
            =function (){
            $this->data['stationTaskBatches']
                =$this->service->createByBatches($this->data['batches'], $this->data['stationTask']);
            $this->assertEquals(self::AmountOfBatch, $this->data['stationTaskBatches']->count());
        })();

        ($isBindingRightRootTasks
            =function (){
            $this->assertEquals(
                data_get($this->data['stationTask'],'*.id'),
                $this->data['stationTaskBatches']->map(function($taskBatch){
                    $taskBatch->loadMissing('stationTask');
                    return $taskBatch['stationTask']['id'];
                })->toArray()
            );
        })();
    }


    public function tearDown(): void
    {
        Batch::query()->whereIn('id',data_get($this->data['batches'],'*.id')??[])->delete();
        StationTask::query()->whereIn('id',data_get($this->data['stationTask'],'*.id')??[])->delete();
        StationTaskBatch::query()->whereIn('id',data_get($this->data['stationTaskBatches'],'*.id')??[])->delete();
        StationTaskChild::query()->whereIn('station_task_id',data_get($this->data['stationTask'],'*.id')??[])->delete();
        $this->data['stationRuleBatch']->delete();
        Owner::query()->where('id',$this->data['owner']['id']??'')->delete();
        parent::tearDown();
    }

}
