<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2019 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 老猫 <thinkcmf@126.com>
// +----------------------------------------------------------------------
namespace app\portal\controller;

use app\portal\model\PortalPostModel;
use cmf\controller\HomeBaseController;
use app\portal\model\PortalCategoryModel;

class ListController extends HomeBaseController
{
    /***
     * 文章列表
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $this->getTopNav();

        //获取分类
        $id                  = $this->request->param('category_id', 0, 'intval');
        $portalCategoryModel = new PortalCategoryModel();
        $category            = $portalCategoryModel->where(function ($query) use ($id) {
            $query->where('id', $id)->whereOr('parent_id', $id);
        })->where('status', 1)->select();
        $category_self       = [
            'id' => 0,
            'name' => '文章列表',
        ];
        $category_child      = [];
        foreach ($category as $v) {
            if ($v['id'] == $id) {
                $category_self = $v;
            } else {
                $category_child[] = $v;
            }
        }
        $this->assign('category_self', $category_self);
        $this->assign('category_child', $category_child);

        //导航
        $path_list = [];
        if (!empty($id)) {
            $path = explode('-', $category_self['path']);
            array_shift($path);
            $path_list = $portalCategoryModel->where('id', 'in', $path)->select();
        }
        $this->assign('path_list', $path_list);

        //文章列表
        $keyword   = $this->request->param('keyword', '');
        $condition = [];
        if (!empty($keyword)) {
            $condition[] = ['post_title', 'like', "%{$keyword}%"];
        }
        $portalModel = new PortalPostModel();
        $list        = $portalModel->getListByCategory($id, 10, $condition);
        foreach ($list as $v) {
            $v['post_content'] = strip_tags($v['post_content']);
            $v['update_time'] = date('Y-m-d H:i:s',$v['update_time']);
        }
        $this->assign('keyword',$keyword);
        $this->assign('list', $list);
        $this->assign('page', $list->render());

        $listTpl = empty($category_self['list_tpl']) ? 'list' : $category_self['list_tpl'];
        return $this->fetch('/' . $listTpl);
    }

}
