<?php

namespace App\Rpc\v1;

use App\Model\AppNews;
use App\Rpc\BaseService;
use Hyperf\RpcServer\Annotation\RpcService;

#[RpcService(name: "news", server: "jsonrpc-http", protocol: "jsonrpc-http")]
class NewsService extends BaseService
{
    /**
     * 查看单个新闻详情
     * @url /news/view
     * @param $id
     * @return array
     */
    public function view($id): array
    {
        $query = AppNews::query()->where('id', $id)->where('is_delete', 0)->first()?->toArray();

        if (!$query) {
            return $this->getResponse()->setCode(404)->send();
        }
        // 相关文章
        $query['about'] = AppNews::formatQuery(['created_at'])
            ->where('is_delete', 0)
            ->select(['title', 'id'])
            ->limit(10)
            ->orderBy('id', 'desc')
            ->get()
            ->toArray();

        // 上一篇文章
        $query['prevNews'] = AppNews::query()->where('id', '<', $id)->select(['title', 'id'])->where('is_delete', 0)->orderBy('id', 'desc')->first();
        // 下一篇文章
        $query['nextNews'] = AppNews::query()->where('id', '>', $id)->select(['title', 'id'])->where('is_delete', 0)->first();

        return $this->getResponse()->setData($query)->setCode(0)->send();
    }

    /**
     * 查看所有新闻
     * @url /news/index
     * @param int $limit
     * @param int $page
     * @return array
     */
    public function index(int $limit = 30, int $page = 1): array
    {
        $query =  AppNews::formatQuery(['created_at'])
            ->where('is_delete', 0)
            ->select(['id'])
            ->orderBy('id', 'desc');;
        $pagination = $query->paginate($limit, page: $page);
        $ids = [];
        foreach ($pagination->items() as $item) {
            $ids[] = $item->id;
        }

        $value = AppNews::query()->whereIn('id', $ids)->orderBy('id', 'desc')->get()->toArray();

        return $this->getResponse()->setData($value)->setCode(0)->send();
    }
}