<?php

namespace App\Jobs;

use App\Configuration;
use App\Procurement;
use App\Services\ConfigurationService;
use App\Services\LogService;
use App\Services\ProcurementService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;

class ProcurementEnquiry implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $procurement;
    private $unit_price;
    /**
     * Create a new job instance.
     *
     * @param Procurement $procurement
     */
    public function __construct(Procurement $procurement)
    {
        $this->procurement=$procurement;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        /** @var ProcurementService $procurementService*/
        /**@var ConfigurationService $configurationService */
        $configurationService=app(ConfigurationService::class);
        $receive_time=$configurationService->getReceiveTime();
        $priceCoefficient=$configurationService->getPriceCoefficient();
        $procurementService=app(ProcurementService::class);
        $procurementQuotation=$procurementService->screenLowestQuotation($this->procurement->id);
        if (!$procurementQuotation){
            $this->procurement->update(['status'=>3]);
            return;
        }
        if(!$this->procurement->unit_price)$this->unit_price=$priceCoefficient*$procurementQuotation['offer'];
        try{
           $this->procurement->update([
               'status'=>2,
               'unit_price'=>$this->unit_price,
               'cost_price'=>$procurementQuotation['offer'],
               'supplier_id'=>$procurementQuotation['supplier_id'],
               'deadline'=>Carbon::parse(Carbon::now()->toDateTimeString())->subHours(-$receive_time)->toDateTimeString(),
           ]);
            dispatch(new ProcurementReceive($this->procurement))->delay(now()->addHours($receive_time)); //可从系统配置获取
            dispatch(new ProcurementWaitConfirmInform($this->procurement));
        }catch (\Exception $e){
            LogService::log(__METHOD__,"ERROR-采购延时选定最低报价供应商",$this->procurement->toJson()." | ".$e->getMessage());
        }
    }
}
