<?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 ProcurementTotalBill extends Model
{
    use ModelLogChanging;
    use ModelTimeFormat;

    const status=[
        0 => "未出账",
        1 => "已出账",
        2 => "已完结",
    ];

    protected $fillable=[
        'counting_month','supplier_id','status','total_payable'
    ];
    public function supplier(): \Illuminate\Database\Eloquent\Relations\BelongsTo
    {
        return $this->belongsTo('App\Supplier','supplier_id','id');
    }
    public function procurement()
    {
        return $this->hasMany('App\Procurement','supplier_id','supplier_id')
            ->whereNotIn('status',[3,10]);
    }

    //截取账单日期为月
    public function getCountingMonthAttribute($value)
    {
        return substr($value,0,7);
    }

    public function  setCurrentMothProcurements(){
        $ProcurementQuery = Procurement::query()->select("id")
            ->where('supplier_id',$this->supplier_id);
         $procurementDeliveryQuery= ProcurementDeliverie::query()->select('id')
            ->whereIn("procurement_id",$ProcurementQuery)
            ->where("created_at","like",$this->counting_month."%");
        $this->relations["procurementCheckSheets"]=ProcurementCheckSheet::query()
            ->with(['procurementDelivery.procurement.ownerMaterial.material','procurementDelivery.procurement.supplier'])
            ->whereIn('procurement_delivery_id',$procurementDeliveryQuery)->get();
    }

    public function checkSheet()
    {

    }

    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);
                });
            }
        }
    }

}
