<?php

namespace App\Imports;

use App\Commodity;
use App\Owner;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Imports\HeadingRowFormatter;

HeadingRowFormatter::default('none');
class CommodityImport implements ToCollection, WithHeadingRow
{
    protected $isOverride=false;
    public function __construct($isOverride)
    {
        if($isOverride=='1')
            $this->isOverride=true;
    }

    /**
     * @param Collection $collections
     */
    public function collection(Collection $collections)
    {
        foreach ($collections as $row)
        {
            $barcode = $row['商品条码'] ?? $row['barcode'] ?? $row['BARCODE'] ?? $row['Barcode'];
            if(!$barcode)continue;
            $name = $row['商品名称'] ?? $row['name'] ?? $row['NAME'] ?? $row['Name'] ?? '';
            $sku = $row['商品编码'] ?? $row['sku'] ?? $row['SKU'] ?? $row['Sku'] ?? '';
            $owner = $row['货主'] ?? $row['owner'] ?? $row['owner_name'] ?? $row['OWNER'] ?? $row['Owner'] ?? '';
            $owner_id=Owner::where('name',$owner)->value('id');
            $commodity=Commodity::whereHas('barcodes', function (Builder $query)use($barcode){
                $query->where('code',$barcode);
            })->where('owner_id',$owner_id)->first();
            if($commodity){
                if($this->isOverride){
                    $name?$commodity['name']= $name:false;
                    $sku?$commodity['sku']= $sku:false;
                    $owner?$commodity['owner_id']= $owner_id:false;
                    $commodity->update();
                }
            }else{
                $commodity=new Commodity([
                    'name' => $name,
                    'sku' => $sku,
                    'owner_id' => $owner_id,
                ]);
                $commodity->save();
                $commodity->newBarcode($barcode);
            }
        }
    }
}
