<?php

namespace Tests\Services\StoreService;

use App\Logistic;
use App\OracleDOCASNHeader;
use App\Owner;
use App\Services\common\DataHandlerService;
use App\Services\LogisticService;
use App\OracleDOCOrderHeader;
use App\Services\OracleDOCOrderHeaderService;
use App\Services\OrderService;
use App\Services\OwnerService;
use App\Services\ShopService;
use App\Services\StoreService;
use App\Services\WarehouseService;
use App\Shop;
use App\ValueStore;
use App\Warehouse;
use Carbon\Carbon;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Support\Facades\DB;
use Tests\TestCase;

class SyncStoreCreateByWmsTest extends TestCase
{
    /**
     * @var StoreService $service
     */
    public $service;
    public $stores;
    public $asnHeaders;
    public $created_at;
    public $last_time;
    public function setUp(): void
    {
        parent::setUp();
        $this->service=app(StoreService::class);
    }

    /**
     * @test
     */
    public function testStoreCreateByWms()
    {
        $this->created_at = config('sync.asn_sync.created_at');
        $this->last_time = ValueStore::query()->where('name',$this->created_at)->value('value');
        if (!$this->last_time) $time=Carbon::now()->subSeconds(65);
        $this->asnHeaders=OracleDOCASNHeader::query()
            ->with(['asnType', 'asnStatus', 'asnDetails' => function ($query) {
                $query->with(['lineStatus', 'qualityStatus','basSku']);
            }])
            ->select('asnno','asnstatus','asntype','addtime','edittime','customerid','notes','warehouseid','asnreference3')
            ->where('addTime', '>=',  $this->last_time??$time)
            ->orderByDesc('addtime')
            ->get();
        $this->service->storeCreateByWms();
        $this->stores = $this->service->getByWms($this->asnHeaders);
        $this->assertNotNull($this->stores);
        $this->assertEquals(count($this->asnHeaders),count($this->stores));
    }

    public function tearDown(): void
    {
        ValueStore::query()->updateOrCreate([
            'name' => $this->created_at,
        ], [
            'name' => $this->created_at,
            'value' => $this->last_time,
        ]);
        $storeIds=[];
        foreach ($this->stores as $store){
            array_push($storeIds,$store->id);
        }
        DB::table('stores')->whereIn('asn_code',data_get($this->asnHeaders,'*.asnno'))->delete();
        DB::table('store_items')->whereIn('store_id',$storeIds)->delete();
        cache()->flush();
        parent::tearDown(); // TODO: Change the autogenerated stub
    }
}
