<?php

namespace App\Services;

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


class ProcessStatisticService
{
    use ServiceAppAop;
    protected $modelClass=ProcessStatistic::class;
    private function conditionQuery(array $params){
        $query = ProcessStatistic::with(['process.owner','operatorLog.user'])->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){
                if (strpos($code, ',') || strpos($code, '，') || strpos($code, ' ')) {
                    $arr = array_filter(preg_split('/[,， ]+/is', $code));
                    $builder->whereIn('code',$arr);
                } else {
                    $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 get(array $params)
    {
        return $this->conditionQuery($params)->get();
    }

}
