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

use app\service\admin\BaseAdminService;
use app\service\RequestHelper;
use Applications\sample\modules\category\core\CoreCategoryService;
use Applications\sample\modules\category\repository\CategoryRepository;
use think\Request;

/**
 * Category Service
 * @package Applications\sample\modules\category\service\admin
 */
class CategoryService extends BaseAdminService
{
    /**
     * 后台分类列表
     * @param Request $request
     * @return array
     */
    public function list(Request $request): array
    {
        $page = $this->repo()->paginateForAdmin([
            'keyword' => $request->get('keyword', ''),
            'status' => $request->get('status', ''),
        ], RequestHelper::parseLimit($request, 'limit', 10, 100));
        return ['code' => 0, 'data' => $page];
    }


    /**
     * 获取所有启用状态的分类
     * @return array
     */
    public function all(): array
    {
        return ['code' => 0, 'data' => $this->repo()->allEnabled()];
    }


    /**
     * 分类详情
     * @param int $id 分类ID
     * @return array
     */
    public function detail(int $id): array
    {
        $cat = $this->repo()->findById($id);
        return $cat ? ['code' => 0, 'data' => $cat->toArray()] : ['code' => 1, 'msg' => '分类不存在'];
    }


    /**
     * 保存分类
     * @param Request $request
     * @return array
     */
    public function save(Request $request): array
    {
        $id = (int)$request->post('id', 0);
        $payload = [
            'id' => $id,
            'name' => $request->post('name', ''),
            'sort' => $request->post('sort', 0),
            'status' => $request->post('status', 1),
        ];
        return $id > 0 ? $this->core()->update($id, $payload) : $this->core()->create($payload);
    }


    /**
     * 删除分类
     * @param Request $request
     * @return array
     */
    public function delete(Request $request): array
    {
        return $this->core()->delete((int)$request->post('id', 0));
    }

    /**
     * 获取核心分类服务实例
     * @return CoreCategoryService
     */
    private function core(): CoreCategoryService
    {
        return $this->app->make(CoreCategoryService::class);
    }

    /**
     * 获取分类仓库实例
     * @return CategoryRepository
     */
    private function repo(): CategoryRepository
    {
        return $this->app->make(CategoryRepository::class);
    }
}
