<?php
declare (strict_types = 1);

namespace app\admin\controller\v1;

use app\admin\model\v1\ArticleModel;

/**
 * 文章回收站管理控制器
 */
class ArticleTrash
{
    // 文章回收站分页列表
    public function index()
    {
        $param = request()->get([
            'title',
            'category_id',
            'page/d' => 1,
            'size/d' => 10
        ]);
        $data = ArticleModel::field([
                'id',
                'category_id',
                'title',
                'image',
                'sort',
                'recommend',
                'release_time',
            ])
            ->with('category')
            ->language(request()->lang_id)
            ->categoryNullable($param['category_id']??null)
            ->withSearch(['title'], ['title' => $param['title']??null])
            ->onlyTrashed()
            ->order(['sort' => 'desc', 'id' => 'desc'])
            ->paginate([
                'page'      => $param['page'],
                'list_rows' => $param['size']
            ])
            ->hidden(['category_id', 'category'])
            ->bindAttr('category', ['category_name' => 'name'])
            ?->each(fn($item) => $item->image = thumb($item->image));

        return success('获取成功', $data);
    }

    // 恢复
    public function restore()
    {
        $id = request()->param('id');
        if (empty($id)) {
            return error('参数错误');
        }

        $article = ArticleModel::onlyTrashed()->bypk($id)->find();
        if (is_null($article)) {
            return error('请确认操作对象');
        }
        if (!$article->restore()) {
            return error('操作失败');
        }

        return success('操作成功');
    }

    // 删除
    public function delete()
    {
        $id = request()->param('id');
        if (empty($id)) {
            return error('参数错误');
        }

        $article = ArticleModel::onlyTrashed()->bypk($id)->find();
        if (is_null($article)) {
            return error('请确认操作对象');
        }
        if (!$article->force()->delete()) {
            return error('操作失败');
        }

        return success('操作成功');
    }
}
