<?php

namespace App;

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

class Order extends Model
{
    //
    use ModelTimeFormat;

    protected $fillable = [
        'created_at','code','shop_id','owner_id',
        'logistic_id','consignee_name','consignee_phone','province',
        'city','district','address','wms_status'];

    protected $appends = [
        'creator',
        'logisticNumbers',
        'amount',
    ];

    public function logistic(){
        return $this->belongsTo('App\logistic','logistic_id','id');
    }

    public function issue(){
        return $this->hasOne('App\OrderIssue','id','order_id');
    }

    public function shop(){
        return $this->belongsTo('App\Shop','shop_id','id');
    }

    public function owner(){
        return $this->belongsTo('App\Owner','owner_id','id');
    }

    public function packages(){
        return $this->hasMany('App\OrderPackage','order_id','id');
    }

    public function setCreatorAttribute ($id,$user_id){
        Sign::updateOrCreate(['signable_type'=>'orders','signable_id'=>$id,'field'=>'creator','mark'=>$user_id]);
    }

    public function getCreatorAttribute(){
       return  $this->hasOne('App\Sign','signable_id','id')
            ->where('signable_type','orders')
            ->where('field','creator')
            ->value('mark');
    }

    public function getlogisticNumbersAttribute(){
        $packages = $this->packages();
        if(!$packages){
            return [];
        }else{
            $arr = [];
           foreach ( $packages->get() as $package){
               $arr[] = $package->logistic_number;
           }
           return $arr;
        }
    }

    public function getAmountAttribute(){
        $packages = $this->packages();
        if(!$packages){
            return 0;
        }else{
            $count = 0;
            foreach ( $packages->get() as $package){
                foreach ($package->commodities as $item){
                    $count += $item->amount;
                }
            }
            return $count;
        }
    }

}
