<?php


namespace App\Filters;

use Illuminate\Http\Request;

class MaterialFilters
{
    protected $request;
    protected $queryBuilder;
    protected $filters = [];
    protected $array_filter;
    protected $params = ['code','name'];

    public function __construct(Request $request)
    {
        $this->request = $request;
        $this->params = $request->all();
        $this->array_filter = array_filter($this->request->only($this->filters));
    }

    private function isSearchLike($str)
    {
        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;
    }

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

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

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