/**
 * 系统账户划转服务
 * [2026-01-06] 新增
 * [2026-01-07] 更新：账户余额从 reporting-service 获取，与数据统计页面保持一致
 */

import apiClient from '@/infrastructure/api/client';
import { API_ENDPOINTS } from '@/infrastructure/api/endpoints';
import type {
  SystemAccount,
  SystemWithdrawalRequest,
  SystemWithdrawalResponse,
  SystemWithdrawalQueryParams,
  SystemWithdrawalOrderListResponse,
} from '@/types/system-withdrawal.types';

/**
 * 系统账户划转服务
 */
export const systemWithdrawalService = {
  /**
   * 获取可划转的系统账户列表
   * [2026-01-07] 更新：从 reporting-service 的系统账户报表接口获取数据
   * 这样账户余额的计算方式与数据统计页面完全一致
   * 公式：账户余额 = (累计收入 + 过期收益) - 累计转出
   */
  async getAccounts(): Promise<SystemAccount[]> {
    // 从 reporting-service 获取系统账户报表数据
    const response = await apiClient.get(API_ENDPOINTS.SYSTEM_ACCOUNT_REPORTS.FULL_REPORT);
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const reportData = (response as any)?.data;

    if (!reportData) {
      return [];
    }

    const accounts: SystemAccount[] = [];

    // 处理固定系统账户
    const fixedAccounts = reportData.fixedAccounts;
    if (fixedAccounts) {
      // 按照指定顺序添加固定账户
      const orderedKeys = ['costAccount', 'operationAccount', 'hqCommunity', 'rwadPoolPending', 'platformFee'];
      for (const key of orderedKeys) {
        const account = fixedAccounts[key];
        if (account) {
          accounts.push({
            accountSequence: account.accountSequence,
            accountName: account.accountType || key,
            balance: account.usdtBalance || '0',
          });
        }
      }
    }

    // 处理省区域账户
    if (reportData.provinceSummary?.accounts) {
      for (const account of reportData.provinceSummary.accounts) {
        accounts.push({
          accountSequence: account.accountSequence,
          accountName: account.regionName || `省区域(${account.regionCode})`,
          balance: account.usdtBalance || '0',
        });
      }
    }

    // 处理市区域账户
    if (reportData.citySummary?.accounts) {
      for (const account of reportData.citySummary.accounts) {
        accounts.push({
          accountSequence: account.accountSequence,
          accountName: account.regionName || `市区域(${account.regionCode})`,
          balance: account.usdtBalance || '0',
        });
      }
    }

    return accounts;
  },

  /**
   * 获取划转订单列表
   * [2026-01-07] 修复：响应结构为 { success, data: { code, message, data } }，需要 .data.data
   */
  async getOrders(params: SystemWithdrawalQueryParams = {}): Promise<SystemWithdrawalOrderListResponse> {
    const response = await apiClient.get(API_ENDPOINTS.SYSTEM_WITHDRAWAL.ORDERS, { params });
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const result = (response as any)?.data?.data;
    // 适配后端返回格式：orders -> items, pageSize -> limit
    if (result) {
      return {
        items: result.orders ?? [],
        total: result.total ?? 0,
        page: result.page ?? 1,
        limit: result.pageSize ?? 20,
      };
    }
    return { items: [], total: 0, page: 1, limit: 20 };
  },

  /**
   * 获取账户名称
   * [2026-01-07] 修复：使用 query 参数传递 accountSequence，响应结构需要 .data.data
   */
  async getAccountName(accountSequence: string): Promise<{ accountSequence: string; name: string }> {
    const response = await apiClient.get(API_ENDPOINTS.SYSTEM_WITHDRAWAL.ACCOUNT_NAME, {
      params: { accountSequence },
    });
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const result = (response as any)?.data?.data;
    return result ?? { accountSequence, name: '未知账户' };
  },

  /**
   * 发起划转请求
   * [2026-01-07] 修复：响应结构需要 .data.data
   */
  async request(data: SystemWithdrawalRequest): Promise<SystemWithdrawalResponse> {
    const response = await apiClient.post(API_ENDPOINTS.SYSTEM_WITHDRAWAL.REQUEST, data);
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    return (response as any)?.data?.data;
  },
};

export default systemWithdrawalService;
