<?php

namespace App\Jobs;

use App\Services\LogService;
use App\Services\StoreService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\QueryException;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;

class StoreCreateInstantBill implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable;


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

    /**
     * Execute the job.
     *
     * @param StoreService $service
     * @return void
     * @throws
     */
    public function handle(StoreService $service)
    {
        if (!$this->stores)return;
        $errors = [];
        foreach ($this->stores as $store){
            try{
                $service->createInstantBill($store);
            }catch(QueryException $qe){
                if ($qe->getCode()!='23000'){
                    LogService::log(__METHOD__,"ERROR-入库生成即时账单",$store->toJson()." | ".$qe->getMessage());
                    $errors = ["store_".$store->id.":".$qe->getMessage()];
                }
            }catch (\Exception $e){
                LogService::log(__METHOD__,"ERROR-入库生成即时账单",$store->toJson()." | ".$e->getMessage());
                $errors = ["store_".$store->id.":".$e->getMessage()];
            }
        }
        if ($errors)throw new \Exception(json_encode($errors));
    }
}
