/**
 * Wallet Service HTTP 客户端
 * [2026-01-04] 新增：用于系统账户报表统计
 * 回滚方式：删除此文件
 */

import { Injectable, Logger } from '@nestjs/common';
import { HttpService } from '@nestjs/axios';
import { ConfigService } from '@nestjs/config';
import { firstValueFrom } from 'rxjs';

export interface OfflineSettlementSummary {
  totalAmount: number;
  totalCount: number;
  byMonth: Array<{
    month: string;
    amount: number;
    count: number;
  }>;
}

// [2026-01-07] 新增：面对面结算明细条目
export interface OfflineSettlementEntryDTO {
  id: string;
  accountSequence: string;
  amount: number;
  memo: string | null;
  refOrderId: string | null;
  createdAt: string;
}

// [2026-01-07] 新增：面对面结算明细列表响应
export interface OfflineSettlementEntriesResponse {
  entries: OfflineSettlementEntryDTO[];
  total: number;
  page: number;
  pageSize: number;
  totalPages: number;
}

export interface SystemAccountBalance {
  accountSequence: string;
  name: string;
  balance: number;
  totalReceived: number;
  createdAt: string;
}

// [2026-01-05] 新增：所有系统账户响应类型
// [2026-01-07] 更新：省/市区域账户添加 totalTransferred 字段
export interface AllSystemAccountsResponse {
  fixedAccounts: Array<{
    accountSequence: string;
    accountType: string;
    usdtBalance: string;
    totalReceived: string;
    totalTransferred: string;
    status: string;
    createdAt: string;
  }>;
  provinceAccounts: Array<{
    accountSequence: string;
    regionCode: string;
    regionName: string;
    usdtBalance: string;
    totalReceived: string;
    totalTransferred: string;  // [2026-01-07] 新增：累计转出
    status: string;
  }>;
  cityAccounts: Array<{
    accountSequence: string;
    regionCode: string;
    regionName: string;
    usdtBalance: string;
    totalReceived: string;
    totalTransferred: string;  // [2026-01-07] 新增：累计转出
    status: string;
  }>;
}

// [2026-01-05] 新增：分类账条目类型
export interface LedgerEntryDTO {
  id: string;
  entryType: string;
  amount: number;
  assetType: string;
  balanceAfter: number | null;
  refOrderId: string | null;
  refTxHash: string | null;
  memo: string | null;
  allocationType: string | null;
  createdAt: string;
}

// [2026-01-05] 新增：所有系统账户分类账响应类型
export interface AllSystemAccountsLedgerResponse {
  fixedAccountsLedger: Array<{
    accountSequence: string;
    accountType: string;
    ledger: LedgerEntryDTO[];
    total: number;
  }>;
  provinceAccountsLedger: Array<{
    accountSequence: string;
    regionCode: string;
    regionName: string;
    ledger: LedgerEntryDTO[];
    total: number;
  }>;
  cityAccountsLedger: Array<{
    accountSequence: string;
    regionCode: string;
    regionName: string;
    ledger: LedgerEntryDTO[];
    total: number;
  }>;
}

// [2026-01-06] 新增：手续费归集账户汇总响应类型
export interface FeeCollectionSummaryResponse {
  accountSequence: string;
  accountBalance: number;
  totalAmount: number;
  totalCount: number;
  breakdown: Array<{
    feeType: string;
    amount: number;
    count: number;
  }>;
  byMonth: Array<{
    month: string;
    amount: number;
    count: number;
  }>;
}

// [2026-01-06] 新增：手续费归集流水条目
export interface FeeCollectionEntryDTO {
  id: string;
  feeType: string;
  amount: number;
  refOrderId: string | null;
  memo: string | null;
  createdAt: string;
}

// [2026-01-06] 新增：手续费归集流水列表响应
export interface FeeCollectionEntriesResponse {
  entries: FeeCollectionEntryDTO[];
  total: number;
  page: number;
  pageSize: number;
  totalPages: number;
}

@Injectable()
export class WalletServiceClient {
  private readonly logger = new Logger(WalletServiceClient.name);
  private readonly baseUrl: string;

