<?php
declare (strict_types = 1);

namespace app\admin\controller\v1;

use app\admin\model\v1\VideoModel;

/**
 * 视频回收站控制器
 */
class VideoTrash
{
    /**
     * 分页数据
     */
    public function index()
    {
        $params = request()->param([
            'name',
            'category_id',
            'page/d' => 1,
            'size/d' => 10,
        ]);

        $videos = VideoModel::field([
                'id',
                'category_id',
                'name',
                'image',
                'video',
                'sort',
                'recommend',
                'created_at',
            ])
            ->with(['category' => function($query) {
                $query->field(['id', 'name' => 'category_name']);
            }])
            ->withSearch(['name'], [
                'name' => $params['name']??null
            ])
            ->language(request()->lang_id)
            ->categoryId($params['category_id']??null)
            ->onlyTrashed()
            ->order(['sort' => 'asc', 'id' => 'desc'])
            ->paginate([
                'list_rows' => $params['size'],
                'page'      => $params['page'],
            ])
            ->bindAttr('category', ['category_name'])
            ->hidden(['category_id', 'category'])
            ?->each(fn($item) => $item->image = thumb($item->image));

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

    /**
     * 恢复操作
     */
    public function restore()
    {
        $id = request()->param('id');

        $video = VideoModel::onlyTrashed()->bypk($id)->find();
        if (empty($video)) {
            return error('请确认操作对象是否存在');
        }

        if (!$video->restore()) {
            return error('操作失败');
        }
        return success('操作成功');
    }

    /**
     * 删除操作
     */
    public function delete()
    {
        $id = request()->param('id');

        $video = VideoModel::onlyTrashed()->bypk($id)->find();
        if (empty($video)) {
            return error('请确认操作对象是否存在');
        }

        if (!$video->force()->delete()) {
            return error('操作失败');
        }
        return success('操作成功');
    }
}
