<?php

namespace App;

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

use App\Traits\ModelLogChanging;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class ProcurementQuotation extends Model
{
    use ModelLogChanging;
    use ModelTimeFormat;

    protected $fillable=[
        'procurement_id','offer', 'operator', 'quoted_at','status','created_at','supplier_id'
    ];

    const status=[
        0 => "待报价",
        1 => "已报价",
        2 => "待接单",
        3 => "已失效",
        4 => "生成中",
        5 => "待收货",
        6 => "待确定",
        7 => "待出账",
        8 => "已出账",
        9 => "完结",
    ];
    public  function supplier(): \Illuminate\Database\Eloquent\Relations\HasOne
    {
        return $this->hasOne('App\Supplier','id','supplier_id');
    }
    public function procurement(): \Illuminate\Database\Eloquent\Relations\BelongsTo
    {
        return $this->belongsTo('App\Procurement','procurement_id','id');
    }

    protected static function booted()
    {
        /** @var User $user */
        $user = Auth::user();
        if ($user && !$user->isSuperAdmin()) {
            /** @var \stdClass $user */
            $ids = array_column(DB::select(DB::raw("SELECT supplier_id FROM supplier_user WHERE user_id = ?"),[$user->id]),"supplier_id");
            if (count($ids)>0){
                static::addGlobalScope('supplier', function (Builder $builder)use ($ids) {
                    $builder->whereIn('supplier_id',  $ids);
                });
            }
        }
    }
}
