<?php

namespace App;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

/**
 * @property mixed rejectedBill
 */use App\Traits\ModelTimeFormat;

use App\Traits\ModelLogChanging;

class RejectedBillItem extends Model
{
    use ModelLogChanging;

    use ModelTimeFormat;
    use SoftDeletes;
    protected $fillable=['id_rejected_bill','barcode_goods','name_goods','amount','id_quality_label',
        'batch_number','validity_at','made_at','is_checked','remark','is_loaded'];

    protected $appends = ['quality_label'];

    public function rejectedBill(){
        return $this->hasOne('App\RejectedBill', 'id', 'id_rejected_bill');
    }
    public function quality(){
        return $this->belongsTo(QualityLabel::class, 'id_quality_label', 'id');
    }
    public function wmsReflectSku(){
        $bill=$this->rejectedBill()->first();
        $wmsReflectReceive=$bill->wmsReflectReceive()->first();
        if(!$wmsReflectReceive){
            $wmsReflectReceive=WMSReflectReceive::where('ASNREFERENCE3',$bill['logistic_number_return'])->orderBy('id','desc')->first();
            if(!$wmsReflectReceive)return null;
        }
        return $wmsReflectReceive->skus()->where('ALTERNATE_SKU1',$this['barcode_goods']);
    }
    public function injectCommodityName(){
        if(!$this['name_goods'])return;
        $barcode=$this['barcode_goods'];
        $name=$this['name_goods'];
        $owner=Owner::where('name',$this->rejectedBill->owner->name)->first();
        $commodity=Commodity::whereHas('barcodes', function (Builder $query)use($barcode){
            $query->where('code',$barcode);
        })->where('owner_id',$owner ? $owner['id'] : null)->first();
        if($commodity){
            if($commodity['name']!=$name){
                $commodity['name']=$name;
            }
            if(!$commodity['owner_id']){
                $commodity['owner_id']=$owner?$owner['id']:null;
            }
            $commodity->update();
        }
        else{
            $commodity = new Commodity();
            $commodity['name']=$name;
            $commodity['owner_id']=$owner?$owner['id']:null;
            $commodity->save();
            $commodity->newBarcode($barcode);
        }
    }
    public function getQualityLabelAttribute(){
        return $this->quality['name']??'';
    }

}
