<?php

namespace App\Console\Commands;


use App\Services\StoreService;
use App\ValueStore;
use Illuminate\Console\Command;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;

class WasSyncWmsAsnInformation extends Command
{

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'WasSyncWmsAsnInformation';
    private $task_start_at;
    private $task_end_at;
    private $restart;
    private $is_enabled;
    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '同步WMS的入库信息';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    public function init()
    {
        $this->task_start_at = config('sync.asn_sync.task_start_at');
        $this->task_end_at = config('sync.asn_sync.task_end_at');
        $this->restart = config('sync.asn_sync.restart');
        $this->is_enabled= config('sync.asn_sync.enabled');
    }
    /**
     * Execute the console command.
     * @return void
     */
    public function handle()
    {
        $this->init();
        if($this->is_enabled==false)return;
        sleep(rand(1,2));
        $start_time =  Cache::remember($this->task_start_at,null,function (){
            return ValueStore::query()->firstOrCreate(['name'=>$this->task_start_at])->first()->value;
        });
        $end_time =  Cache::remember($this->task_end_at,null,function (){
            return  ValueStore::query()->firstOrCreate(['name'=>$this->task_end_at])->first()->value;
        });

        $start = Carbon::now();
        // 判断上一次任务异常了
        //1.第一次就异常了
        if(isset($start_time) && empty($end_time) && $start->diffInMinutes(Carbon::parse($start_time)) < $this->restart)return;
        //2.中间某次异常了
        if(isset($start_time) && isset($end_time)
            && Carbon::parse($end_time)->lt(Carbon::parse($start_time))
            && $start->diffInMinutes(Carbon::parse($start_time)) < $this->restart)
            return;

        $start = (string)$start;
        Cache::put($this->task_start_at,$start);
        ValueStore::query()->where('name',$this->task_start_at)->update(['value'=>$start]);
        $this->WasSyncWmsAsn();
        $end = (string)Carbon::now();
        Cache::put($this->task_end_at,$end);
        ValueStore::query()->where('name',$this->task_end_at)->update(['value'=>$end]);
    }

    public function WasSyncWmsAsn(){
        /** @var StoreService $storeService */
        $storeService  = app(StoreService::class);
        $storeService->storeCreateByWms();
        $storeService->storeUpdateByWms();
    }
}
