<?php


namespace App\Filters;


use App\Material;
use App\User;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;

class OwnerMaterialFilters
{
    protected $request;
    protected $queryBuilder;
    protected $materialQuery;
    protected $userQuery;
    protected $filters = [];
    protected $array_filter;
    protected $params = [
        'owner_id','material_code','user_name','created_at_start','created_at_end','special'
    ];

    public function __construct(Request $request)
    {
        $this->request = $request;
    }

    public function apply($builder)
    {
        $this->queryBuilder = $builder;
        $filters = array_filter($this->request->only($this->filters));
        foreach ($filters as $filter => $value) {
            if (method_exists($this, $filter)) {
                $this->$filter($value, $this->queryBuilder);
            }
        }
        $this->afterApply();
        return $this->queryBuilder;
    }

    private function isSearchLike($str):bool
    {
        if (substr($str, 0, 1) == "%" || substr($str, strlen($str) - 1, 1) == "%") {
            return true;
        }
        return false;
    }

    private function searchWay($query, $param, $column)
    {
        if ($this->isSearchLike($param)) {
            $query->where($column, 'like', $param);
        } else {
            $query->whereIn($column, array_filter(preg_split('/[,， ]+/is', $param)));
        }
        return $query;
    }

    private function getMaterialQuery():Builder
    {
        if(!$this->materialQuery)
            $this->materialQuery = Material::query()->selectRaw('id');
        return $this->materialQuery;
    }

    private function getUserQuery():Builder
    {
        if(!$this->userQuery)
            $this->userQuery = User::query()->selectRaw('id');
        return $this->userQuery;
    }

    public function owner_Id($owner_id)
    {
        $this->searchWay($this->queryBuilder,$owner_id,'owner_id');
    }

    public function material_code($material_code)
    {
        $this->getMaterialQuery()->where('code','like',"{$material_code}%");
    }

    public function user_name($user_name)
    {
        $this->getUserQuery()->where('name','like',"{$user_name}%");
    }

    public function created_at_start($created_at)
    {
        $this->queryBuilder->where('created_at','>=',"{$created_at} 00:00:00");
    }

    public function created_at_end($created_at)
    {
        $this->queryBuilder->where('created_at','<=',"{$created_at} 23:59:59");
    }

    public function special($special)
    {
        $this->queryBuilder->where('special','like',"{$special}%");
    }

    public function afterApply()
    {
        if($this->userQuery)
            $this->queryBuilder->whereIn('initiator',$this->userQuery);

        if($this->materialQuery)
            $this->queryBuilder->whereIn('material_id',$this->userQuery);

    }

}
