<?php

namespace App\Jobs;

use App\Events\WeighedEvent;
use App\MeasuringMachine;
use App\OrderPackage;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;

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

    protected $measuringMachine;
    /**
     * Create a new job instance.
     *
     * @param MeasuringMachine$measuringMachine
     *
     * @return void
     */
    public function __construct(MeasuringMachine $measuringMachine)
    {
        $this->measuringMachine=$measuringMachine;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        if ($this->measuringMachine->updated_at<Carbon::now()->subMinutes(30)){
            $this->measuringMachine->status="离线";
            $this->measuringMachine->save();
            $package=OrderPackage::with(['order'=>function($query){
                $query->with('owner','logistic');
            },'paperBox','measuringMachine'])->
            where('measuring_machine_id',$this->measuringMachine->id)->orderBy('id','DESC')->first();
            if (!$package){
                $package=new OrderPackage();
                if ($this->measuringMachine)$package->measuringMachine=$this->measuringMachine;
            }
            event(new WeighedEvent($package));
        }
    }

}
