import { Controller, Get, Post, Body, Param, Query, Logger } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiResponse, ApiParam, ApiQuery } from '@nestjs/swagger';
import { WalletApplicationService, FiatWithdrawalApplicationService } from '@/application/services';
import { GetMyWalletQuery } from '@/application/queries';
import {
  DeductForPlantingCommand,
  AllocateFundsCommand,
  FundAllocationItem,
  FreezeForPlantingCommand,
  ConfirmPlantingDeductionCommand,
  UnfreezeForPlantingCommand,
} from '@/application/commands';
import { Public } from '@/shared/decorators';
import { FiatWithdrawalStatus } from '@/domain/value-objects/fiat-withdrawal-status.enum';
import { LedgerEntryType } from '@/domain/value-objects';

/**
 * 内部API控制器 - 供其他微服务调用
 * 不需要JWT认证，通过内部网络访问
 */
@ApiTags('Internal Wallet API')
@Controller('wallets')
export class InternalWalletController {
  private readonly logger = new Logger(InternalWalletController.name);

  constructor(
    private readonly walletService: WalletApplicationService,
    private readonly fiatWithdrawalService: FiatWithdrawalApplicationService,
  ) {}

  @Get(':userId/balance')
  @Public()
  @ApiOperation({ summary: '获取用户钱包余额(内部API)' })
  @ApiParam({ name: 'userId', description: '用户ID或accountSequence' })
  @ApiResponse({ status: 200, description: '余额信息' })
  async getBalance(@Param('userId') userId: string) {
    // 判断是 accountSequence (以 D 开头) 还是 userId (纯数字)
    const isAccountSequence = userId.startsWith('D');
    // 如果是 accountSequence，userId 参数设为 '0'（会被忽略，通过 accountSequence 查找）
    // 如果是纯 userId，accountSequence 参数设为 userId（会通过 userId 查找）
    const query = new GetMyWalletQuery(
      isAccountSequence ? userId : userId,  // accountSequence
      isAccountSequence ? '0' : userId,     // userId (如果是 accountSequence 则忽略)
    );
    const wallet = await this.walletService.getMyWallet(query);
    return {
      userId,
      available: wallet.balances.usdt.available,
      locked: wallet.balances.usdt.frozen,
      currency: 'USDT',
    };
  }

  @Post('deduct-for-planting')
  @Public()
  @ApiOperation({ summary: '认种扣款(内部API) - 直接扣款模式' })
  @ApiResponse({ status: 200, description: '扣款结果' })
  async deductForPlanting(
    @Body() dto: { userId: string; accountSequence?: string; amount: number; orderId: string },
  ) {
    // 优先使用 accountSequence，如果未提供则使用 userId
    const userIdentifier = dto.accountSequence || dto.userId;
    const command = new DeductForPlantingCommand(
      userIdentifier,
      dto.amount,
      dto.orderId,
    );
    const success = await this.walletService.deductForPlanting(command);
    return { success };
  }

  @Post('freeze-for-planting')
  @Public()
  @ApiOperation({ summary: '认种冻结资金(内部API) - 预扣款模式第一步' })
  @ApiResponse({ status: 200, description: '冻结结果' })
  async freezeForPlanting(
    @Body() dto: { userId: string; accountSequence?: string; amount: number; orderId: string },
  ) {
    this.logger.log(`========== freeze-for-planting 请求 ==========`);
    this.logger.log(`请求参数: ${JSON.stringify(dto)}`);
    this.logger.log(`  userId: ${dto.userId}`);
    this.logger.log(`  accountSequence: ${dto.accountSequence || '未提供'}`);
    this.logger.log(`  amount: ${dto.amount}`);
    this.logger.log(`  orderId: ${dto.orderId}`);

    try {
      // 优先使用 accountSequence，如果未提供则使用 userId
      const userIdentifier = dto.accountSequence || dto.userId;
      this.logger.log(`  使用标识符: ${userIdentifier}`);

      const command = new FreezeForPlantingCommand(
        userIdentifier,
        dto.amount,
        dto.orderId,
      );
      const result = await this.walletService.freezeForPlanting(command);
      this.logger.log(`冻结成功: ${JSON.stringify(result)}`);
      return result;
    } catch (error) {
      this.logger.error(`冻结失败: ${error.message}`);
      this.logger.error(`错误堆栈: ${error.stack}`);
      throw error;
    }
  }

