<?php

namespace App\Controller\api\v1;

use App\Controller\AbstractController;
use App\FormModel\api\v1\ArticlesModel;
use App\Helpers\AppHelper;
use App\Model\AppArticle;
use App\Model\AppBrand;
use Hyperf\Collection\Collection;
use Hyperf\HttpServer\Annotation\AutoController;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\RequestMapping;

#[Controller]
class ArticlesController extends AbstractController
{
    /**
     * 文章列表
     * @url /api/v1/articles
     * @return array
     */
    #[RequestMapping(path:'', methods: 'get')]
    public function index(): array
    {
        $request = $this->request;
        $query = Model::query()->orderBy('id');
        $pagination = $query->paginate($request->input('limit', 10), page: $request->input('page'));
        $data = $query->get()->toArray();
//        $data['cover'] = AppHelper::setImageUrl($query['cover']);

        foreach ($data as &$v) {
            $v['cover'] = AppHelper::setImageUrl($v['cover']);
        }
        return ['code' => 0, 'msg' => 'ok', 'count' => $pagination->total(), 'data' => $data];
    }

    /**
     * 新增/编辑文章
     * @url /api/v1/articles/save
     * @return array
     */
    #[RequestMapping(path:'save', methods: 'post')]
    public function save(): array
    {
        $id = $this->request->input('id');
        $model = new ArticlesModel();
        if ($id) {
            $model->edit();
        } else {
            $model->create();
        }

        return [
            'code' => 0,
            'message' => 'ok'
        ];
    }
}