<?php

namespace App\Events;

use App\DeliveryAppointment;
use App\DeliveryAppointmentCar;
use Illuminate\Broadcasting\Channel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class DeliveryAppointmentEvent implements ShouldBroadcastNow
{
    use Dispatchable, SerializesModels;

    public $delivery;
    /**
     * Create a new event instance.
     *
     * @param DeliveryAppointmentCar|\stdClass $delivery
     *
     * @return void
     */
    public function __construct(DeliveryAppointmentCar $delivery)
    {
        $delivery->load(["deliveryAppointment"=>function($query){
            /** @var Builder $query */
            $query->withCount("cars");
        }]);

        $owner = $delivery->deliveryAppointment->owner->name ?? "";
        $len = mb_strlen($owner);
        $ownerName = "";
        for($i=0;$i<$len-1;$i++)$ownerName .= "*";
        $ownerName .= mb_substr($owner,$len-1,1);

        $count = $delivery->deliveryAppointment->cars_count ?? 0;
        $delivery->warehouse = $delivery->deliveryAppointment->warehouse_id ?? "";
        $delivery->cubic_meter = isset($delivery->deliveryAppointment->cubic_meter) && $delivery->deliveryAppointment->cubic_meter>0 ? ($count>1 ? $delivery->deliveryAppointment->cubic_meter."/".$count : $delivery->deliveryAppointment->cubic_meter) : "";
        $delivery->tonne = isset($delivery->deliveryAppointment->tonne) && $delivery->deliveryAppointment->tonne>0 ? ($count>1 ? $delivery->deliveryAppointment->tonne."/".$count : $delivery->deliveryAppointment->tonne) : "";
        $delivery->license_plate_number = $delivery->license_plate_number ? $delivery->license_plate_number : substr($delivery->appointment_number,0,5)."****".substr($delivery->appointment_number,9,1);
        $delivery->owner_name = $ownerName;
        $delivery->status = DeliveryAppointmentCar::STATUS[$delivery->status];
        $delivery->type = DeliveryAppointment::TYPE[$delivery->deliveryAppointment->type_mark] ?? '';
        $delivery->period = isset($delivery->deliveryAppointment->date_period) ? ($delivery->deliveryAppointment->date_period==0 ? '上午' : '下午') : '';
        $delivery->delivery_time = $delivery->delivery_time ? substr($delivery->delivery_time,11,5) : '';

        $delivery->morrow = $delivery->deliveryAppointment->appointment_date == date('Y-m-d',strtotime("+1 day"));
        $this->delivery = $delivery->withoutRelations();
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new Channel('delivery');
    }

    public function broadcastAs()
    {
        return "car";
    }
}
