<?php
// +----------------------------------------------------------------------
// | onezan-admin 快速开发的管理平台
// +----------------------------------------------------------------------
// | 官方网址：https://www.onezan.cn
// +----------------------------------------------------------------------
// | onezan团队 版权所有 开源版本可自由商用
// +----------------------------------------------------------------------
// | Author: 543885307@qq.com
// +----------------------------------------------------------------------
namespace Applications\sample\modules\article\service\api;

use app\service\api\BaseApiService;
use app\service\RequestHelper;
use Applications\sample\modules\article\repository\ArticleRepository;
use Applications\sample\modules\order\repository\OrderRepository;
use think\Request;

/**
 * Article Service
 * @package Applications\sample\modules\article\service\api
 */
class ArticleService extends BaseApiService
{
    /**
     * C端列表
     */
    public function list(Request $request): array
    {
        $page = $this->repository()->paginateForApi([
            'keyword' => $request->get('keyword', ''),
            'category_id' => $request->get('category_id', ''),
        ], RequestHelper::parseLimit($request, 'limit', 10, 100));

        return ['code' => 0, 'data' => $page];
    }

    /**
     * C端详情（含付费拦截）
     */
    public function detail(int $id, int $uid): array
    {
        $article = $this->repository()->findById($id);
        if (!$article || (int)$article->status !== 1) {
            return ['code' => 1, 'msg' => '文章不存在'];
        }

        $data = $article->toArray();

        // 判断是否已付费
        $isPaid = false;
        if ($uid > 0 && (float)$data['price'] > 0) {
            $orderRepo = $this->app->make(OrderRepository::class);
            $isPaid = $orderRepo->hasPaid($uid, $id);
        }

        // 免费文章或已付费 → 全文；否则 → 摘要前200字
        $data['is_unlocked'] = (float)$data['price'] <= 0 || $isPaid;
        if (!$data['is_unlocked']) {
            $data['content'] = mb_substr($data['content'], 0, 200) . '...';
        }

        return ['code' => 0, 'data' => $data];
    }

    private function repository(): ArticleRepository
    {
        return $this->app->make(ArticleRepository::class);
    }
}
