<?php

namespace App;

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

use App\Traits\ModelLogChanging;

class Commodity extends Model
{
    use ModelLogChanging;

    use ModelTimeFormat;
    protected $fillable=['name','sku','owner_id','created_at','length',
        'width','height','volumn',"type","pack_spec",'updated_at',"remark"];
    protected $appends=['barcode'];

    public function setNameAttribute($value){
        $this->attributes['name']=str_replace(PHP_EOL,'',$value);
    }
    public function getNameAttribute($value){
        return str_replace(array("\r\n","\n","\r","\"","&quot;"),' ',$value);
    }
    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[0]['code']??'';
    }
    public function getOwnerNameAttribute(){
        return $this->owner['name']??'';
    }
    public function getOwnerCodeAttribute(){
        return $this->owner['code']??'';
    }

    public function newBarcode($barcode){
        $barcodeModel = $this->barcodes()->where('code', $barcode)->first();
        if(!$barcodeModel){
            return CommodityBarcode::query()->create(['commodity_id'=>$this['id'],'code'=>$barcode]);
        }
        return $barcodeModel;
    }
}
