<?php

namespace Tests\Services\StationTaskCommodityService;
use App\Batch;
use App\Order;
use App\OrderCommodity;
use App\Services\StationTaskCommodityService;
use App\Services\StationTaskService;
use App\StationTask;
use App\Traits\TestMockSubServices;
use Tests\TestCase;
use App\StationTaskCommodity;

class CreateByBatchesTest extends TestCase
{

    use TestMockSubServices;
    /** @var StationTaskCommodityService $service */
    public $service;
    /** @var StationTaskService $service */
    private $stationTaskService;
    private $data;
    private $batchAmount=2;
    private $orderAmount=4;
    private $orderCommodityAmount=8;
    function setUp(): void
    {
        parent::setUp();
        $this->service = app('StationTaskCommodityService');
        $this->stationTaskService = app('StationTaskService');
        $this->data['stationTask'] =
            $this->stationTaskService->create($this->batchAmount);
        $this->data['batches'] =
            factory(Batch::class,
                $this->batchAmount)
                ->create([
                    'status'=>'未处理',
                ]);
        $this->data['orders'] =
            factory(Order::class)
                ->createMany($this->makeArray($this->orderAmount,[
                    'status'=>'未处理',
                    'batch_id' => function(){return $this->getTargetFieldCirculately($this->data['batches']);}
                ]));
        $this->data['orderCommodities'] =
            factory(OrderCommodity::class)
                ->createMany($this->makeArray($this->orderCommodityAmount,[
                    'order_id' => function(){return $this->getTargetFieldCirculately($this->data['orders']);}
                ]));
    }

    public function testReturned()
    {
        $this->data['stationTaskCommodities']=
            $this->service->createByBatches(
                $this->data['batches'],
                $this->data['stationTask']);
        $this->assertEquals($this->orderCommodityAmount, $this->data['stationTaskCommodities']->count());
        $this->assertNotFalse(array_search($this->data['stationTaskCommodities'][0]['id'],
            data_get($this->data['stationTaskCommodities'][0]['stationTask']['stationTaskCommodities'],'*.id')));

    }

    function tearDown(): void
    {
        StationTaskCommodity::query()
            ->whereIn('id',data_get($this->data['stationTaskCommodities'],'*.id')??[])
            ->delete();
        StationTask::query()
            ->whereIn('id',data_get($this->data['stationTask'],'*.id')??[])
            ->delete();
        Batch::query()
            ->whereIn('id',data_get($this->data['batches'],'*.id')??[])
            ->delete();
        Order::query()
            ->whereIn('id',data_get($this->data['orders'],'*.id')??[])
            ->delete();
        OrderCommodity::query()
            ->whereIn('id',data_get($this->data['orderCommodities'],'*.id')??[])
            ->delete();
        parent::tearDown();
    }
}
