<?php


namespace app\system\controller;

use app\model\api\ArticleModel;
use think\Request;



class ArticleController
{
    // 获取文章列表
    public function getArticleList(Request $request)
    {
        $page = $request->param('page', 1);
        $pageSize = $request->param('pageSize', 10);
        $title = $request->param('title', '');
        $query = (new ArticleModel())->order('create_time', 'desc');
        if ($title) {
            $query->where('title', 'like', "%$title%");
        }
        $articles = $query->page($page, $pageSize)->select();
        $count = $query->count();
        $data['list'] = $articles;
        $data['count'] = $count;
        return app('json')->success($data);
    }

    //获取文章详情
    public function getArticleDetail(Request $request)
    {
        $id = $request->param('id');
        $article = ArticleModel::where('id', $id)->find();
        if (!$article) {
            return app('json')->fail('文章不存在');
        }
        return app('json')->success(['list' => [$article], 'count' => 1]);
    }

    // 添加文章
    public function addArticle(Request $request)
    {
        $data = $request->param();
        $article = new ArticleModel();
        $article->title = $data['title'];
        $article->content = $data['content'];
        $article->create_time = time();
        $article->save();
        return app('json')->success();
    }

    // 修改文章
    public function updateArticle(Request $request)
    {
        $id = $request->param('id');
        $data = $request->param();
        $article = ArticleModel::where('id', $id)->find();
        if (!$article) {
            return app('json')->fail('文章不存在');
        }
        $article->title = $data['title'];
        $article->content = $data['content'];
        $article->save();
        return app('json')->success();
    }

    // 删除文章
    public function deleteArticle(Request $request)
    {
        $id = $request->param('id');
        $article = ArticleModel::where('id', $id)->find();
        if (!$article) {
            return app('json')->fail('文章不存在');
        }
        $article->delete();
        return app('json')->success();
    }

}