<?php
namespace app\daohang\controller;

use app\daohang\controller\Front;

class Search extends Front
{
    public function _initialize()
    {
        //post请求
        if($this->request->isPost()){
            $this->redirect(DcUrl('daohang/search/'.$this->request->action(),['searchText'=>$this->request->post('searchText')]),302);
        }
        //请求验证
        $this->requestCheck();
        //请求过滤
        $this->request->filter('trim,strip_tags,htmlspecialchars');
        //继承上级
        parent::_initialize();
    }
    
    public function index()
    {
        return $this->detail('index');
    }
    
    public function baidu()
    {
        $this->redirect('https://www.baidu.com/s?wd='.$this->query['searchText'],302);
    }
    
    public function sogou()
    {
        $this->redirect('https://www.sogou.com/web?query='.$this->query['searchText'],302);
    }
    
    public function toutiao()
    {
        $this->redirect('https://so.toutiao.com/search?mod=website&keyword='.$this->query['searchText'],302);
    }
    
    public function bing()
    {
        $this->redirect('https://cn.bing.com/search?q='.$this->query['searchText'],302);
    }
    
    public function so()
    {
        $this->redirect('https://www.so.com/s?q='.$this->query['searchText'],302);
    }
    
    public function _empty($action='')
    {
        //模型验证
        $this->actionCheck($action);
        //查询数据
        return $this->detail($action);
    }
    
    private function detail($action='index')
    {
        //判断是否有关键词
        if( !$this->query['searchText'] ){
            $this->error(lang('daohang/error/params'),'daohang/index/index');
        }
        
        //搜索频率验证
        if( !$this->searchCheck() ){
            $this->error(lang('daohang/error/rest'), 'daohang/index/index');
        }
        
        //地址栏
        $info = [];
        $info['searchText'] = $this->query['searchText'];
        $info['pageSize']   = daohangLimit(config('daohang.limit_search'));
        $info['pageNumber'] = $this->site['page'];
        $info['sortName']   = 'info_order';
        $info['sortOrder']  = 'desc';
        
        //分页路径
        $info['pagePath'] = DcUrl('daohang/search/'.$action,[
            'searchText' => $info['searchText'],
            'pageNumber' => '[PAGE]',
        ]);
        
        //搜索引擎列表
        $info['searchList']  = $this->searchList($info['searchText']);
        
        //SEO优化TKD
        $info['seoTitle'] = str_replace('[searchText]', $info['searchText'], daohangSeo(config('daohang.search_title'),$this->site['page']));
        $info['seoKeywords'] = str_replace('[searchText]', $info['searchText'], daohangSeo(config('daohang.search_keywords'),$this->site['page']));
        $info['seoDescription'] = str_replace('[searchText]', $info['searchText'], daohangSeo(config('daohang.search_description'),$this->site['page']));
        
        //查询数据
        $item = daohangSelect([
            'cache'      => true,
            'status'     => 'normal',
            'action'     => $action,
            'sort'       => $info['sortName'],
            'order'      => $info['sortOrder'],
            'limit'      => $info['pageSize'],
            'page'       => $info['pageNumber'],
            'with'       => 'term,info_meta',
            'group'      => 'info.info_id',
            'field'      => 'info_name,info_slug,info_action,info_excerpt,info_status,info_order,info_views,info_hits,info_create_time,info_update_time',
            'whereOr'    => ['info_module="daohang" and info_controll="detail" and info_name like "%'.$info['searchText'].'%"'],
            'meta_query' => [
                [
                    'key'   => ['eq','info_referer'],
                    'value' => ['like','%'.$info['searchText'].'%'],
                ],
            ],
        ]);
        if($item){
            $this->assign($item);
        }
        
        //模板变量
        $this->assign($info);
        
        //加载模板
        return $this->fetchTpl($action);
    }
    
    //搜索请求是否合法（搜索间隔时长）
    private function searchCheck()
    {
        //后台验证开关
        $configInterval = intval(config('daohang.search_interval'));
        if($configInterval < 1){
            return true;
        }
        //搜索限制白名单
        if( \daicuo\Auth::check('daohang/search/common', $this->site['user']['user_capabilities'], $this->site['user']['user_caps']) ){
            return true;
        }
        //客户端唯一标识
        $client = md5($this->request->ip().$this->request->header('user-agent'));
        //几秒内不得再次搜索(缓存标识未过期)
        if( DcCache('search'.$client) ){
            return false;
        }
        DcCache('search'.$client, 1, $configInterval);
        //未超出限制
        return true;
    }
    
    //定义搜索引擎列表
    private function searchList($searchText='')
    {
        $result = [];
        $result['daohang/search/index'] = daohangUrlSearch('daohang/search/index',['searchText' => $searchText]);
        foreach(explode(',',config('daohang.search_list')) as $key=>$name){
            $result[$name] = daohangUrlSearch($name,['searchText' => $searchText]);
        }
        return $result;
    }
}