<?php
/**
 * User: Mike
 * Email: m@9026.com
 * Date: 2017/1/12
 * Time: 17:52
 */

namespace App\Repositories\Settings\Banner\Criteria;


use App\Repositories\Base\Criteria;
use App\Repositories\Contracts\RepositoryInterface as Repository;

class MultiWhere extends Criteria {

    private $search = [];

    /**
     * MultiWhere constructor.
     * @param array $search
     *
     */
    public function __construct(array $search)
    {
        $this->search = $search;
    }

    /**
    * @param $model
    * @param RepositoryInterface $repository
    * @return mixed
    */
    public function apply($model, Repository $repository)
    {
        //有返回/banner/首次出现的位置 无返回false
        $url =  strpos(url()->current(), '/banner/');
        $appid = $this->search['appid'];
        if ($url !== false) {
            if(isset($this->search['keyword']) && ! empty($this->search['keyword'])) {
                $keywords = '%' . $this->search['keyword'] . '%';
                $model = $model->where(function ($query) use ($keywords) {
                    $query->where('id'  , 'like', $keywords)
                        ->where('category','banner')
                        ->orwhere('sort', 'like', $keywords);
                });
            }else{
                $model = $model->where('category','banner');
            }
        }else{          //sign标签
            if(isset($this->search['keyword']) && ! empty($this->search['keyword'])) {
                $keywords = '%' . $this->search['keyword'] . '%';
                $model = $model->where(function ($query) use ($keywords) {
                    $query->where('id'  , 'like', $keywords)
                        ->where('category','sign')
                        ->orwhere('value', 'like', $keywords);
                });
            }else{
                $model = $model->where('category','sign');
            }
        }
        return $model->where('appid',$appid);
    }

}