import { Controller, Post, Body, Logger, Get, Query } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiResponse, ApiQuery } from '@nestjs/swagger';
import { IsArray, IsString, IsOptional } from 'class-validator';
import { RewardApplicationService } from '../../application/services/reward-application.service';

/**
 * 批量查询月度收益请求 DTO
 */
class BatchMonthlyEarningsRequest {
  @IsArray()
  @IsString({ each: true })
  accountSequences: string[];

  @IsString()
  month: string; // 格式: YYYY-MM

  @IsOptional()
  @IsArray()
  @IsString({ each: true })
  rightTypes?: string[]; // 可选，过滤权益类型
}

/**
 * 月度收益响应项
 */
interface MonthlyEarningsItem {
  accountSequence: string;
  monthlySettleableUsdt: number;
  monthlyShareUsdt: number; // 分享权益收益
  monthlyProvinceTeamUsdt: number; // 省团队权益收益
  monthlyCityTeamUsdt: number; // 市团队权益收益
  monthlyTotalUsdt: number; // 月度总收益
}

/**
 * 内部 API 控制器
 * 用于服务间通信，不需要 JWT 认证
 */
@ApiTags('Internal')
@Controller('internal')
export class InternalController {
  private readonly logger = new Logger(InternalController.name);

  constructor(private readonly rewardService: RewardApplicationService) {}

  @Post('monthly-earnings/batch')
  @ApiOperation({ summary: '批量查询月度可结算收益（内部接口）' })
  @ApiResponse({ status: 200, description: '成功' })
  async batchGetMonthlyEarnings(
    @Body() request: BatchMonthlyEarningsRequest,
  ): Promise<MonthlyEarningsItem[]> {
    const { accountSequences, month, rightTypes } = request;

    if (!accountSequences || accountSequences.length === 0) {
      return [];
    }

    this.logger.debug(
      `[batchGetMonthlyEarnings] 查询 ${accountSequences.length} 个账户的月度收益, month=${month}`,
    );

    const result = await this.rewardService.batchGetMonthlyEarnings(
      accountSequences,
      month,
      rightTypes,
    );

    this.logger.debug(
      `[batchGetMonthlyEarnings] 返回 ${result.length} 条记录`,
    );

    return result;
  }

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

