<?php

namespace App;

use App\Http\Controllers\Controller;
use Illuminate\Database\Eloquent\Model;

use App\Traits\ModelLogChanging;

class OrderCommodity extends Model
{
    use ModelLogChanging;

    protected $fillable = [
        'id', 'order_id','commodity_id', 'amount','wms_ptltaskid','location'
    ];
    protected $appends=['barcode','name','sku'];
    public function order(){
        return $this->belongsTo('App\Order', 'order_id','id');
    }
    public function commodity(){
        return $this->hasOne('\App\Commodity','id','commodity_id');
    }
    public function orderBin(){
        return $this->hasOne(OrderBin::class,'order_id','order_id');
    }
    public function getBarcodeAttribute(){
        $commodity=$this->commodity()->first();
        if($commodity)return $commodity['barcode'];
        return '';
    }
    public function getNameAttribute(){
        return $this->commodity['name']??'';
    }
    public function getSkuAttribute(){
        return $this->commodity['sku']??'';
    }
    public function getLocationAttribute($var){
        if($var){
            return preg_replace('/_\d$/','',$var);
        }
        return $var??'';
    }
    public function getMaterialBoxPositionAttribute(){
        if($this->attributes['location']){
            preg_match('/_(\d)$/',$this->attributes['location'],$arr);
            if(isset($arr[1]))
                return $arr[1];
        }
        return null;
    }
}
