<?php

namespace App\Services;

use App\Process;
use App\Services\common\QueryService;
use Carbon\Carbon;
use Illuminate\Http\Request;

Class ProcessService
{
    private function conditionQuery(Request $request){
        $processes=Process::filterAuthorities()->with(['tutorials','signs',
            'signUnitPrice','processesContents'=>function($query){
            return $query->with(['signCommodityName','signCommoditySku','commodity'=>function($query){
                return $query->with('barcodes');
            }]);
        }])->orderBy('processes.id','DESC');
        if ($request->input('commodity_barcode')){
            $barcode=$request->input('commodity_barcode');
            $processes=$processes->whereHas('processesContents',function ($query)use($barcode){
                $query->whereHas('commodity',function ($builder)use($barcode){
                    $builder->whereHas('barcodes',function ($builder)use($barcode){
                        $builder->where('code','like',$barcode);
                    });
                });
            });
            $request->offsetUnset('commodity_barcode');
        }
        if ($request->input('wms_code')){
            $wms_code=$request->input('wms_code');
            $processes=$processes->whereHas('processesContents',function ($builder)use ($wms_code){
                $builder->where('wms_code','like',$wms_code);
            });
            $request->offsetUnset('wms_code');
        }
        if (!$request->is_accomplish){
            $processes=$processes->where('status','!=','交接完成');
        }else $request->offsetUnset('is_accomplish');
        $columnQueryRules=[
            'date_start' => ['alias' => 'created_at' , 'startDate' => ' 00:00:00'],
            'date_end' => ['alias' => 'created_at' , 'endDate' => ' 23:59:59'],
            'code' => ['like' => ''],
            'owner_id' => ['multi' => ','],
        ];
        $processes = app(QueryService::class)->query($request,$processes,$columnQueryRules);
        return $processes;
    }

    public function paginate(Request $request){
        return $this->conditionQuery($request)->paginate($request->paginate ?? 50);
    }

    public function get(Request $request){
        return $this->conditionQuery($request)->get();
    }

    public function some(Request $request){
        return Process::filterAuthorities()->with(['processesContents'=>function($query){
            return $query->with(['commodity'=>function($query){
                return $query->with('barcodes');
            }]);
        }])->orderBy('processes.id','DESC')->whereIn('processes.id',explode(',',$request->data))->get();
    }

}
