<?php
declare (strict_types = 1);

namespace app\admin\controller\v1;

use app\admin\model\v1\ProductModel;
use app\admin\validate\v1\ProductValidate;

/**
 * 产品回收站管理控制器
 */
class ProductTrash
{
    // 产品回回站分页列表
    public function index()
    {
        $param = request()->param([
            'name',
            'spu',
            'category_id',
            'page/d' => 1,
            'size/d' => 10
        ]);

        $validate = new ProductValidate();
        if (!$validate->scene('trash')->check($param)) {
            return error($validate->getError());
        }

        $products = ProductModel::field([
                'id',
                'name',
                'cover_image',
                'spu',
                'category_id',
                'sort',
                'is_new',
                'is_sale',
                'stock_qty',
                'status',
                'created_at',
                'deleted_at'
            ])
            ->with(['category'])
            ->language(request()->lang_id)
            ->withSearch(['name_nullable', 'spu_nullable'], [
                'name_nullable'       => $param['name']??null,
                'spu_nullable'        => $param['spu']??null,
            ])
            ->categoryNullable($param['category_id']??null)
            ->onlyTrashed()
            ->order(['sort' => 'asc', 'id' => 'desc'])
            ->paginate([
                'list_rows' => $param['size'],
                'page'      => $param['page'],
            ])
            ->bindAttr('category', ['category_name' => 'name'])
            ->hidden(['category_id', 'category'])
            ?->each(fn($item) => $item->cover_image = thumb($item->cover_image));

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

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

        $product = ProductModel::onlyTrashed()->bypk($id)->find();
        if (is_null($product)) {
            return error('请确认操作对象');
        }

        if (!$product->restore()) {
            return error('操作失败');
        }

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

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

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

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