  @Post('confirm-planting-deduction')
  @Public()
  @ApiOperation({ summary: '确认认种扣款(内部API) - 预扣款模式第二步' })
  @ApiResponse({ status: 200, description: '确认结果' })
  async confirmPlantingDeduction(
    @Body() dto: { userId: string; accountSequence?: string; orderId: string },
  ) {
    // 优先使用 accountSequence，如果未提供则使用 userId
    const userIdentifier = dto.accountSequence || dto.userId;
    const command = new ConfirmPlantingDeductionCommand(
      userIdentifier,
      dto.orderId,
    );
    const success = await this.walletService.confirmPlantingDeduction(command);
    return { success };
  }

  @Post('unfreeze-for-planting')
  @Public()
  @ApiOperation({ summary: '解冻认种资金(内部API) - 认种失败时回滚' })
  @ApiResponse({ status: 200, description: '解冻结果' })
  async unfreezeForPlanting(
    @Body() dto: { userId: string; accountSequence?: string; orderId: string },
  ) {
    // 优先使用 accountSequence，如果未提供则使用 userId
    const userIdentifier = dto.accountSequence || dto.userId;
    const command = new UnfreezeForPlantingCommand(
      userIdentifier,
      dto.orderId,
    );
    const success = await this.walletService.unfreezeForPlanting(command);
    return { success };
  }

  /**
   * [2026-03-01] 预种购买后触发待领取→可结算转换（内部API）
   *
   * planting-service 在用户购买预种份额后调用此端点：
   * 1. markUserAsPlanted(accountSequence) — 设置 hasPlanted=true
   * 2. settleUserPendingRewards(accountSequence) — 结算所有 PENDING 奖励
   * 两步均幂等，重复调用安全。
   */
  @Post('settle-after-pre-planting')
  @Public()
  @ApiOperation({ summary: '预种购买后结算待领取奖励(内部API) - 幂等' })
  @ApiResponse({ status: 200, description: '结算结果' })
  async settleAfterPrePlanting(
    @Body() dto: { accountSequence: string },
  ) {
    this.logger.log(`========== settle-after-pre-planting 请求 ==========`);
    this.logger.log(`accountSequence: ${dto.accountSequence}`);

    const result = await this.walletService.settleAfterPrePlanting(dto.accountSequence);

    this.logger.log(`预种结算结果: ${JSON.stringify(result)}`);
    return result;
  }

  @Post('allocate-funds')
  @Public()
  @ApiOperation({ summary: '资金分配(内部API)' })
  @ApiResponse({ status: 200, description: '分配结果' })
  async allocateFunds(
    @Body() dto: { orderId: string; allocations: FundAllocationItem[] },
  ) {
    const command = new AllocateFundsCommand(
      dto.orderId,
      '', // payerUserId will be determined from order
      dto.allocations,
    );
    const result = await this.walletService.allocateFunds(command);
    return { success: result.success };
  }

  @Post('ensure-region-accounts')
  @Public()
  @ApiOperation({ summary: '确保区域账户存在(内部API) - 在选择省市确认后调用' })
  @ApiResponse({ status: 200, description: '区域账户创建结果' })
  async ensureRegionAccounts(
    @Body() dto: { provinceCode: string; provinceName: string; cityCode: string; cityName: string },
  ) {
    this.logger.log(`确保区域账户存在: 省=${dto.provinceName}(${dto.provinceCode}), 市=${dto.cityName}(${dto.cityCode})`);

    const result = await this.walletService.ensureRegionAccounts({
      provinceCode: dto.provinceCode,
      provinceName: dto.provinceName,
      cityCode: dto.cityCode,
      cityName: dto.cityName,
    });

    return result;
  }

  @Post('settle-to-balance')
  @Public()
  @ApiOperation({ summary: '结算到余额(内部API) - 可结算USDT转入钱包余额' })
  @ApiResponse({ status: 200, description: '结算结果' })
  async settleToBalance(
    @Body() dto: {
      accountSequence: string;
      usdtAmount: number;
      rewardEntryIds: string[];
      breakdown?: Record<string, number>;
      memo?: string;
    },
  ) {
    this.logger.log(`========== settle-to-balance 请求 ==========`);
    this.logger.log(`请求参数: ${JSON.stringify(dto)}`);

    const result = await this.walletService.settleToBalance({
      accountSequence: dto.accountSequence,
      usdtAmount: dto.usdtAmount,
      rewardEntryIds: dto.rewardEntryIds,
      breakdown: dto.breakdown,
      memo: dto.memo,
    });

    this.logger.log(`结算结果: ${JSON.stringify(result)}`);
    return result;
  }

