<?php

namespace app\admin\controller\mall;

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

/**
 * 用户资产（后台列表）
 */
class UserAsset extends Backend
{
    /**
     * @var object|null
     * @phpstan-var \app\common\model\MallUserAsset|null
     */
    protected ?object $model = null;

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

    protected string|array $quickSearchField = [
        'playx_user_id',
        'username',
        'phone',
    ];

    protected string|array $indexField = [
        'id',
        'playx_user_id',
        'username',
        'phone',
        'locked_points',
        'available_points',
        'today_limit',
        'today_claimed',
        'today_limit_date',
        'create_time',
        'update_time',
    ];

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

    /**
     * 远程下拉：资产主键 id + 用户名（用于地址/订单等关联）
     */
    public function select(Request $request): Response
    {
        $response = $this->initializeBackend($request);
        if ($response !== null) {
            return $response;
        }

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

        $list = [];
        foreach ($res->items() as $row) {
            $arr = $row->toArray();
            $list[] = [
                'id'       => $arr['id'] ?? 0,
                'username' => $arr['username'] ?? '',
            ];
        }

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

