<?php
/**
 * Copyright: Shanghai NuLang Network Technology Co., Ltd.
 * Faith: Some things do not need others to understand.
 * Project: CoverCMS <Your world, your ambition>
 * License: http://www.svipplus.cn/license/
 * Author: The Rain° <rain@svipplus.cn>
 * File: SearchController.php
 * Time: 14:29
 */

namespace app\app\controller;


use app\common\controller\BaseController;
use think\Db;

class SearchController extends BaseController
{
    public function indexAction()
    {
        $type = [
            'art' => 'article',
            'pro' => 'product',
            'cas' => 'case'
        ];
        $t = 'art';
        $page = 1;
        $perPage = 10;
        if (request()->isPost()) {
            $keyword = trim(input('post.k'));
            $baseUrl = request()->scheme() . '://' . request()->host();
            if (input('?post.t') && isset($type[input('post.t')])) {
                $t = input('post.t');
            }
            if (input('?post.p') && intval(input('post.p')) > 0) {
                $page = intval(input('post.p'));
            }
            $param = [
                'k' => $keyword,
                't' => $t,
                'p' => $page
            ];
            $this->redirect($baseUrl . url('index', $param));
        }

        if (input('?get.t') && isset($type[input('get.t')])) {
            $t = input('get.t');
        }
        $table = $type[$t];
        if (input('?get.p') && intval(input('get.p')) > 0) {
            $page = intval(input('get.p'));
        }
        $result = [];
        if (!input('?get.k') || empty(trim(input('get.k')))) {
            return $this->render('search', [
                'no_k' => '请输入关键词'
            ]);
        }
        $keyword = input('get.k');
        $map['title'] = ['like', '%' . $keyword . '%'];
        $total = Db::name($table)->where($map)->count();
        if ($total > 0) {
            $result = Db::name($table)->where($map)->order('weight desc,create_time desc')->page($page, $perPage)->select();
            if (count($result) > 0) {
                foreach ($result as &$item) {
                    $item['url'] = url('app/default/detail', ['cid' => $item['category_id'], 'aid' => $item['id']]);
                }
            }
        }
        $hasLastPage = false;
        $hasNextPage = false;
        $lastPage = $page - 1;
        if ($lastPage > 0) {
            $hasLastPage = true;
        }
        $nextPage = $page + 1;
        if ($page * $perPage < $total) {
            $hasNextPage = true;
        }
        return $this->render('search', [
            'total' => $total,
            'items' => $result,
            'type' => $t,
            'keyword' => $keyword,
            'has_last_page' => $hasLastPage,
            'has_next_page' => $hasNextPage,
            'last_page' => $lastPage,
            'next_page' => $nextPage
        ]);
    }
}