  constructor(
    private readonly httpService: HttpService,
    private readonly configService: ConfigService,
  ) {
    this.baseUrl = this.configService.get<string>(
      'WALLET_SERVICE_URL',
      'http://rwa-wallet-service:3001',
    );
  }

  /**
   * 获取面对面结算统计汇总
   * [2026-01-06] 修复：wallet-service 返回 { success, data, timestamp } 包装格式，需要解包
   */
  async getOfflineSettlementSummary(params?: {
    startDate?: string;
    endDate?: string;
  }): Promise<OfflineSettlementSummary> {
    try {
      const queryParams = new URLSearchParams();
      if (params?.startDate) queryParams.append('startDate', params.startDate);
      if (params?.endDate) queryParams.append('endDate', params.endDate);

      const url = `${this.baseUrl}/api/v1/wallets/statistics/offline-settlement-summary?${queryParams.toString()}`;
      this.logger.debug(`[getOfflineSettlementSummary] 请求: ${url}`);

      const response = await firstValueFrom(
        this.httpService.get<{ success: boolean; data: OfflineSettlementSummary; timestamp: string }>(url),
      );

      // wallet-service 返回 { success, data, timestamp } 包装格式
      return response.data.data;
    } catch (error) {
      this.logger.error(`[getOfflineSettlementSummary] 失败: ${error.message}`);
      // 返回默认值，不阻塞报表
      return {
        totalAmount: 0,
        totalCount: 0,
        byMonth: [],
      };
    }
  }

  // [2026-01-07] 新增：获取面对面结算明细列表
  // 回滚方式：删除此方法
  /**
   * 获取面对面结算明细列表
   */
  async getOfflineSettlementEntries(params?: {
    page?: number;
    pageSize?: number;
    startDate?: string;
    endDate?: string;
  }): Promise<OfflineSettlementEntriesResponse> {
    try {
      const queryParams = new URLSearchParams();
      if (params?.page) queryParams.append('page', params.page.toString());
      if (params?.pageSize) queryParams.append('pageSize', params.pageSize.toString());
      if (params?.startDate) queryParams.append('startDate', params.startDate);
      if (params?.endDate) queryParams.append('endDate', params.endDate);

      const url = `${this.baseUrl}/api/v1/wallets/statistics/offline-settlement-entries?${queryParams.toString()}`;
      this.logger.debug(`[getOfflineSettlementEntries] 请求: ${url}`);

      const response = await firstValueFrom(
        this.httpService.get<{ success: boolean; data: OfflineSettlementEntriesResponse; timestamp: string }>(url),
      );

      // wallet-service 返回 { success, data, timestamp } 包装格式
      return response.data.data;
    } catch (error) {
      this.logger.error(`[getOfflineSettlementEntries] 失败: ${error.message}`);
      // 返回默认值，不阻塞报表
      return {
        entries: [],
        total: 0,
        page: 1,
        pageSize: params?.pageSize ?? 50,
        totalPages: 0,
      };
    }
  }

  /**
   * 获取系统账户余额
   */
  async getSystemAccountsBalances(
    accountSequences: string[],
  ): Promise<SystemAccountBalance[]> {
    try {
      const url = `${this.baseUrl}/api/v1/wallets/statistics/system-accounts-balances?sequences=${accountSequences.join(',')}`;
      this.logger.debug(`[getSystemAccountsBalances] 请求: ${url}`);

      const response = await firstValueFrom(
        this.httpService.get<SystemAccountBalance[]>(url),
      );

      return response.data;
    } catch (error) {
      this.logger.error(`[getSystemAccountsBalances] 失败: ${error.message}`);
      return [];
    }
  }

  // [2026-01-05] 新增：获取所有系统账户（固定+区域）
  /**
   * 获取所有系统账户列表
   * 从 wallet-service 获取实际余额数据
   */
  async getAllSystemAccounts(): Promise<AllSystemAccountsResponse> {
    try {
      const url = `${this.baseUrl}/api/v1/wallets/statistics/all-system-accounts`;
      this.logger.debug(`[getAllSystemAccounts] 请求: ${url}`);

      const response = await firstValueFrom(
        this.httpService.get<{ success: boolean; data: AllSystemAccountsResponse }>(url),
      );

      // wallet-service 返回 { success: true, data: { fixedAccounts, ... } }
      return response.data.data;
    } catch (error) {
      this.logger.error(`[getAllSystemAccounts] 失败: ${error.message}`);
      return {
        fixedAccounts: [],
        provinceAccounts: [],
        cityAccounts: [],
      };
    }
  }

