<?php

namespace NewOrderCountingRecordService;


use App\Order;
use App\OrderCountingRecord;
use App\Owner;
use App\Services\NewOrderCountingRecordService;
use App\User;
use Carbon\Carbon;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class OrderCountingRecordsTest extends TestCase
{

    protected $newOrderCountingRecordService;
    protected $queryConditionDay;
    protected $queryConditionWeek;
    protected $queryConditionMonth;
    protected $queryConditionYear;
    protected $ownerIds;
    protected $cache_key = 'order_counting_records_';
    protected $step_length = 1;
    protected $orderCountingRecordIds = [];
    protected $units = ['日', '月', '年'];
    protected $orderIds;


    protected function setUp(): void
    {
        parent::setUp(); // TODO: Change the autogenerated stub
        cache()->flush();
        $this->newOrderCountingRecordService = new NewOrderCountingRecordService();
        $user = User::query()->where('name', 'yang')->first();
        $this->actingAs($user);
        $owners = factory(Owner::class)->times(2)->create();
        $this->ownerIds = array_column($owners->toArray(), 'id');
        $this->queryConditionDay = $this->newOrderCountingRecordService->transfersToCondition(Carbon::now()->subDays($this->step_length)->toDateString(), Carbon::now()->toDateString(), '日', $this->ownerIds);
        $this->queryConditionMonth = $this->newOrderCountingRecordService->transfersToCondition(Carbon::now()->subMonths($this->step_length)->toDateString(), Carbon::now()->toDateString(), '月', $this->ownerIds);
        $this->queryConditionYear = $this->newOrderCountingRecordService->transfersToCondition(Carbon::now()->subYears($this->step_length)->toDateString(), Carbon::now()->toDateString(), '年', $this->ownerIds);
    }

    protected function tearDown(): void
    {
        cache()->flush();
        Owner::destroy($this->ownerIds);
        orderCountingRecord::destroy($this->orderCountingRecordIds);
        parent::tearDown();
    }


    /**
     * @test
     */
    public function unit_day()
    {
        for ($i = 0; $i <= $this->step_length; $i++) {
            foreach ($this->ownerIds as $ownerId) {
                $dateStr = Carbon::now()->subDays($i)->toDateTimeString();
                $order = factory(Order::class)->create([
                    'created_at' => $dateStr,
                    'owner_id' => $ownerId,
                    'wms_status' => '订单完成'
                ]);
                $this->orderIds = $order->id;
            }
        }
        $start = Carbon::now()->subDays($this->step_length)->toDateString();
        $end = Carbon::now()->toDateString();
        $result =  $this->newOrderCountingRecordService->orderCountingRecords($start, $end, '日', $this->ownerIds);
        $this->assertEquals([2,2],$result->pluck('counter')->toArray());
    }
}
