<?php
namespace app\common\controllers;
use yii\helpers\Url;
use app\common\components\SiteUrl;
use app\common\helpers\Identify;
use app\modules\ad\models\AdData;
use app\modules\shopping\models\ShoppingStore;
use app\modules\ucenter\models\UserFavorite;
use app\common\components\CacheId;
use app\models\SearchRecord;
use app\common\components\MultiSearchUrl;
use app\models\ContentModel;
use app\models\ContentModelField;
use yii\data\Pagination;
use Yii;

/**
 * 前台基类
 */
class FController extends CController
{

    public $homeUrl;//首页地址
    public $userInfo;
    public $navList;//头部导航
    public $footerLinks;//底部链接
    public $wapMenuList;//手机端菜单
    public $wapNavList;//手机端导航
    public $filterConfig;//多条件筛选初始配置
    public $keywords;//Meta keywords
    public $description;//Meta keywords
    public $searchtitle;//Meta searchtitle;
    public function init()
    {
        parent::init();
        $this->homeUrl = Url::to(['/web/default/index'],true);
        $this->navList = $this->getNavData(2);//默认取PC内页导航数据
        $this->footerLinks = $this->getNavData(4);
        $this->wapNavList = $this->getNavData(6);
        $this->userInfo = Identify::getUserInfo();
        $this->initFilterConfig();
    }

    public function behaviors()
    {

        parent::behaviors();
        return [

            [
                'class' => 'app\common\filters\FrontEndTokenFilter',
            ],
        ];
    }




