<?php 

namespace App\Services; 

use App\ProcessStatistic;
use App\Services\common\QueryService;
use Illuminate\Database\Eloquent\Builder;

Class ProcessStatisticService
{ 
    private function conditionQuery(array $params){
        $query = ProcessStatistic::with(['process'/*,'operatorLogSubmit'*/])->orderBy('process_statistics.process_id','DESC')
            ->has('process');
        if ($params["owner_id"] ?? false){
            $owner_id=$params["owner_id"];
            $query=$query->whereHas('process',function (Builder $builder)use($owner_id){
                $builder->where('owner_id',$owner_id);
            });
            unset($params["owner_id"]);
        }
        if ($params["code"] ?? false){
            $code=$params["code"];
            $query=$query->whereHas('process',function (Builder $builder)use($code){
                $builder->where('code','like',$code."%");
            });
            unset($params["code"]);
        }
        if ($params["status"] ?? false){
            $status=$params["status"];
            $query=$query->whereHas('process',function (Builder $builder)use($status){
                $builder->where('status',$status);
            });
            unset($params["status"]);
        }
        if($params['process_method_id'] ?? false){
            $process_method_id = $params['process_method_id'];
            $query=$query->whereHas('process',function (Builder $builder)use($process_method_id){
                $builder->where('process_method_id',$process_method_id);
            });
            unset($params['process_method_id']);
        }
        $columnQueryRules=[
            'started_at_start' => ['alias' => 'started_at','startDate' => ' 00:00:00'],
            'started_at_end' => ['alias' => 'started_at','endDate' => ' 23:59:59'],
            'process_id' => ['multi' => ','],
        ];
        $query = app(QueryService::class)->query($params,$query,$columnQueryRules,"process_statistics");
        return $query;
    }

    public function paginate(array $params){
        return $this->conditionQuery($params)->paginate($params["paginate"] ?? 50);
    }

    public function getSql(array $params){
        return $this->conditionQuery($params)->selectRaw('process_statistics.*')
            ->leftJoin('processes','process_statistics.process_id','processes.id')
                ->selectRaw('processes.created_at process_created_at,processes.code process_code,processes.unit_price process_unit_price,processes.amount process_amount,processes.completed_amount process_completed_amount,processes.status process_status,processes.remark process_remark,processes.balance_remark process_balance_remark')
            ->leftJoin('owners','processes.owner_id','owners.id')
                ->selectRaw('owners.name owner_name')
            ->leftJoin('process_methods','processes.process_method_id','process_methods.id')
                ->selectRaw('process_methods.name process_method_name')
            ->sql();
    }

}