  // =============== 法币提现管理 API ===============

  @Get('fiat-withdrawals/pending-review')
  @Public()
  @ApiOperation({ summary: '获取待审核的法币提现订单(内部API)' })
  @ApiResponse({ status: 200, description: '待审核订单列表' })
  async getFiatWithdrawalsPendingReview() {
    return this.fiatWithdrawalService.getPendingReviewOrders();
  }

  @Get('fiat-withdrawals/pending-payment')
  @Public()
  @ApiOperation({ summary: '获取待打款的法币提现订单(内部API)' })
  @ApiResponse({ status: 200, description: '待打款订单列表' })
  async getFiatWithdrawalsPendingPayment() {
    return this.fiatWithdrawalService.getPendingPaymentOrders();
  }

  @Get('fiat-withdrawals/by-status')
  @Public()
  @ApiOperation({ summary: '根据状态获取法币提现订单(内部API)' })
  @ApiQuery({ name: 'status', enum: FiatWithdrawalStatus })
  @ApiResponse({ status: 200, description: '订单列表' })
  async getFiatWithdrawalsByStatus(@Query('status') status: FiatWithdrawalStatus) {
    return this.fiatWithdrawalService.getOrdersByStatus(status);
  }

  @Post('fiat-withdrawals/:orderNo/review')
  @Public()
  @ApiOperation({ summary: '审核法币提现订单(内部API)' })
  @ApiParam({ name: 'orderNo', description: '订单号' })
  @ApiResponse({ status: 200, description: '审核结果' })
  async reviewFiatWithdrawal(
    @Param('orderNo') orderNo: string,
    @Body() dto: { approved: boolean; reviewedBy: string; remark?: string },
  ) {
    return this.fiatWithdrawalService.reviewFiatWithdrawal({
      orderNo,
      approved: dto.approved,
      reviewedBy: dto.reviewedBy,
      remark: dto.remark,
    });
  }

  @Post('fiat-withdrawals/:orderNo/start-payment')
  @Public()
  @ApiOperation({ summary: '开始打款(内部API)' })
  @ApiParam({ name: 'orderNo', description: '订单号' })
  @ApiResponse({ status: 200, description: '操作结果' })
  async startFiatPayment(
    @Param('orderNo') orderNo: string,
    @Body() dto: { paidBy: string },
  ) {
    return this.fiatWithdrawalService.startPayment({
      orderNo,
      paidBy: dto.paidBy,
    });
  }

  @Post('fiat-withdrawals/:orderNo/complete-payment')
  @Public()
  @ApiOperation({ summary: '完成打款(内部API)' })
  @ApiParam({ name: 'orderNo', description: '订单号' })
  @ApiResponse({ status: 200, description: '操作结果' })
  async completeFiatPayment(
    @Param('orderNo') orderNo: string,
    @Body() dto: { paymentProof?: string; remark?: string },
  ) {
    return this.fiatWithdrawalService.completePayment({
      orderNo,
      paymentProof: dto.paymentProof,
      remark: dto.remark,
    });
  }

  // =============== 特殊扣减 API ===============

  @Post('special-deduction/execute')
  @Public()
  @ApiOperation({ summary: '执行特殊扣减(内部API) - 用户确认扣减操作' })
  @ApiResponse({ status: 200, description: '扣减结果' })
  async executeSpecialDeduction(
    @Body() dto: {
      accountSequence: string;
      pendingActionId: string;
      amount: number;
      reason: string;
    },
  ) {
    this.logger.log(`========== special-deduction/execute 请求 ==========`);
    this.logger.log(`请求参数: ${JSON.stringify(dto)}`);

    const result = await this.walletService.executeSpecialDeduction({
      accountSequence: dto.accountSequence,
      amount: dto.amount,
      memo: dto.reason,
      operatorId: `pending-action:${dto.pendingActionId}`,
    });

    this.logger.log(`特殊扣减结果: ${JSON.stringify(result)}`);
    return result;
  }

  // =============== 全额线下结算扣减 API ===============

