<?php
/**
 * @copyright Copyright (c) 2021 勾股工作室
 * @license https://opensource.org/licenses/GPL-3.0
 * @link https://www.gougucms.com
 */

declare (strict_types = 1);

namespace app\api\controller;

use app\api\ApiController;
use app\api\middleware\Auth;
use app\note\model\Note as NoteList;
use app\note\validate\NoteCheck;
use app\note\validate\NoteCateCheck;
use think\exception\ValidateException;
use think\facade\Db;

class NoteIndex extends ApiController
{
    protected $middleware = [
    	Auth::class => ['except' => []]
    ];

    public function index()
    {
        $this->checkAuth();
        $param = get_params();
        $where = array();
        if (!empty($param['keyword'])) {
            $where[] = ['a.title', 'like', '%' . $param['keyword'] . '%'];
        }
        $where[] = ['a.status', '=', 1];
        $rows = empty($param['limit']) ? get_config('app.page_size') : $param['limit'];
        $note = NoteList::where($where)
            ->field('a.id,a.cate_id,a.title,a.content,a.status,a.create_time,a.start_time,a.end_time,c.title as cate_title')
            ->alias('a')
            ->join('NoteCate c', 'a.cate_id = c.id', 'LEFT')
            ->order('a.end_time desc,a.sort desc,a.create_time desc')
            ->paginate($rows, false, ['query' => $param])
            ->each(function ($item, $key) {
                $item->start_time = empty($item->start_time) ? '-' : date('Y-m-d', $item->start_time);
                $item->end_time = empty($item->end_time) ? '-' : date('Y-m-d', $item->end_time);
            });
        $this->apiSuccess('获取成功', $note);
    }

    public function view()
    {
        $this->checkAuth();
        $id = empty(get_params('id')) ? 0 : get_params('id');
        $note = Db::name('Note')->where(['id' => $id])->find();
        if (empty($note)) {
            $this->apiError('公告不存在');
        }
        $note['cate_title'] = Db::name('NoteCate')->where(['id' => $note['cate_id']])->value('title');
        $note['start_time'] = date('Y-m-d H:i:s', $note['start_time']);
        $note['end_time'] = date('Y-m-d H:i:s', $note['end_time']);
        $note['create_time'] = date('Y-m-d H:i:s', $note['create_time']);
        $note['update_time'] = date('Y-m-d H:i:s', $note['update_time']);
        $this->apiSuccess('获取成功', $note);
    }

}
