<?php

namespace app\admin\controller\admin;

use app\common\controller\Backend;
use support\think\Db;
use support\Response;
use Webman\Http\Request as WebmanRequest;

/**
 * 管理员钱包（只读）
 */
class AdminWallet extends Backend
{
    protected ?object $model = null;

    protected bool $modelValidate = false;

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

    protected string|array $defaultSortField = ['id' => 'desc'];

    protected string|array $orderGuarantee = ['id' => 'desc'];

    protected array $withJoinTable = ['admin'];

    protected function initController(WebmanRequest $request): ?Response
    {
        $this->model = new \app\common\model\AdminWallet();
        return null;
    }

    protected function _index(): Response
    {
        if ($this->request && $this->request->get('select')) {
            return $this->select($this->request);
        }
        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $table = strtolower($this->model->getTable());
        $mainShort = $alias[$table] ?? '';
        if ($mainShort !== '' && $this->auth && !$this->auth->isSuperAdmin()) {
            // 非超管仅可查看自己钱包
            $where[] = [$mainShort . '.admin_id', '=', intval($this->auth->id ?? 0)];
        }
        $res = $this->model
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->with($this->withJoinTable)
            ->visible([
                'admin' => ['username', 'channel_id'],
            ])
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->paginate($limit);
        $items = $res->items();
        $channelIds = [];
        foreach ($items as $item) {
            $channelId = intval($item['admin']['channel_id'] ?? 0);
            if ($channelId > 0) {
                $channelIds[] = $channelId;
            }
        }
        $channelNames = [];
        if ($channelIds !== []) {
            $channelNames = Db::name('channel')
                ->whereIn('id', array_values(array_unique($channelIds)))
                ->column('name', 'id');
        }
        foreach ($items as &$item) {
            $channelId = intval($item['admin']['channel_id'] ?? 0);
            $item['channel_name'] = $channelId > 0 ? strval($channelNames[$channelId] ?? '') : '';
        }
        unset($item);

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

    protected function _add(): Response
    {
        return $this->error(__('Admin wallet does not allow manual creation'));
    }

    protected function _edit(): Response
    {
        return $this->error(__('Admin wallet does not allow manual editing'));
    }

    protected function _del(): Response
    {
        return $this->error(__('Admin wallet does not allow deletion'));
    }
}