  @Get('offline-settlement/unprocessed/:accountSequence')
  @Public()
  @ApiOperation({ summary: '查询未处理的结算收益记录(内部API) - 用于全额线下结算扣减' })
  @ApiParam({ name: 'accountSequence', description: '账户序列号' })
  @ApiResponse({ status: 200, description: '未处理的结算记录列表' })
  async getUnprocessedSettlements(@Param('accountSequence') accountSequence: string) {
    this.logger.log(`========== offline-settlement/unprocessed 请求 ==========`);
    this.logger.log(`accountSequence: ${accountSequence}`);

    const result = await this.walletService.getUnprocessedSettlements(accountSequence);

    this.logger.log(`查询结果: ${result.count} 条记录, 总金额: ${result.totalAmount}`);
    return result;
  }

  @Post('offline-settlement/execute')
  @Public()
  @ApiOperation({ summary: '执行全额线下结算扣减(内部API) - 扣减用户所有未处理的结算收益' })
  @ApiResponse({ status: 200, description: '扣减结果' })
  async executeOfflineSettlementDeduction(
    @Body() dto: {
      accountSequence: string;
      pendingActionId?: string;
      operatorId: string;
      customMemo?: string;
    },
  ) {
    this.logger.log(`========== offline-settlement/execute 请求 ==========`);
    this.logger.log(`请求参数: ${JSON.stringify(dto)}`);

    const result = await this.walletService.executeOfflineSettlementDeduction({
      accountSequence: dto.accountSequence,
      pendingActionId: dto.pendingActionId,
      operatorId: dto.operatorId,
      customMemo: dto.customMemo,
    });

    this.logger.log(`全额线下结算扣减结果: ${JSON.stringify(result)}`);
    return result;
  }

  // =============== 系统账户报表统计 API ===============
  // [2026-01-04] 新增：用于 reporting-service 聚合系统账户报表数据
  // 回滚方式：删除以下 API 方法即可

  @Get('statistics/offline-settlement-summary')
  @Public()
  @ApiOperation({ summary: '面对面(线下)结算统计汇总(内部API) - 用于系统账户报表' })
  @ApiQuery({ name: 'startDate', required: false, description: '开始日期 (YYYY-MM-DD)' })
  @ApiQuery({ name: 'endDate', required: false, description: '结束日期 (YYYY-MM-DD)' })
  @ApiResponse({ status: 200, description: '面对面结算统计汇总' })
  async getOfflineSettlementSummary(
    @Query('startDate') startDate?: string,
    @Query('endDate') endDate?: string,
  ) {
    this.logger.log(`========== statistics/offline-settlement-summary 请求 ==========`);
    this.logger.log(`startDate: ${startDate}, endDate: ${endDate}`);

    const result = await this.walletService.getOfflineSettlementSummary({
      startDate: startDate ? new Date(startDate) : undefined,
      endDate: endDate ? new Date(endDate) : undefined,
    });

    this.logger.log(`面对面结算统计结果: totalAmount=${result.totalAmount}, totalCount=${result.totalCount}`);
    return result;
  }

  // [2026-01-07] 新增：面对面结算明细列表 API
  // 回滚方式：删除此方法
  @Get('statistics/offline-settlement-entries')
  @Public()
  @ApiOperation({ summary: '面对面(线下)结算明细列表(内部API) - 用于系统账户报表' })
  @ApiQuery({ name: 'page', required: false, description: '页码，默认1' })
  @ApiQuery({ name: 'pageSize', required: false, description: '每页条数，默认50' })
  @ApiQuery({ name: 'startDate', required: false, description: '开始日期 (YYYY-MM-DD)' })
  @ApiQuery({ name: 'endDate', required: false, description: '结束日期 (YYYY-MM-DD)' })
  @ApiResponse({ status: 200, description: '面对面结算明细列表' })
  async getOfflineSettlementEntries(
    @Query('page') page?: string,
    @Query('pageSize') pageSize?: string,
    @Query('startDate') startDate?: string,
    @Query('endDate') endDate?: string,
  ) {
    this.logger.log(`========== statistics/offline-settlement-entries 请求 ==========`);
    this.logger.log(`page: ${page}, pageSize: ${pageSize}, startDate: ${startDate}, endDate: ${endDate}`);

    const result = await this.walletService.getOfflineSettlementEntries({
      page: page ? parseInt(page, 10) : undefined,
      pageSize: pageSize ? parseInt(pageSize, 10) : undefined,
      startDate: startDate ? new Date(startDate) : undefined,
      endDate: endDate ? new Date(endDate) : undefined,
    });

    this.logger.log(`面对面结算明细结果: total=${result.total}, page=${result.page}, totalPages=${result.totalPages}`);
    return result;
  }