    //获取导航/链接数据
    public  function getNavData($type)
    {
        $allNavList =  json_decode(Yii::$app->cache->get(CacheId::navCacheId()),true);
        $navList = $allNavList[$type];
        $navData = [];
        if(is_array($navList))foreach($navList as $nav)
        {
            if($nav['parent_id']>0)continue;
            if($nav['is_dropdown']&&$nav['dropdown_level']>0)
            {
                if($nav['content_model_id'])
                {
                    $modelList =  json_decode(Yii::$app->cache->get(CacheId::modelListCacheId()),true);
                    $functionName = $modelList[$nav['content_model_id']]['table_name'].'List';
                    //SiteUrl::$functionName(8);
                    $categoryList = json_decode(Yii::$app->cache->get(CacheId::categoryItemsCacheId($nav['content_model_id'])),true);
                    $childs = [];
                    if(is_array($categoryList))foreach($categoryList as $category)
                    {
                        if(empty($category['parent_id']))
                        {
                            //二级菜单
                            $secChilds = [];
                            if(is_array($categoryList))foreach($categoryList as $secCategory)
                            {
                                if($secCategory['parent_id']==$category['cat_id'])
                                {
                                    //三级菜单
                                    $thirdChilds = [];
                                    if(is_array($categoryList))foreach($categoryList as $thirdCategory)
                                    {
                                        if($thirdCategory['parent_id']==$secCategory['cat_id'])
                                        {
                                            $thirdChilds[] = array('title'=>$thirdCategory['cat_name'],'url'=>SiteUrl::$functionName($thirdCategory['cat_id']),'blank'=>$nav['blank']);
                                        }
                                    }

                                    $secChilds[] = array('title'=>$secCategory['cat_name'],'url'=>SiteUrl::$functionName($secCategory['cat_id']),'blank'=>$nav['blank'],'childs'=>$thirdChilds);

                                }
                            }
                            $childs[] =  array('title'=>$category['cat_name'],'url'=>SiteUrl::$functionName($category['cat_id']),'blank'=>$nav['blank'],'childs'=>$secChilds);

                        }
                    }
                    $navData[] = array('title'=>$nav['title'],'url'=>$nav['url'],'blank'=>$nav['blank'],'width'=>$nav['width'],'is_dropdown'=>$nav['is_dropdown'],'dropdown_level'=>$nav['dropdown_level'],'iconfont'=>$nav['iconfont'],'childs'=>$childs);
                }
                else
                {
                    $childs = [];
                    if(is_array($navList))foreach($navList as $childNav)
                    {
                        if($childNav['parent_id']==$nav['id'])
                        {
                            $secChilds = [];
                            if(is_array($navList))foreach($navList as $secNav)
                            {
                                if($secNav['parent_id']==$childNav['id'])
                                {
                                    //三级菜单
                                    $thirdChilds = [];
                                    if(is_array($navList))foreach($navList as $thirdNav)
                                    {
                                        if($thirdNav['parent_id']==$secNav['id'])
                                        {
                                            $thirdChilds[] = array('title'=>$thirdNav['title'],'url'=>$thirdNav['url'],'blank'=>$thirdNav['blank'],'is_new'=>$thirdNav['is_new'],'is_hot'=>$thirdNav['is_hot'],'iconfont'=>$thirdNav['iconfont']);
                                        }
                                    }
                                    $secChilds[] = array('title'=>$secNav['title'],'url'=>$secNav['url'],'blank'=>$secNav['blank'],'is_new'=>$secNav['is_new'],'is_hot'=>$secNav['is_hot'],'iconfont'=>$secNav['iconfont'],'childs'=>$thirdChilds);
                                }
                            }
                            $childs[] = array('title'=>$childNav['title'],'url'=>$childNav['url'],'blank'=>$childNav['blank'],'is_new'=>$childNav['is_new'],'is_hot'=>$childNav['is_hot'],'iconfont'=>$childNav['iconfont'],'childs'=>$secChilds);
                        }
                    }
                    $navData[] = array('title'=>$nav['title'],'url'=>$nav['url'],'blank'=>$nav['blank'],'width'=>$nav['width'],
'is_dropdown'=>$nav['is_dropdown'],'dropdown_level'=>$nav['dropdown_level'],'iconfont'=>$nav['iconfont'],'childs'=>$childs);
                }
            }
            else
            {

                $childs = [];
                if(is_array($navList))foreach($navList as $childNav)
                {
                    if($childNav['parent_id']==$nav['id'])
                    {
                        $secChilds = [];
                        if(is_array($navList))foreach($navList as $secNav)
                        {
                            if($secNav['parent_id']==$childNav['id'])
                            {
                                //三级菜单
                                $thirdChilds = [];
                                if(is_array($navList))foreach($navList as $thirdNav)
                                {
                                    if($thirdNav['parent_id']==$secNav['id'])
                                    {
                                        $thirdChilds[] = array('title'=>$thirdNav['title'],'url'=>$thirdNav['url'],'blank'=>$thirdNav['blank'],'is_new'=>$thirdNav['is_new'],'is_hot'=>$thirdNav['is_hot'],'iconfont'=>$thirdNav['iconfont']);
                                    }
                                }
                                $secChilds[] = array('title'=>$secNav['title'],'url'=>$secNav['url'],'blank'=>$secNav['blank'],'is_new'=>$secNav['is_new'],'is_hot'=>$secNav['is_hot'],'iconfont'=>$secNav['iconfont'],'childs'=>$thirdChilds);
                            }
                        }

                        $childs[] = array('title'=>$childNav['title'],'url'=>$childNav['url'],'blank'=>$childNav['blank'],'is_new'=>$childNav['is_new'],'is_hot'=>$childNav['is_hot'],'iconfont'=>$childNav['iconfont'],'childs'=>$secChilds);
                    }
                }

                $navData[] = array('title'=>$nav['title'],'url'=>$nav['url'],'blank'=>$nav['blank'],'is_dropdown'=>$nav['is_dropdown'],'dropdown_level'=>$nav['dropdown_level'],'iconfont'=>$nav['iconfont'],'childs'=>$childs);
            }
        }
        return $navData;
    }

    //单条记录字段值修改
    public function actionSetfield()
    {
        $table = strtolower(safe_replace($_GET['table']));
        $fileldName = safe_replace($_GET['field']);
        $fieldValue = safe_replace($_GET['value']);
        $pk = safe_replace($_GET['pk']);
        $pkField = \app\common\models\EActiveRecord::getPrikey($table);
        if(!empty($pk)&&!empty($fileldName))
        {
            if(empty($this->userInfo))
            {
                $msgdata = ['error' => 1,'msg' => '操作失败'];
            }
            else
            {
                $result  =  Yii::$app->db->createCommand("UPDATE {{%$table}} SET $fileldName='$fieldValue' WHERE $pkField='$pk' and user_id=".$this->userInfo['user_id'])->execute();
                if($result)
                {
                    $msgdata = ['error' => 0,'msg' => '操作成功'];
                }
                else
                {

                    $msgdata = ['error' => 1,'msg' => '操作失败'];
                }
            }

        }
        else
        {

            $msgdata = ['error' => 1,'msg' => '操作失败'];
        }
        echo_json($msgdata);
    }

    //获取广告数据
    public function getAdData($space_id)
    {
        $dataList = AdData::find()->where("space_id='".$space_id."' and status=1 and end_time>".TIMESTAMP)->orderBy(['list_order'=>SORT_ASC])->all();
        return $dataList;
    }

