/**
 * 系统账户报表应用服务
 * [2026-01-04] 新增：用于聚合各服务的系统账户报表数据
 * [2026-01-05] 修改：改为从 wallet-service 获取系统账户数据（实际余额所在位置）
 * [2026-01-06] 更新：添加收益类型汇总统计接口
 * 回滚方式：删除此文件，并从 application.module.ts 中移除注册
 */
import { Injectable, Logger } from '@nestjs/common';
import { WalletServiceClient, OfflineSettlementSummary, AllSystemAccountsResponse, AllSystemAccountsLedgerResponse, FeeCollectionSummaryResponse, FeeCollectionEntriesResponse, OfflineSettlementEntriesResponse } from '../../infrastructure/external/wallet-service/wallet-service.client';
import { RewardServiceClient, ExpiredRewardsSummary, AllRewardTypeSummaries, RewardEntriesResponse, ExpiredRewardsEntriesResponse } from '../../infrastructure/external/reward-service/reward-service.client';

/**
 * 固定系统账户信息
 */
export interface FixedAccountInfo {
  accountSequence: string;
  accountType: string;
  usdtBalance: string;
  totalReceived: string;
  totalTransferred: string;
  status: string;
  createdAt: string;
}

/**
 * 区域账户信息
 */
export interface RegionAccountInfo {
  accountSequence: string;
  regionCode: string;
  regionName: string;
  usdtBalance: string;
  totalReceived: string;
  totalTransferred: string;  // [2026-01-07] 新增：累计转出
  status: string;
}

/**
 * 系统账户报表完整响应
 */
export interface SystemAccountReportResponse {
  // 固定系统账户
  fixedAccounts: {
    costAccount: FixedAccountInfo | null;       // 成本账户 S0000000001
    operationAccount: FixedAccountInfo | null;  // 运营账户 S0000000002
    hqCommunity: FixedAccountInfo | null;       // 总部社区 S0000000003
    rwadPoolPending: FixedAccountInfo | null;   // RWAD待发放池 S0000000004
    platformFee: FixedAccountInfo | null;       // 平台手续费 S0000000005
  };
  // 省区域账户汇总
  provinceSummary: {
    accounts: RegionAccountInfo[];
    summary: {
      totalBalance: string;
      totalReceived: string;
      totalTransferred: string;  // [2026-01-07] 新增：累计转出
      count: number;
    };
  };
  // 市区域账户汇总
  citySummary: {
    accounts: RegionAccountInfo[];
    summary: {
      totalBalance: string;
      totalReceived: string;
      totalTransferred: string;  // [2026-01-07] 新增：累计转出
      count: number;
    };
  };
  // 面对面结算统计
  offlineSettlement: OfflineSettlementSummary;
  // 过期收益统计
  expiredRewards: ExpiredRewardsSummary;
  // 报表生成时间
  generatedAt: string;
}

/**
 * 固定账户类型映射
 */
const FIXED_ACCOUNT_TYPES: Record<string, string> = {
  COST_ACCOUNT: 'costAccount',
  OPERATION_ACCOUNT: 'operationAccount',
  HQ_COMMUNITY: 'hqCommunity',
  RWAD_POOL_PENDING: 'rwadPoolPending',
  PLATFORM_FEE: 'platformFee',
};

@Injectable()
export class SystemAccountReportApplicationService {
  private readonly logger = new Logger(SystemAccountReportApplicationService.name);

  constructor(
    private readonly walletServiceClient: WalletServiceClient,
    private readonly rewardServiceClient: RewardServiceClient,
  ) {}

  /**
   * 获取完整的系统账户报表
   * [2026-01-05] 修改：从 wallet-service 获取所有系统账户数据
   */
  async getFullReport(params?: {
    startDate?: string;
    endDate?: string;
  }): Promise<SystemAccountReportResponse> {
    this.logger.log('[getFullReport] 开始聚合系统账户报表数据...');

    // 并行获取所有数据
    const [
      allSystemAccounts,
      offlineSettlement,
      expiredRewards,
    ] = await Promise.all([
      this.walletServiceClient.getAllSystemAccounts(),
      this.walletServiceClient.getOfflineSettlementSummary(params),
      this.rewardServiceClient.getExpiredRewardsSummary(params),
    ]);

    // 组装固定账户数据，并将过期收益累加到总部储蓄账户
    const fixedAccounts = this.assembleFixedAccounts(
      allSystemAccounts.fixedAccounts,
      expiredRewards.totalAmount,
    );

    // 组装省账户汇总
    const provinceSummary = this.assembleRegionSummary(allSystemAccounts.provinceAccounts);

    // 组装市账户汇总
    const citySummary = this.assembleRegionSummary(allSystemAccounts.cityAccounts);

    const report: SystemAccountReportResponse = {
      fixedAccounts,
      provinceSummary,
      citySummary,
      offlineSettlement,
      expiredRewards,
      generatedAt: new Date().toISOString(),
    };

    this.logger.log('[getFullReport] 系统账户报表数据聚合完成');
    return report;
  }