  @Get('statistics/system-accounts-balances')
  @Public()
  @ApiOperation({ summary: '批量查询系统账户余额(内部API) - 用于系统账户报表' })
  @ApiQuery({ name: 'sequences', description: '账户序列号列表，逗号分隔 (如: S0000000001,S0000000002)' })
  @ApiResponse({ status: 200, description: '系统账户余额列表' })
  async getSystemAccountsBalances(
    @Query('sequences') sequences: string,
  ) {
    this.logger.log(`========== statistics/system-accounts-balances 请求 ==========`);
    this.logger.log(`sequences: ${sequences}`);

    const accountSequences = sequences.split(',').map(s => s.trim()).filter(s => s);
    const result = await this.walletService.getSystemAccountsBalances(accountSequences);

    this.logger.log(`系统账户余额查询结果: ${result.length} 个账户`);
    return result;
  }

  @Get('statistics/all-system-accounts')
  @Public()
  @ApiOperation({ summary: '获取所有系统账户列表(内部API) - 用于系统账户报表' })
  @ApiResponse({ status: 200, description: '所有系统账户列表（固定+区域）' })
  async getAllSystemAccounts() {
    this.logger.log(`========== statistics/all-system-accounts 请求 ==========`);
    const result = await this.walletService.getAllSystemAccounts();
    this.logger.log(`系统账户查询结果: 固定=${result.fixedAccounts.length}, 省=${result.provinceAccounts.length}, 市=${result.cityAccounts.length}`);
    return result;
  }

  // [2026-01-05] 新增：单个系统账户分类账查询
  @Get('statistics/system-account-ledger')
  @Public()
  @ApiOperation({ summary: '获取单个系统账户分类账(内部API)' })
  @ApiQuery({ name: 'accountSequence', required: true, description: '账户序列号' })
  @ApiQuery({ name: 'page', required: false, description: '页码，默认1' })
  @ApiQuery({ name: 'pageSize', required: false, description: '每页条数，默认20' })
  @ApiQuery({ name: 'entryType', required: false, description: '流水类型筛选' })
  @ApiQuery({ name: 'startDate', required: false, description: '开始日期' })
  @ApiQuery({ name: 'endDate', required: false, description: '结束日期' })
  @ApiResponse({ status: 200, description: '分类账明细列表' })
  async getSystemAccountLedger(
    @Query('accountSequence') accountSequence: string,
    @Query('page') page?: string,
    @Query('pageSize') pageSize?: string,
    @Query('entryType') entryType?: string,
    @Query('startDate') startDate?: string,
    @Query('endDate') endDate?: string,
  ) {
    this.logger.log(`========== statistics/system-account-ledger 请求 ==========`);
    this.logger.log(`accountSequence=${accountSequence}, page=${page}, pageSize=${pageSize}`);

    const result = await this.walletService.getSystemAccountLedger({
      accountSequence,
      page: page ? parseInt(page, 10) : 1,
      pageSize: pageSize ? parseInt(pageSize, 10) : 20,
      entryType: entryType as LedgerEntryType | undefined,
      startDate: startDate ? new Date(startDate) : undefined,
      endDate: endDate ? new Date(endDate) : undefined,
    });

    this.logger.log(`系统账户分类账查询结果: ${result.total} 条记录`);
    return result;
  }

  // [2026-01-05] 新增：所有系统账户分类账查询
  @Get('statistics/all-system-accounts-ledger')
  @Public()
  @ApiOperation({ summary: '获取所有系统账户的分类账明细(内部API) - 用于系统账户报表' })
  @ApiQuery({ name: 'pageSize', required: false, description: '每个账户显示的条数，默认50' })
  @ApiQuery({ name: 'startDate', required: false, description: '开始日期' })
  @ApiQuery({ name: 'endDate', required: false, description: '结束日期' })
  @ApiResponse({ status: 200, description: '所有系统账户的分类账明细' })
  async getAllSystemAccountsLedger(
    @Query('pageSize') pageSize?: string,
    @Query('startDate') startDate?: string,
    @Query('endDate') endDate?: string,
  ) {
    this.logger.log(`========== statistics/all-system-accounts-ledger 请求 ==========`);

    const result = await this.walletService.getAllSystemAccountsLedger({
      pageSize: pageSize ? parseInt(pageSize, 10) : 50,
      startDate: startDate ? new Date(startDate) : undefined,
      endDate: endDate ? new Date(endDate) : undefined,
    });

    const totalLedgers = result.fixedAccountsLedger.reduce((sum, a) => sum + a.total, 0) +
      result.provinceAccountsLedger.reduce((sum, a) => sum + a.total, 0) +
      result.cityAccountsLedger.reduce((sum, a) => sum + a.total, 0);
    this.logger.log(`所有系统账户分类账查询完成: 固定=${result.fixedAccountsLedger.length}, 省=${result.provinceAccountsLedger.length}, 市=${result.cityAccountsLedger.length}, 总流水=${totalLedgers}`);
    return result;
  }

