<?php

namespace app\controller\api;

use app\extra\basic\Base;
use app\extra\service\blue\ArticleService;
use app\extra\service\blue\CategoryService;
use app\middleware\WxMiddleware;
use app\model\blue\BlueArticle;
use app\model\blue\BlueCategory;
use DI\Attribute\Inject;
use LinFly\Annotation\Route\Controller;
use LinFly\Annotation\Route\Middleware;
use LinFly\Annotation\Route\Route;
use support\Request;
use support\Response;
use think\facade\Db;


#[Controller(prefix: "/wx_api/school"),Middleware(WxMiddleware::class)]
class School extends Base
{

    protected array $noNeedLogin = ['getPortalData','getArticleDetail','getCategoryData'];

    #[Inject]
    protected CategoryService $service;

    #[Inject]
    protected BlueArticle $article;

    #[Inject]
    protected BlueCategory $category;

    #[Inject]
    protected ArticleService $articleService;

    /**
     * 商学院首页
     * @param Request $request
     * @return Response
     */
    #[Route(path: "portal",methods: "get")]
    public function getPortalData(Request $request): Response
    {
        try {
            $data = $this->service->getPortalData($request->all());
            return successTrans("success.data",$data);
        } catch (\Throwable $throwable) {
            return error($throwable->getMessage());
        }
    }


    #[Route(path: "category",methods: "get")]
    public function getCategoryData(Request $request): Response
    {
        try {
            $param = $this->_valid([
                "id.require"    => trans("empty.require"),
                "page.default"  => 1,
                "size.default"  => 10
            ],$request->method());
            if (!is_array($param)) return error($param);
            $category = $this->category->where("id",$param['id'])->findOrEmpty();
            if ($category->isEmpty()) return errorTrans("empty.data");
            $list = $this->articleService->getSchoolList(["category" => $param['id'],'pageSize' => $param['size'],'page' => $param['page']]);
            return successTrans("success.data",pageFormat($list));
        } catch (\Throwable $throwable) {
            return error($throwable->getMessage());
        }
    }

    /**
     * 文章详情
     * @param Request $request
     * @return Response
     */
    #[Route(path: "detail",methods: "get")]
    public function getArticleDetail(Request $request): Response
    {
        try {
            $param = $this->_valid([
                "id.require"    => trans("empty.require")
            ],$request->method());
            if (!is_array($param)) return error($param);
            $data = $this->article->where("id",$param['id'])->findOrEmpty();
            if ($data->isEmpty()) return errorTrans("empty.data");
            $data->inc("view")->save();
            return successTrans("success.data",$data->toArray());
        } catch (\Throwable $throwable) {
            return error($throwable->getMessage());
        }
    }

}