<?php

namespace App\Services;

use App\CommodityBarcode;
use Illuminate\Support\Collection;

Class CommodityBarcodeService
{
    public function getCommodities(array $codes, $owner_id){
        return CommodityBarcode::query()->whereHas('commodity',function ($query)use($owner_id){
            $query->where('owner_id',$owner_id);
        })->select('code','commodity_id')->whereIn('code',$codes)->get();
    }

    public function insert(array $params){
        return CommodityBarcode::query()->insert($params);
    }


    public function first(array $params){
        $query = CommodityBarcode::query();
        foreach ($params as $column => $value){
            $query->where($column,$value);
        }
        return $query->first();
    }

    public function get(array $params){
        $query = CommodityBarcode::query()->select('commodity_id','code');
        foreach ($params as $column => $values){
            if (is_array($values)) $query->whereIn($column,$values);
            else $query->where($column,$values);
        }
        return $query->get();
    }

    public function firstOrCreate(array $params, array $value = null)
    {
        if (!$value)$value = $params;
        return CommodityBarcode::query()->firstOrCreate($params,$value);
    }

    public function create(array $params)
    {
        return CommodityBarcode::query()->create($params);
    }

    /**
     * @param array $commoditiesAndBarcodesPacks 格式：[['commodity_id'=>id, barcodes=[str,str,str]], [......]]
     * @return bool
     */
    public function insertMany_onCommodities(array $commoditiesAndBarcodesPacks)
    {
        $commodityBarcodes=[];
        foreach ($commoditiesAndBarcodesPacks as $commoditiesAndBarcodesPack){
            $commodity_id=$commoditiesAndBarcodesPack['commodity_id'];
            $barcodes=$commoditiesAndBarcodesPack['barcodes'];
            foreach ($barcodes as $barcode){
                $commodityBarcodes[]=[
                    'commodity_id'=>$commodity_id,
                    'code'=>$barcode,
                ];
            }
        }
        if(empty($commodityBarcodes))return false;
        return CommodityBarcode::query()->insert($commodityBarcodes);
    }
    public function destroyCollections(Collection $commodityBarcodes)
    {
        $ids=$commodityBarcodes->map(function($commodityBarcode){
            return $commodityBarcode['id'];
        });
        return CommodityBarcode::destroy($ids);
    }
}