  // [2026-01-05] 新增：获取所有系统账户的分类账明细
  /**
   * 获取所有系统账户的分类账明细
   * 返回每个系统账户的交易流水
   */
  async getAllSystemAccountsLedger(params?: {
    pageSize?: number;
    startDate?: string;
    endDate?: string;
  }): Promise<AllSystemAccountsLedgerResponse> {
    try {
      const queryParams = new URLSearchParams();
      if (params?.pageSize) queryParams.append('pageSize', params.pageSize.toString());
      if (params?.startDate) queryParams.append('startDate', params.startDate);
      if (params?.endDate) queryParams.append('endDate', params.endDate);

      const url = `${this.baseUrl}/api/v1/wallets/statistics/all-system-accounts-ledger?${queryParams.toString()}`;
      this.logger.debug(`[getAllSystemAccountsLedger] 请求: ${url}`);

      const response = await firstValueFrom(
        this.httpService.get<{ success: boolean; data: AllSystemAccountsLedgerResponse }>(url),
      );

      return response.data.data;
    } catch (error) {
      this.logger.error(`[getAllSystemAccountsLedger] 失败: ${error.message}`);
      return {
        fixedAccountsLedger: [],
        provinceAccountsLedger: [],
        cityAccountsLedger: [],
      };
    }
  }

  // [2026-01-06] 新增：获取手续费归集账户汇总统计
  // [2026-01-07] 修复：wallet-service 返回 { success, data, timestamp } 包装格式，需要解包
  /**
   * 获取手续费归集账户汇总统计
   * 统计 S0000000006 账户收到的所有提现手续费
   */
  async getFeeCollectionSummary(): Promise<FeeCollectionSummaryResponse> {
    try {
      const url = `${this.baseUrl}/api/v1/wallets/statistics/fee-collection-summary`;
      this.logger.debug(`[getFeeCollectionSummary] 请求: ${url}`);

      const response = await firstValueFrom(
        this.httpService.get<{ success: boolean; data: FeeCollectionSummaryResponse; timestamp: string }>(url),
      );

      // wallet-service 返回 { success, data, timestamp } 包装格式
      return response.data.data;
    } catch (error) {
      this.logger.error(`[getFeeCollectionSummary] 失败: ${error.message}`);
      return {
        accountSequence: 'S0000000006',
        accountBalance: 0,
        totalAmount: 0,
        totalCount: 0,
        breakdown: [],
        byMonth: [],
      };
    }
  }

  // [2026-01-07] 修复：wallet-service 返回 { success, data, timestamp } 包装格式，需要解包
  /**
   * 获取手续费归集账户流水明细
   */
  async getFeeCollectionEntries(params?: {
    page?: number;
    pageSize?: number;
    feeType?: string;
    startDate?: string;
    endDate?: string;
  }): Promise<FeeCollectionEntriesResponse> {
    try {
      const queryParams = new URLSearchParams();
      if (params?.page) queryParams.append('page', params.page.toString());
      if (params?.pageSize) queryParams.append('pageSize', params.pageSize.toString());
      if (params?.feeType) queryParams.append('feeType', params.feeType);
      if (params?.startDate) queryParams.append('startDate', params.startDate);
      if (params?.endDate) queryParams.append('endDate', params.endDate);

      const url = `${this.baseUrl}/api/v1/wallets/statistics/fee-collection-entries?${queryParams.toString()}`;
      this.logger.debug(`[getFeeCollectionEntries] 请求: ${url}`);

      const response = await firstValueFrom(
        this.httpService.get<{ success: boolean; data: FeeCollectionEntriesResponse; timestamp: string }>(url),
      );

      // wallet-service 返回 { success, data, timestamp } 包装格式
      return response.data.data;
    } catch (error) {
      this.logger.error(`[getFeeCollectionEntries] 失败: ${error.message}`);
      return {
        entries: [],
        total: 0,
        page: 1,
        pageSize: params?.pageSize ?? 50,
        totalPages: 0,
      };
    }
  }
}
