<?php

namespace App\Services;

use App\Owner;
use App\Procurement;
use App\ProcurementQuotation;
use App\Services\common\QueryService;
use App\Supplier;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Auth;
use App\Traits\ServiceAppAop;


class ProcurementService
{
    use ServiceAppAop;

    //选中最低报价
    public function screenLowestQuotation($procurement_id){
        if (!$procurement_id) return null;
        return ProcurementQuotation::query()
            ->with(['supplier','procurement'])
            ->select('procurement_id','supplier_id','offer')
            ->orderBy('offer','asc')
            ->where('procurement_id',$procurement_id)
            ->first();
    }

    public function computeDeadline($time): string
    {
        /**@var ConfigurationService $configurationService */
        $configurationService=app(ConfigurationService::class);
        $enquiry_time=$configurationService->getEnquiryTime();
        $date=Carbon::parse($time)->toDateString();
        $date_tom=Carbon::parse($time)->subDays(-1)->toDateString();
        $hour=Carbon::parse($time)->format('H');
        if ($hour < 9)return Carbon::parse($date." 09:00:00")->subHours(-$enquiry_time)->toDateTimeString();
        if ($hour >=9 && $hour <12)return Carbon::parse($time)->subHours(-$enquiry_time-1)->toDateTimeString();
        if ($hour ==12)return Carbon::parse($date." 13:00:00")->subHours(-$enquiry_time)->toDateTimeString();
        if ($hour >12 && $hour < 18){
            if (18-$hour>=$enquiry_time) return Carbon::parse($date." ".$hour.":00:00")->subHours(-$enquiry_time)->toDateTimeString();
            return Carbon::parse($date_tom." 09:00:00")->subHours(-$enquiry_time+(18-$hour))->toDateTimeString();
        }
        if ($hour>=18)return Carbon::parse($date_tom." 09:00:00")->subHours(-$enquiry_time)->toDateTimeString();

    }
    public function screenSupplier($user,$material)
    {
        //通过当前登录用户及采购单对应相应耗材筛选出指定供应商
        $supplier=Supplier::query()
            ->whereHas('user',function($query)use($user){
                /** @var Builder $query */
                return $query->where('id',$user->id);
            })
            ->whereHas('material',function ($builder)use ($material){
                /** @var Builder $builder */
                return $builder->where('id',$material['id']);
            })->first();
        if ($supplier) return $supplier;
    }
}