    //判断当前用户是否已关注该记录
    public function checkFavor($table_name,$data_id)
    {
        if($this->hasLogined())
        {
            $user_id = Identify::getUserInfo(null,'user_id');
            $exist = UserFavorite::find()->where("user_id=$user_id and table_name='".$table_name."' and data_id='".$data_id."'")->exists();
            if($exist)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        else
        {
            return false;
        }

    }

    //返回个人主页链接
    function getUpage($user_id,$open_home=0)
    {
        if(defined('IN_WAP')&&IN_WAP==TRUE)
        {
            $str = 'href="javascript:;"';
        }
        else
        {
            if($open_home)
            {
                $str = 'href="'.\app\common\components\SiteUrl::uHome($user_id).'" target="_blank"';
            }
            else
            {
                $str = 'href="javascript:;"';
            }
        }

        return $str;
    }

    //返回前台创作者名称信息
    function getOwnername($user_id,$nick_name='')
    {
        if(empty($user_id))return '游客';
        $store = ShoppingStore::find()->where("user_id=$user_id")->one();
        if($store)
        {
            return $store->store_name;
        }
        else
        {
            if(!empty($nick_name))
            {
                return $nick_name;
            }
            else
            {
                $user = \app\modules\ucenter\models\User::findOne($user_id);
                return $user->nick_name;
            }

        }
    }

    //返回前台创作者名称信息
    function getOwneravatar($user_id,$avatar='')
    {
        if(empty($user_id))return;
        $store = ShoppingStore::find()->where("user_id=$user_id")->one();
        if($store)
        {
            return $store->logo;
        }
        else
        {
            if(!empty($avatar))
            {
                return $avatar;
            }
            else
            {
                $user = \app\modules\ucenter\models\User::findOne($user_id);
                return $user->avatar;
            }

        }
    }

    //返回前台主页简介
    function getOwnerdes($user_id,$des='')
    {
        if(empty($user_id))return '';
        $store = ShoppingStore::find()->where("user_id=$user_id")->one();
        if($store)
        {
            return $store->desc;
        }
        else
        {
            if(!empty($des))
            {
                return $des;
            }
            else
            {
                $user = \app\modules\ucenter\models\User::findOne($user_id);
                return $user->signature;
            }

        }
    }

    //返回前台主页关键词
    function getOwnerkeywords($user_id,$keywords='')
    {
        if(empty($user_id))return '';
        $store = ShoppingStore::find()->where("user_id=$user_id")->one();
        if($store)
        {
            return $store->keywords;
        }
        else
        {
            return $keywords;

        }
    }
    //初始化列表多条件筛选配置
    public function initFilterConfig()
    {
        //文档筛选条件
        $this->filterConfig['doc'] = array(
           'fieldConfig' => array(
                'c'=>array('type'=>'cat_ids','flag'=>'like','field'=>'cat_ids'),
                'xa'=>array('type'=>'equal','flag'=>'=','field'=>'ext_type_1'),
                'xb'=>array('type'=>'equal','flag'=>'=','field'=>'ext_type_2'),
                'xc'=>array('type'=>'equal','flag'=>'=','field'=>'ext_type_3'),
                'xd'=>array('type'=>'equal','flag'=>'=','field'=>'ext_type_4'),
                'xe'=>array('type'=>'equal','flag'=>'=','field'=>'ext_type_5'),
                'sp'=>array('type'=>'boollist','flag'=>'=','field'=>array('is_new','is_hot','is_original','is_recommend')),
                'vp'=>array('type'=>'boollist','flag'=>'=','field'=>array('is_vip','vip_free','is_free')),
            ),
            'sortConfig' => array(
                '1'=>array('value'=>1, 'order'=>'create_time desc','title'=>'最新上传','tips'=>'点击按上传时间排序'),
                '2'=>array('value'=>2, 'order'=>'downs desc','title'=>'热门下载','tips'=>'点击按下载量排序'),
                '3'=>array('value'=>3, 'order'=>'views desc','title'=>'浏览优先','tips'=>'点击按浏览量排序'),
                '4'=>array('value'=>4, 'order'=>'favors desc','title'=>'收藏优先','tips'=>'点击按收藏量排序'),
            ),
            'sortConfigWap' => array(
                '1'=>array('value'=>1, 'order'=>'create_time desc','title'=>'综合','tips'=>'点击按上传时间排序'),
                '2'=>array('value'=>2, 'order'=>'downs desc','title'=>'下载量','tips'=>'点击按下载量排序'),
                '3'=>array('value'=>3, 'order'=>'views desc','title'=>'浏览量','tips'=>'点击按浏览量排序'),
            ),
            'xConfig' => array('1'=>'xa','2'=>'xb','3'=>'xc','4'=>'xd','5'=>'xe'),
            'spConfig' => array('1'=>'最新','2'=>'最热','3'=>'原创','4'=>'推荐'),
            'vpConfig' => array('1'=>'VIP专享','2'=>'VIP免费','3'=>'免费')
        );

        //资讯筛选条件
        $this->filterConfig['news'] = array(
            'fieldConfig' => array(
                'c'=>array('type'=>'cat_ids','flag'=>'like','field'=>'cat_ids'),
                'sp'=>array('type'=>'boollist','flag'=>'=','field'=>array('is_new','is_hot','is_recommend')),
            ),
            'sortConfig' => array(
                '1'=>array('value'=>1, 'order'=>'create_time desc','title'=>'最新发布','tips'=>'点击按发布时间排序'),
                '2'=>array('value'=>2, 'order'=>'digs desc','title'=>'点赞优先','tips'=>'点击按点赞量排序'),
                '3'=>array('value'=>3, 'order'=>'views desc','title'=>'浏览优先','tips'=>'点击按浏览量排序'),
                '4'=>array('value'=>4, 'order'=>'favors desc','title'=>'收藏优先','tips'=>'点击按收藏量排序'),
            ),
            'spConfig' => array('1'=>'最新','2'=>'最热','3'=>'推荐'),
        );
    }


    //搜索逻辑处理
    public function doSearch($kw,$model_id,$higherconfig=null)
    {
        if(!empty($higherconfig))$mapp = true;
        require(BASE_PATH.'common'.DIRECTORY_SEPARATOR.'components'.DIRECTORY_SEPARATOR.'sphinxapi.php');
        $higherconfig = $higherconfig?$higherconfig:Yii::$app->controller->module->higherconfig;

        //每页显示数量
        $pageSize = 10;
        //记录搜索热点
        $kwModel = SearchRecord::find()->where("keyword='".$kw."' and content_model_id=$model_id")->one();
        if(!empty($kwModel))
        {
            $kwModel->times++;
            $kwModel->save();
        }
        else
        {
            $kwModel = new SearchRecord();
            $kwModel->content_model_id = $model_id;
            $kwModel->keyword = $kw;
            $kwModel->times = 1;
            $kwModel->create_time = TIMESTAMP;
            $kwModel->save();
        }
        //获取排序配置
        $searchModelList = getSysconfigValue('search_models_flag');
        $contentFilterConfig = $this->filterConfig[$searchModelList[$model_id]];
        //筛选条件解析
        $multiSearch = MultiSearchUrl::getSelfInstance(array('fieldConfig'=> $contentFilterConfig['fieldConfig'],'sortConfig'=>$contentFilterConfig['sortConfig']));
        $searchConditions = $multiSearch->getSearchConditions();
        //序列化多维度筛选
        $sqlInfo  = $multiSearch->sqllizeConditions();
        $st = $multiSearch->getConditionValueByType($searchConditions,'st');
        //没有排序条件,默认按最新上传时间
        if(empty($sqlInfo['order']))$sqlInfo['order']="order by create_time desc";
        $page = Yii::$app->request->get('page',1);
        if($higherconfig['open_sphinx'])
        {
            $cl = new \SphinxClient ();
            $q = $kw;
            $host = "localhost";
            $port = 9312;
            //此处变量名称与内容模型主表名一一对应
            $index = $higherconfig[$searchModelList[$model_id].'_index'];
            $cl->SetServer ( $host, $port );
            $connect = $cl->_Connect();
            if(!$connect)
            {
                $this->showMessage(array('class'=>'danger','message'=>'sphinx连接失败'),1);
            }
            $cl->SetConnectTimeout ( 1 );
            $cl->SetArrayResult ( true );
            $cl->SetMatchMode(SPH_MATCH_ALL);
            $cl->SetLimits(($page-1)*$pageSize,$pageSize);
            $cl->SetFieldWeights(array('title'=>10,'tags'=>5,'keywords'=>5,'description'=>3));
            if(!empty($st))
            {
                $cl->SetSortMode(SPH_SORT_EXTENDED, str_replace("order by ","",$sqlInfo['order']));
            }
            else
            {
                $cl->SetSortMode(SPH_SORT_EXTENDED, "@weight DESC,@id DESC");//按照相关度排序
            }
            $res = $cl->Query ( $q, $index );
            $count = $res['total_found'];
            $resultList = [];
            //定义关键字标注内容
            $opts = array('before_match'=>'<span style="color:red">','after_match'=>'</span>');
            if(is_array($res['matches']))foreach($res['matches'] as $k=>$match)
            {
                // "mysql" 我的索引名   “你好”要标红的关键字;
                $go = $cl->BuildExcerpts(array($match['attrs']['title']),$index,$kw,$opts);
                $res['matches'][$k]['attrs']['title'] = $go[0];
                $resultList[$k] =  $res['matches'][$k]['attrs'];
                $resultList[$k]['id'] = $match['id'];
                $resultList[$k]['description'] = str_replace($kw,"<span style='color:red;'>$kw</span>",$resultList[$k]['description']);
            }

            $pages = new Pagination([
                'totalCount' => $count,
                'pageSize'   => $pageSize,
                'defaultPageSize' => $pageSize, //添加默认
            ]);
        }
        else
        {
            $contentModel = ContentModel::findOne($model_id);
            $contentModelFieldList = ContentModelField::find()->where("model_id=$model_id")->all();
            if($contentModel->table_name=='doc')
            {
                $tableName = Yii::$app->db->tablePrefix.$contentModel->table_name.'_real';

            }
            else
            {
                $tableName = Yii::$app->db->tablePrefix.$contentModel->table_name;
            }
            //增加标记判断
            if(is_array($contentModelFieldList))foreach($contentModelFieldList as $contentModelField)
            {
                if(in_array($contentModelField->field,['is_delete','is_del','disabled']))
                {
                    $sqlother[] = " and ".$contentModelField->field.'=0';
                }
            }

            if(!empty($sqlother))$sqlother = join(" ",$sqlother);

            $query = new \yii\db\Query();
            $query->from($tableName);
            $sql = "(title like '%".$kw."%' or keywords like '%".$kw."%' or description like '%".$kw."%') and status=1 ".$sqlother;
            $query->where($sql);
            $query->orderBy(str_replace('order by ','',$sqlInfo['order']));
            $countQuery = clone $query;
            $count = $countQuery->count();
            $pages = new Pagination([
                'totalCount' => $count,
                'pageSize'   => $pageSize,
                'defaultPageSize' => $pageSize, //添加默认
            ]);
            //获取当前页内容
            $resultList =  $query->offset($pages->offset)->limit($pages->limit)->all();
            if(is_array($resultList))foreach($resultList as $k=>$result)
            {
                $resultList[$k]['title'] = str_replace($kw,"<span style='color:red;'>$kw</span>",$resultList[$k]['title']);
                $resultList[$k]['description'] = str_replace($kw,"<span style='color:red;'>$kw</span>",$resultList[$k]['description']);
            }
        }

        if(!$mapp)
        {
            $badwords = getSearchBadWords();
            $hournow = get_date(TIMESTAMP,'H');
            $filter = true;
            if(Yii::$app->controller->module->badwordconfig['hours'])
            {
                $hours = explode(",",Yii::$app->controller->module->badwordconfig['hours']);
                if(!in_array($hournow,$hours))
                {
                    $filter = false;
                }

            }
            if($filter)
            {
                //设定过滤条件(爬虫过滤)
                if(isSpider()&&Yii::$app->controller->module->badwordconfig['open_spider'])
                {
                    if(is_array($badwords))foreach($badwords as $badword)
                    {
                        if(strpos($kw,$badword)!==false)
                        {
                            return ['resultList'=>[],'searchConditions'=>$searchConditions,'st'=>[],'count'=>0,'pages'=>[],'pageCount'=>0,'contentFilterConfig'=>[],'currentPage'=>0,'pageSize'=>0];
                        }
                    }
                }

                //设定过滤条件(手机站)
                if(!isSpider()&&defined('IN_WAP')&&IN_WAP==TRUE&&Yii::$app->controller->module->badwordconfig['open_wap'])
                {
                    if(is_array($badwords))foreach($badwords as $badword)
                    {
                        if(strpos($kw,$badword)!==false)
                        {
                            return ['resultList'=>[],'searchConditions'=>$searchConditions,'st'=>[],'count'=>0,'pages'=>[],'pageCount'=>0,'contentFilterConfig'=>[],'currentPage'=>0,'pageSize'=>0];
                        }
                    }
                }

                //设定过滤条件(PC站)
                if(!isSpider()&&defined('REQUEST_FROM')&&REQUEST_FROM==1&&Yii::$app->controller->module->badwordconfig['open_pc'])
                {
                    if(is_array($badwords))foreach($badwords as $badword)
                    {
                        if(strpos($kw,$badword)!==false)
                        {
                            return ['resultList'=>[],'searchConditions'=>$searchConditions,'st'=>[],'count'=>0,'pages'=>[],'pageCount'=>0,'contentFilterConfig'=>[],'currentPage'=>0,'pageSize'=>0];
                        }
                    }
                }
            }
        }

        return ['resultList'=>$resultList,'searchConditions'=>$searchConditions,'st'=>$st,'count'=>$count,'pages'=>$pages,'pageCount'=>ceil($count/$pageSize),'contentFilterConfig'=>$contentFilterConfig,'currentPage'=>$page,'pageSize'=>$pageSize];
    }

    //列表页Sphinx查询
    public function doList($query,$sql,$sqlInfo,$table,$pageSize,$higherconfig=null)
    {
        require(BASE_PATH.'common'.DIRECTORY_SEPARATOR.'components'.DIRECTORY_SEPARATOR.'sphinxapi.php');
        $page = Yii::$app->request->get('page',1);
        $higherconfig = $higherconfig?$higherconfig:Yii::$app->controller->module->higherconfig;
        if($higherconfig['open_sphinx'])
        {
            $contentModel = ContentModel::find()->where("table_name='".$table."'")->one();
            $cl = new \SphinxClient ();
            $host = "localhost";
            $port = 9312;
            //此处变量名称与内容模型主表名一一对应
            $searchModelList = getSysconfigValue('search_models_flag');
            $index = $higherconfig[$searchModelList[$contentModel->model_id].'_index'];
            $cl->SetServer ( $host, $port );
            $connect = $cl->_Connect();
            if(!$connect)
            {
                $this->showMessage(array('class'=>'danger','message'=>'sphinx连接失败'),1);
            }

            $cl->SetConnectTimeout ( 1 );
            $cl->SetArrayResult ( true );
            $cl->SetMatchMode(SPH_MATCH_EXTENDED2);
            $cl->SetLimits(($page-1)*$pageSize,$pageSize);
            if(empty($sqlInfo['order']))$sqlInfo['order']="order by create_time desc";
            $cl->SetSortMode(SPH_SORT_EXTENDED, str_replace("order by ","",$sqlInfo['order']));
            $fieldList = ContentModelField::find()->where("model_id=".$contentModel->model_id)->all();
            if(is_array($fieldList))foreach($fieldList as $field)
            {
                $sql = str_replace($field->field,'@'.$field->field,$sql);

            }

            $sql = str_replace('and','&',$sql);
            $sql = str_replace('or','|',$sql);
            $sql = str_replace('%','',$sql);
            $sql = str_replace('like','',$sql);
            $res = $cl -> query($sql,$index);
            $count = $res['total_found'];
           /* echo $sql;

            echo "Query failed: " . $cl->GetLastError() . ".\n";
            echo json_encode($res);*/

            $resultList = [];
            //定义关键字标注内容
            if(is_array($res['matches']))foreach($res['matches'] as $k=>$match)
            {
                $resultList[$k] =  $res['matches'][$k]['attrs'];
                $resultList[$k]['id'] = $match['id'];
            }

            $pages = new Pagination([
                'totalCount' => $count,
                'pageSize'   => $pageSize,
                'defaultPageSize' => $pageSize, //添加默认
            ]);
            $return = [
                'count'=>$count,
                'pages'=>$pages,
                'pageSize'=>$pageSize,
                'resultList'=>$resultList,
            ];
        }
        else
        {
            $query->where($sql);
            //没有排序条件,默认按最新上传时间
            if(empty($sqlInfo['order']))$sqlInfo['order']="order by create_time desc";
            $query->orderBy(str_replace('order by ','',$sqlInfo['order']));
            //分页
            $countQuery = clone $query;
            $pages = new Pagination([
                'totalCount' => $countQuery->count(),
                'pageSize'   => $pageSize,
                'defaultPageSize' => $pageSize //添加默认
            ]);
            $resultList =  $query->offset($pages->offset)->limit($pages->limit)->all();
            $return = [
                'count'=>$countQuery->count(),
                'pages'=>$pages,
                'pageSize'=>$pageSize,
                'resultList'=>$resultList,
            ];
        }

        return $return;
    }



}