  /**
   * 获取固定账户列表（带余额）
   */
  async getFixedAccountsWithBalances(): Promise<FixedAccountInfo[]> {
    const allSystemAccounts = await this.walletServiceClient.getAllSystemAccounts();
    return allSystemAccounts.fixedAccounts;
  }

  /**
   * 获取省区域账户汇总
   */
  async getProvinceAccountsSummary(): Promise<{
    accounts: RegionAccountInfo[];
    summary: { totalBalance: string; totalReceived: string; totalTransferred: string; count: number };
  }> {
    const allSystemAccounts = await this.walletServiceClient.getAllSystemAccounts();
    return this.assembleRegionSummary(allSystemAccounts.provinceAccounts);
  }

  /**
   * 获取市区域账户汇总
   */
  async getCityAccountsSummary(): Promise<{
    accounts: RegionAccountInfo[];
    summary: { totalBalance: string; totalReceived: string; totalTransferred: string; count: number };
  }> {
    const allSystemAccounts = await this.walletServiceClient.getAllSystemAccounts();
    return this.assembleRegionSummary(allSystemAccounts.cityAccounts);
  }

  /**
   * 获取面对面结算统计
   */
  async getOfflineSettlementSummary(params?: {
    startDate?: string;
    endDate?: string;
  }): Promise<OfflineSettlementSummary> {
    return this.walletServiceClient.getOfflineSettlementSummary(params);
  }

  /**
   * 获取过期收益统计
   */
  async getExpiredRewardsSummary(params?: {
    startDate?: string;
    endDate?: string;
  }): Promise<ExpiredRewardsSummary> {
    return this.rewardServiceClient.getExpiredRewardsSummary(params);
  }

  // [2026-01-07] 新增：获取过期收益明细列表
  // 回滚方式：删除此方法
  /**
   * 获取过期收益明细列表
   */
  async getExpiredRewardsEntries(params?: {
    page?: number;
    pageSize?: number;
    rightType?: string;
  }): Promise<ExpiredRewardsEntriesResponse> {
    this.logger.log('[getExpiredRewardsEntries] 获取过期收益明细列表');
    return this.rewardServiceClient.getExpiredRewardsEntries(params);
  }

  // [2026-01-07] 新增：获取面对面结算明细列表
  // 回滚方式：删除此方法
  /**
   * 获取面对面结算明细列表
   */
  async getOfflineSettlementEntries(params?: {
    page?: number;
    pageSize?: number;
    startDate?: string;
    endDate?: string;
  }): Promise<OfflineSettlementEntriesResponse> {
    this.logger.log('[getOfflineSettlementEntries] 获取面对面结算明细列表');
    return this.walletServiceClient.getOfflineSettlementEntries(params);
  }

  // [2026-01-05] 新增：获取所有系统账户的分类账明细
  /**
   * 获取所有系统账户的分类账明细
   * 返回每个系统账户的交易流水
   */
  async getAllSystemAccountsLedger(params?: {
    pageSize?: number;
    startDate?: string;
    endDate?: string;
  }): Promise<AllSystemAccountsLedgerResponse> {
    this.logger.log('[getAllSystemAccountsLedger] 开始获取所有系统账户分类账...');
    const result = await this.walletServiceClient.getAllSystemAccountsLedger(params);
    this.logger.log(`[getAllSystemAccountsLedger] 完成: 固定=${result.fixedAccountsLedger.length}, 省=${result.provinceAccountsLedger.length}, 市=${result.cityAccountsLedger.length}`);
    return result;
  }

  // [2026-01-06] 新增：获取所有收益类型汇总统计
  /**
   * 获取所有收益类型的汇总统计
   * 包括：手续费汇总、省团队收益汇总、市团队收益汇总、分享引荐收益汇总、社区收益汇总
   */
  async getAllRewardTypeSummaries(): Promise<AllRewardTypeSummaries> {
    this.logger.log('[getAllRewardTypeSummaries] 开始获取所有收益类型汇总...');
    const result = await this.rewardServiceClient.getAllRewardTypeSummaries();
    this.logger.log(`[getAllRewardTypeSummaries] 完成`);
    return result;
  }

  // [2026-01-06] 新增：获取收益类型详细记录列表
  /**
   * 获取指定收益类型的详细记录列表
   */
  async getRewardEntriesByType(params: {
    rightType: string;
    page?: number;
    pageSize?: number;
  }): Promise<RewardEntriesResponse> {
    this.logger.log(`[getRewardEntriesByType] 获取收益类型详细记录: ${params.rightType}`);
    return this.rewardServiceClient.getRewardEntriesByType(params);
  }

