<?php

namespace App\Jobs;

use App\Models\Bike;
use App\Models\WorkOrder;
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;
use Illuminate\Support\Facades\Log;

class VerifyChargeWorkOrderJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    public $tries = 5;

    private $work_no;

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

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        //
        $work_order = WorkOrder::query()->where('work_no', $this->work_no)->first();
        if (empty($work_order)) {
            Log::error('charge工单验证时,找不到工单内容,工单号为:' . $this->work_no);
            return;
        }
        $bike_id = $work_order->bike_id;
        $bike = Bike::query()->find($bike_id);
        if (empty($bike)) {
            Log::error('charge工单验证时,找不到工单车辆信息,工单号为:' . $this->work_no);
            return;
        }
        if ($bike->battery_power > config('bike.huan_max_battery_power')) {
            try {
                $work_order->status = WorkOrder::STATUS_OK;
                $work_order->planned = WorkOrder::PLANNED_STATUS_OVER;
                $work_order->fix_end_time = Carbon::now();

                $work_order->save();
            } catch (\Exception $e) {
                Log::error('更新watch工单为结束状态失败' . $e->getMessage());
            }
        } else {
            // 未通过验证  改为未待处理状态
            try {
                $work_order->planned = WorkOrder::PLANNED_STATUS_WORK;
                $work_order->save();
            } catch (\Exception $e) {
                Log::error('更新watch工单为待处理状态失败' . $e->getMessage());
            }
        }
    }
}