<?php

namespace App;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use App\Traits\ModelTimeFormat;

class Commodity extends Model
{
    use ModelTimeFormat;
    protected $fillable=['name','sku','owner_id','created_at'];
    protected $appends=['barcode','owner_name','owner_code'];

    public function barcodes()
    {
        return $this->hasMany('\App\CommodityBarcode');
    }
    public function owner(){
        return $this->belongsTo('App\Owner','owner_id','id');
    }
    public function getBarcodeAttribute(){
        return $this->barcodes()->first()['code'];
    }
    public function getOwnerNameAttribute(){
        return $this->owner()->first()['name'];
    }
    public function getOwnerCodeAttribute(){
        return $this['owner'] ? $this['owner']['code'] : null;
    }

    static function newCommodityBy_BarcodeOwnerIdNameSku($barcode,$ownerId,$name,$sku){
        $barcodes=rtrim($barcode,',');
        $barcodes=explode(',',$barcodes);
        foreach ($barcodes as $k=>$barcode){
            if(!trim($barcode)) unset($barcodes[$k]);
        }

        $commodities=[];
        foreach ($barcodes as $barcode){
            if(!trim($barcode))continue;
            $commodity=Commodity::whereHas('barcodes', function (Builder $query)use($barcode){
                $query->where('code',$barcode);
            })->where('name',$name)->where('owner_id',$ownerId)->first();
            if($commodity)$commodities[]=$commodity;
        }

        if(count($barcodes)==count($commodities)&&count($commodities)>0){//过滤掉仅有一个条码相等的。
            $commodity=$commodities[0];
        }else{
            $commodity=null;
        }

        if(!$commodity){
            $commodity=new Commodity(['name'=>$name,'sku'=>$sku,'owner_id'=>$ownerId]);
            $commodity->save();
        }else{
            if(!isset($commodity['name'])||(!isset($commodity['sku'])||$sku)){
                $commodity['name']=$name;
                $commodity['sku']=$sku;
                $commodity->save();
            }
        }
        foreach ($barcodes as $barcode){
            if(!trim($barcode))continue;
//            if(preg_match('/[\x{4e00}-\x{9fa5}]/u',$barcode))continue;
            $commodityBarcode=CommodityBarcode::where('code',$barcode)->where('commodity_id',$commodity['id'])->first();
            if(!$commodityBarcode){
                $commodityBarcode=new CommodityBarcode(['code'=>$barcode,'commodity_id'=>$commodity['id']]);
                $commodityBarcode->save();
            }
        }
        return $commodity;
    }

    public function newBarcode($barcode){
        return CommodityBarcode::query()->firstOrCreate(['commodity_id'=>$this['id'],'code'=>$barcode]);
    }
}
