<?php

namespace app\admin\controller\mall;

use app\common\controller\Backend;
use support\Response;
use Webman\Http\Request;

/**
 * 商品管理
 */
class Item extends Backend
{
    /**
     * MallItem模型对象
     * @var object|null
     * @phpstan-var \app\common\model\MallItem|null
     */
    protected ?object $model = null;

    protected array|string $preExcludeFields = ['id', 'create_time', 'update_time'];

    protected array $withJoinTable = ['admin'];

    protected string|array $quickSearchField = ['id', 'title'];

    /** 添加时自动填充 admin_id */
    protected bool $autoFillAdminId = true;

    public function initialize(): void
    {
        parent::initialize();
        $this->model = new \app\common\model\MallItem();
    }

    /**
     * 查看
     */
    public function index(Request $request): Response
    {
        $response = $this->initializeBackend($request);
        if ($response !== null) {
            return $response;
        }

        if ($request->get('select') || $request->post('select')) {
            return $this->select($request);
        }

        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->visible(['admin' => ['username']])
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->paginate($limit);

        return $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }

    /**
     * 远程下拉选择数据（供 remoteSelect 使用）
     */
    public function select(Request $request): Response
    {
        $response = $this->initializeBackend($request);
        if ($response !== null) {
            return $response;
        }

        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->field('id,title')
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->paginate($limit);

        return $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }
}