<?php
/**
* @author 龙虾 <15108148@qq.com>
* @version 2.0 2020-08-21
* @copyright 睿谷信息 <www.rgxx.com>
*/
namespace app\home\controller;
use app\common\model\Cmsmodels;
use app\common\model\Cmsfields;
use Request;

class Search extends Base
{
    // 搜索
    public function index()
    {
        $search_map = $search_query = [];
        Request::filter(['trim','strip_tags','htmlspecialchars']);
        $data = Request::get();
        if(empty($data['model'])) $this->error(lang('param_error'));
        // 获取模型信息
        $modelinfo = Cmsmodels::whereName($data['model'])->with('cmsfields')->whereType(1)->find();
        if(!$modelinfo) $this->error(lang('model_no'));
        $search_class = 'app\\common\\model\\'.$modelinfo['classname'];
        if(!class_exists($search_class)) $this->error('model_no');
        // 模板
        $tpl = is_file($this->htmldir.$data['model'].'_search.html') ? $this->htmldir.$data['model'].'_search.html' : $this->htmldir.'default_search.html';
        if(!file_exists($tpl)) abort(500,lang('temp_error').basename($tpl));
        $search_query['model'] = $data['model'];
        if(!empty($data['title'])) {
            $search_map[] = ['title','like','%'.$data['title'].'%'];
            $search_query['title'] = $data['title'];
        }
        // 获取模型自定义字段列表并开启搜素的
        $search_fields = $modelinfo['cmsfields']->where("is_search",">",0);
        foreach ($search_fields as $v) {
            if(!empty($data[$v['name']])) {
                if($v['is_search'] == 1) {
                    $search_map[] = [$v['name'],'=',$data[$v['name']]];
                } else {
                    $search_map[] = [$v['name'],'like','%'.$data[$v['name']].'%'];
                }
                $search_query[$v['name']] = $data[$v['name']];
            }
        }
        if(!$search_map) $this->error('请输入要搜索的内容');
        $this->assign($this->seoinfo);
        return $this->fetch($tpl,compact('search_map','search_class','search_query'));
    }
}