  /**
   * 获取手续费类型的详细记录列表
   * @deprecated 使用 getFeeCollectionEntries 获取真正的提现手续费记录
   */
  async getFeeEntriesDetailed(params?: {
    page?: number;
    pageSize?: number;
  }): Promise<RewardEntriesResponse> {
    this.logger.log('[getFeeEntriesDetailed] 获取手续费类型详细记录');
    return this.rewardServiceClient.getFeeEntriesDetailed(params);
  }

  // [2026-01-06] 新增：获取手续费归集账户统计（真正的提现手续费）
  // 来源：wallet-service 中 S0000000006 账户的 FEE_COLLECTION 类型流水
  // 回滚方式：删除以下方法

  /**
   * 获取手续费归集账户汇总统计
   * 统计 S0000000006 账户收到的所有提现手续费
   */
  async getFeeCollectionSummary(): Promise<FeeCollectionSummaryResponse> {
    this.logger.log('[getFeeCollectionSummary] 获取手续费归集账户汇总统计');
    return this.walletServiceClient.getFeeCollectionSummary();
  }

  /**
   * 获取手续费归集账户流水明细
   */
  async getFeeCollectionEntries(params?: {
    page?: number;
    pageSize?: number;
    feeType?: string;
    startDate?: string;
    endDate?: string;
  }): Promise<FeeCollectionEntriesResponse> {
    this.logger.log('[getFeeCollectionEntries] 获取手续费归集流水明细');
    return this.walletServiceClient.getFeeCollectionEntries(params);
  }

  /**
   * 组装固定账户数据
   * [2026-01-07] 更新：账户余额 = 累计收入 - 累计转出
   * 对于总部储蓄账户 (HQ_COMMUNITY / S0000000001)，累计收入需要加上过期收益
   */
  private assembleFixedAccounts(
    fixedAccounts: AllSystemAccountsResponse['fixedAccounts'],
    expiredRewardsTotal: number = 0,
  ): SystemAccountReportResponse['fixedAccounts'] {
    const result: SystemAccountReportResponse['fixedAccounts'] = {
      costAccount: null,
      operationAccount: null,
      hqCommunity: null,
      rwadPoolPending: null,
      platformFee: null,
    };

    for (const account of fixedAccounts) {
      const fieldName = FIXED_ACCOUNT_TYPES[account.accountType];
      if (fieldName && fieldName in result) {
        const currentReceived = parseFloat(account.totalReceived) || 0;
        const currentTransferred = parseFloat(account.totalTransferred) || 0;

        // 如果是总部储蓄账户 (HQ_COMMUNITY)，累计收入需要加上过期收益
        if (account.accountType === 'HQ_COMMUNITY' && expiredRewardsTotal > 0) {
          const newTotalReceived = currentReceived + expiredRewardsTotal;
          // 账户余额 = 累计收入 - 累计转出
          const newBalance = newTotalReceived - currentTransferred;
          (result as any)[fieldName] = {
            ...account,
            usdtBalance: newBalance.toFixed(8),
            totalReceived: newTotalReceived.toFixed(8),
          };
          this.logger.log(
            `[assembleFixedAccounts] HQ_COMMUNITY 累计收入: ${currentReceived} + 过期收益 ${expiredRewardsTotal} = ${newTotalReceived}`,
          );
          this.logger.log(
            `[assembleFixedAccounts] HQ_COMMUNITY 余额: ${newTotalReceived} - ${currentTransferred} = ${newBalance}`,
          );
        } else {
          // 其他账户：账户余额 = 累计收入 - 累计转出
          const newBalance = currentReceived - currentTransferred;
          (result as any)[fieldName] = {
            ...account,
            usdtBalance: newBalance.toFixed(8),
          };
        }
      }
    }

    return result;
  }

  /**
   * 组装区域账户汇总
   * [2026-01-07] 更新：添加 totalTransferred 累计转出统计
   */
  private assembleRegionSummary(
    accounts: RegionAccountInfo[],
  ): {
    accounts: RegionAccountInfo[];
    summary: { totalBalance: string; totalReceived: string; totalTransferred: string; count: number };
  } {
    let totalBalance = 0;
    let totalReceived = 0;
    let totalTransferred = 0;

    for (const account of accounts) {
      totalBalance += parseFloat(account.usdtBalance) || 0;
      totalReceived += parseFloat(account.totalReceived) || 0;
      totalTransferred += parseFloat(account.totalTransferred) || 0;
    }

    return {
      accounts,
      summary: {
        totalBalance: totalBalance.toFixed(8),
        totalReceived: totalReceived.toFixed(8),
        totalTransferred: totalTransferred.toFixed(8),
        count: accounts.length,
      },
    };
  }
}