  // =============== 钱包预创建 API ===============
  // [2026-01-08] 新增：确保用户钱包存在（用于用户注册时或内部转账前）
  // 回滚方式：删除以下 API 方法即可

  @Post('ensure-wallet')
  @Public()
  @ApiOperation({ summary: '确保用户钱包存在(内部API) - 幂等操作' })
  @ApiResponse({ status: 200, description: '钱包信息' })
  async ensureWalletExists(
    @Body() dto: { accountSequence: string; userId: string },
  ) {
    this.logger.log(`========== ensure-wallet 请求 ==========`);
    this.logger.log(`请求参数: ${JSON.stringify(dto)}`);

    const result = await this.walletService.ensureWalletExists({
      accountSequence: dto.accountSequence,
      userId: dto.userId,
    });

    this.logger.log(`确保钱包结果: ${JSON.stringify(result)}`);
    return result;
  }

  @Post('ensure-wallets')
  @Public()
  @ApiOperation({ summary: '批量确保用户钱包存在(内部API) - 幂等操作' })
  @ApiResponse({ status: 200, description: '钱包信息列表' })
  async ensureWalletsExist(
    @Body() dto: { wallets: Array<{ accountSequence: string; userId: string }> },
  ) {
    this.logger.log(`========== ensure-wallets 请求 ==========`);
    this.logger.log(`请求参数: ${dto.wallets.length} 个钱包`);

    const results = await this.walletService.ensureWalletsExist(dto.wallets);

    this.logger.log(`批量确保钱包结果: ${results.length} 个已处理`);
    return { results };
  }

  // [2026-01-06] 新增：手续费归集账户统计 API
  // 用于系统账户报表中的"手续费账户汇总" Tab
  // 回滚方式：删除以下 API 方法即可

  @Get('statistics/fee-collection-summary')
  @Public()
  @ApiOperation({ summary: '获取手续费归集账户汇总统计(内部API) - 用于系统账户报表' })
  @ApiResponse({ status: 200, description: '手续费归集账户汇总统计' })
  async getFeeCollectionSummary() {
    this.logger.log(`========== statistics/fee-collection-summary 请求 ==========`);

    const result = await this.walletService.getFeeCollectionSummary();

    this.logger.log(`手续费归集统计结果: totalAmount=${result.totalAmount}, totalCount=${result.totalCount}, balance=${result.accountBalance}`);
    return result;
  }

  @Get('statistics/fee-collection-entries')
  @Public()
  @ApiOperation({ summary: '获取手续费归集账户流水明细(内部API) - 用于系统账户报表' })
  @ApiQuery({ name: 'page', required: false, description: '页码，默认1' })
  @ApiQuery({ name: 'pageSize', required: false, description: '每页条数，默认50' })
  @ApiQuery({ name: 'feeType', required: false, description: '手续费类型筛选 (WITHDRAWAL_FEE/FIAT_WITHDRAWAL_FEE)' })
  @ApiQuery({ name: 'startDate', required: false, description: '开始日期' })
  @ApiQuery({ name: 'endDate', required: false, description: '结束日期' })
  @ApiResponse({ status: 200, description: '手续费归集流水明细列表' })
  async getFeeCollectionEntries(
    @Query('page') page?: string,
    @Query('pageSize') pageSize?: string,
    @Query('feeType') feeType?: string,
    @Query('startDate') startDate?: string,
    @Query('endDate') endDate?: string,
  ) {
    this.logger.log(`========== statistics/fee-collection-entries 请求 ==========`);
    this.logger.log(`page=${page}, pageSize=${pageSize}, feeType=${feeType}`);

    const result = await this.walletService.getFeeCollectionEntries({
      page: page ? parseInt(page, 10) : 1,
      pageSize: pageSize ? parseInt(pageSize, 10) : 50,
      feeType,
      startDate: startDate ? new Date(startDate) : undefined,
      endDate: endDate ? new Date(endDate) : undefined,
    });

    this.logger.log(`手续费归集流水查询结果: ${result.total} 条记录`);
    return result;
  }
}