  @Get('statistics/expired-rewards-summary')
  @ApiOperation({ summary: '过期收益统计汇总（内部接口）- 用于系统账户报表' })
  @ApiQuery({ name: 'startDate', required: false, description: '开始日期 (YYYY-MM-DD)' })
  @ApiQuery({ name: 'endDate', required: false, description: '结束日期 (YYYY-MM-DD)' })
  @ApiResponse({ status: 200, description: '过期收益统计汇总' })
  async getExpiredRewardsSummary(
    @Query('startDate') startDate?: string,
    @Query('endDate') endDate?: string,
  ) {
    this.logger.log(`========== statistics/expired-rewards-summary 请求 ==========`);
    this.logger.log(`startDate: ${startDate}, endDate: ${endDate}`);

    const result = await this.rewardService.getExpiredRewardsSummary({
      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-06] 新增：收益类型汇总统计接口
  // 用于系统账户报表中的：手续费汇总、省团队收益汇总、市团队收益汇总、分享引荐收益汇总、社区收益汇总
  // 回滚方式：删除以下 API 方法即可

  @Get('statistics/reward-type-summaries')
  @ApiOperation({ summary: '所有收益类型汇总统计（内部接口）- 用于系统账户报表' })
  @ApiResponse({ status: 200, description: '所有收益类型汇总' })
  async getAllRewardTypeSummaries() {
    this.logger.log(`========== statistics/reward-type-summaries 请求 ==========`);

    const result = await this.rewardService.getAllRewardTypeSummaries();

    this.logger.log(`收益类型汇总统计结果:`);
    this.logger.log(`  - 手续费汇总: ${result.feeAccountSummary.totalAmount}`);
    this.logger.log(`  - 省团队收益: ${result.provinceTeamSummary.totalAmount}`);
    this.logger.log(`  - 市团队收益: ${result.cityTeamSummary.totalAmount}`);
    this.logger.log(`  - 分享引荐收益: ${result.shareReferralSummary.totalAmount}`);
    this.logger.log(`  - 社区收益: ${result.communitySummary.totalAmount}`);

    return result;
  }

  // [2026-01-06] 新增：收益类型详细记录列表接口
  // 用于系统账户报表中展示各收益类型的明细列表
  // 回滚方式：删除以下 API 方法即可

  @Get('statistics/reward-entries-by-type')
  @ApiOperation({ summary: '获取指定收益类型的详细记录列表（内部接口）- 用于系统账户报表' })
  @ApiQuery({ name: 'rightType', required: true, description: '收益类型' })
  @ApiQuery({ name: 'page', required: false, description: '页码，默认1' })
  @ApiQuery({ name: 'pageSize', required: false, description: '每页条数，默认50' })
  @ApiResponse({ status: 200, description: '收益类型详细记录列表' })
  async getRewardEntriesByType(
    @Query('rightType') rightType: string,
    @Query('page') page?: string,
    @Query('pageSize') pageSize?: string,
  ) {
    this.logger.log(`========== statistics/reward-entries-by-type 请求 ==========`);
    this.logger.log(`rightType=${rightType}, page=${page}, pageSize=${pageSize}`);

    const result = await this.rewardService.getRewardEntriesByType({
      rightType,
      page: page ? parseInt(page, 10) : undefined,
      pageSize: pageSize ? parseInt(pageSize, 10) : undefined,
    });

    this.logger.log(`收益类型详细记录查询结果: total=${result.total}, page=${result.page}, pageSize=${result.pageSize}`);
    return result;
  }

  @Get('statistics/fee-entries-detailed')
  @ApiOperation({ summary: '获取手续费类型的详细记录列表（内部接口）- 用于系统账户报表' })
  @ApiQuery({ name: 'page', required: false, description: '页码，默认1' })
  @ApiQuery({ name: 'pageSize', required: false, description: '每页条数，默认50' })
  @ApiResponse({ status: 200, description: '手续费类型详细记录列表' })
  async getFeeEntriesDetailed(
    @Query('page') page?: string,
    @Query('pageSize') pageSize?: string,
  ) {
    this.logger.log(`========== statistics/fee-entries-detailed 请求 ==========`);
    this.logger.log(`page=${page}, pageSize=${pageSize}`);

    const result = await this.rewardService.getFeeEntriesDetailed({
      page: page ? parseInt(page, 10) : undefined,
      pageSize: pageSize ? parseInt(pageSize, 10) : undefined,
    });

    this.logger.log(`手续费详细记录查询结果: total=${result.total}, page=${result.page}, pageSize=${result.pageSize}`);
    return result;
  }

  // [2026-01-07] 新增：获取过期收益明细列表接口
  // 用于系统账户报表中展示过期收益的具体记录
  // 回滚方式：删除以下 API 方法即可

  @Get('statistics/expired-rewards-entries')
  @ApiOperation({ summary: '获取过期收益明细列表（内部接口）- 用于系统账户报表' })
  @ApiQuery({ name: 'page', required: false, description: '页码，默认1' })
  @ApiQuery({ name: 'pageSize', required: false, description: '每页条数，默认50' })
  @ApiQuery({ name: 'rightType', required: false, description: '权益类型筛选（可选）' })
  @ApiResponse({ status: 200, description: '过期收益明细列表' })
  async getExpiredRewardsEntries(
    @Query('page') page?: string,
    @Query('pageSize') pageSize?: string,
    @Query('rightType') rightType?: string,
  ) {
    this.logger.log(`========== statistics/expired-rewards-entries 请求 ==========`);
    this.logger.log(`page=${page}, pageSize=${pageSize}, rightType=${rightType || 'all'}`);

    const result = await this.rewardService.getExpiredRewardsEntries({
      page: page ? parseInt(page, 10) : undefined,
      pageSize: pageSize ? parseInt(pageSize, 10) : undefined,
      rightType: rightType || undefined,
    });

    this.logger.log(`过期收益明细查询结果: total=${result.total}, page=${result.page}, pageSize=${result.pageSize}`);
    return result;
  }
}
