/**
 * 系统账户报表Tab组件
 * [2026-01-04] 新增：显示系统账户统计数据
 * [2026-01-05] 更新：添加分类账明细显示
 * [2026-01-06] 更新：添加收益类型汇总统计（手续费、省团队、市团队、分享引荐、社区）
 * 回滚方式：删除此文件及整个 system-account-report 目录
 */
'use client';

import { useState, useEffect, useCallback } from 'react';
import { systemAccountReportService } from '@/services/systemAccountReportService';
import type {
  SystemAccountReportResponse,
  RegionAccountsSummary,
  AllSystemAccountsLedgerResponse,
  FixedAccountLedger,
  RegionAccountLedger,
  LedgerEntryDTO,
  AllRewardTypeSummariesResponse,
  RewardTypeSummary,
  FeeAccountSummary,
  RewardEntriesResponse,
  RewardEntryDTO,
  FeeCollectionSummaryResponse,
  FeeCollectionEntriesResponse,
  OfflineSettlementEntriesResponse,
  OfflineSettlementEntryDTO,
  ExpiredRewardsEntriesResponse,
  ExpiredRewardEntryDTO,
} from '@/types';
import { ENTRY_TYPE_LABELS, ACCOUNT_TYPE_LABELS, FEE_TYPE_LABELS, REWARD_RIGHT_TYPE_LABELS, REWARD_STATUS_LABELS, FEE_COLLECTION_TYPE_LABELS, getAccountDisplayName, SYSTEM_ACCOUNT_NAMES, PROVINCE_CODE_NAMES } from '@/types';
import styles from './SystemAccountsTab.module.scss';

/**
 * 格式化金额显示
 */
const formatAmount = (value: string | number | undefined): string => {
  if (value === undefined || value === null) return '0.00';
  const num = typeof value === 'string' ? parseFloat(value) : value;
  if (isNaN(num)) return '0.00';
  return num.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
};

/**
 * 权益类型显示名称
 */
const getRightTypeName = (type: string): string => {
  const labels: Record<string, string> = {
    SETTLEABLE: '可结算收益',
    SHARE: '分享权益',
    PROVINCE_TEAM: '省团队权益',
    CITY_TEAM: '市团队权益',
    PROVINCE_REGION: '省区域权益',
    CITY_REGION: '市区域权益',
    COMMUNITY: '社区权益',
  };
  return labels[type] || type;
};

/**
 * 系统账户报表Tab组件
 */
// Tab类型定义
type TabType = 'fixed' | 'province' | 'city' | 'settlement' | 'expired' | 'ledger' | 'feeAccount' | 'provinceTeam' | 'cityTeam' | 'shareReferral' | 'community';

export default function SystemAccountsTab() {
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [reportData, setReportData] = useState<SystemAccountReportResponse | null>(null);
  const [ledgerData, setLedgerData] = useState<AllSystemAccountsLedgerResponse | null>(null);
  const [ledgerLoading, setLedgerLoading] = useState(false);
  // [2026-01-06] 新增：收益类型汇总数据
  const [rewardTypeSummaries, setRewardTypeSummaries] = useState<AllRewardTypeSummariesResponse | null>(null);
  const [rewardTypeSummariesLoading, setRewardTypeSummariesLoading] = useState(false);
  const [activeTab, setActiveTab] = useState<TabType>('fixed');

  // 加载报表数据
  const loadReportData = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const response = await systemAccountReportService.getFullReport();
      if (response.data) {
        setReportData(response.data);
      }
    } catch (err) {
      setError('加载系统账户报表失败');
      console.error('Failed to load system account report:', err);
    } finally {
      setLoading(false);
    }
  }, []);

  // 加载分类账明细
  const loadLedgerData = useCallback(async () => {
    setLedgerLoading(true);
    try {
      const response = await systemAccountReportService.getAllLedger({ pageSize: 50 });
      if (response.data) {
        setLedgerData(response.data);
      }
    } catch (err) {
      console.error('Failed to load ledger data:', err);
    } finally {
      setLedgerLoading(false);
    }
  }, []);

  // [2026-01-06] 新增：加载收益类型汇总数据
  const loadRewardTypeSummaries = useCallback(async () => {
    setRewardTypeSummariesLoading(true);
    try {
      const response = await systemAccountReportService.getRewardTypeSummaries();
      if (response.data) {
        setRewardTypeSummaries(response.data);
      }
    } catch (err) {
      console.error('Failed to load reward type summaries:', err);
    } finally {
      setRewardTypeSummariesLoading(false);
    }
  }, []);

  useEffect(() => {
    loadReportData();
  }, [loadReportData]);

  // 切换到分类账明细时加载数据
  useEffect(() => {
    if (activeTab === 'ledger' && !ledgerData && !ledgerLoading) {
      loadLedgerData();
    }
  }, [activeTab, ledgerData, ledgerLoading, loadLedgerData]);

  // [2026-01-06] 切换到收益类型汇总Tab时加载数据
  const rewardTypeTabs: TabType[] = ['feeAccount', 'provinceTeam', 'cityTeam', 'shareReferral', 'community'];
  useEffect(() => {
    if (rewardTypeTabs.includes(activeTab) && !rewardTypeSummaries && !rewardTypeSummariesLoading) {
      loadRewardTypeSummaries();
    }
  }, [activeTab, rewardTypeSummaries, rewardTypeSummariesLoading, loadRewardTypeSummaries]);

  if (loading) {
    return (
      <div className={styles.loading}>
        <div className={styles.spinner} />
        <span>加载中...</span>
      </div>
    );
  }

  if (error) {
    return (
      <div className={styles.error}>
        <span>{error}</span>
        <button onClick={loadReportData} className={styles.retryButton}>
          重试
        </button>
      </div>
    );
  }

  if (!reportData) {
    return <div className={styles.empty}>暂无数据</div>;
  }

  return (
    <div className={styles.container}>
      {/* Tab 切换 */}
      <div className={styles.tabs}>
        <button
          className={`${styles.tab} ${activeTab === 'fixed' ? styles.active : ''}`}
          onClick={() => setActiveTab('fixed')}
        >
          固定系统账户
        </button>
        <button
          className={`${styles.tab} ${activeTab === 'province' ? styles.active : ''}`}
          onClick={() => setActiveTab('province')}
        >
          省区域账户汇总
        </button>
        <button
          className={`${styles.tab} ${activeTab === 'city' ? styles.active : ''}`}
          onClick={() => setActiveTab('city')}
        >
          市区域账户汇总
        </button>
        <button
          className={`${styles.tab} ${activeTab === 'settlement' ? styles.active : ''}`}
          onClick={() => setActiveTab('settlement')}
        >
          面对面结算
        </button>
        <button
          className={`${styles.tab} ${activeTab === 'expired' ? styles.active : ''}`}
          onClick={() => setActiveTab('expired')}
        >
          过期收益
        </button>
        {/* [2026-01-07] 隐藏分类账明细Tab */}
        {/* <button
          className={`${styles.tab} ${activeTab === 'ledger' ? styles.active : ''}`}
          onClick={() => setActiveTab('ledger')}
        >
          分类账明细
        </button> */}
        {/* [2026-01-06] 新增：收益类型汇总Tab */}
        <button
          className={`${styles.tab} ${activeTab === 'feeAccount' ? styles.active : ''}`}
          onClick={() => setActiveTab('feeAccount')}
        >
          手续费账户汇总
        </button>
        <button
          className={`${styles.tab} ${activeTab === 'provinceTeam' ? styles.active : ''}`}
          onClick={() => setActiveTab('provinceTeam')}
        >
          省团队收益汇总
        </button>
        <button
          className={`${styles.tab} ${activeTab === 'cityTeam' ? styles.active : ''}`}
          onClick={() => setActiveTab('cityTeam')}
        >
          市团队收益汇总
        </button>
        <button
          className={`${styles.tab} ${activeTab === 'shareReferral' ? styles.active : ''}`}
          onClick={() => setActiveTab('shareReferral')}
        >
          分享引荐收益汇总
        </button>
        <button
          className={`${styles.tab} ${activeTab === 'community' ? styles.active : ''}`}
          onClick={() => setActiveTab('community')}
        >
          社区收益汇总
        </button>
      </div>

      {/* 内容区域 */}
      <div className={styles.content}>
        {activeTab === 'fixed' && <FixedAccountsSection data={reportData.fixedAccounts} />}
        {activeTab === 'province' && <RegionAccountsSection data={reportData.provinceSummary} type="province" />}
        {activeTab === 'city' && <RegionAccountsSection data={reportData.citySummary} type="city" />}
        {activeTab === 'settlement' && <OfflineSettlementSection data={reportData.offlineSettlement} />}
        {activeTab === 'expired' && <ExpiredRewardsSection data={reportData.expiredRewards} />}
        {activeTab === 'ledger' && <LedgerSection data={ledgerData} loading={ledgerLoading} onRefresh={loadLedgerData} />}
        {/* [2026-01-06] 更新：手续费账户汇总改用 wallet-service 的真正提现手续费数据 */}
        {activeTab === 'feeAccount' && (
          <FeeAccountSection
            onRefresh={loadRewardTypeSummaries}
          />
        )}
        {activeTab === 'provinceTeam' && (
          <RewardTypeSummarySection
            title="省团队收益汇总"
            data={rewardTypeSummaries?.provinceTeamSummary}
            loading={rewardTypeSummariesLoading}
            onRefresh={loadRewardTypeSummaries}
          />
        )}
        {activeTab === 'cityTeam' && (
          <RewardTypeSummarySection
            title="市团队收益汇总"
            data={rewardTypeSummaries?.cityTeamSummary}
            loading={rewardTypeSummariesLoading}
            onRefresh={loadRewardTypeSummaries}
          />
        )}
        {activeTab === 'shareReferral' && (
          <RewardTypeSummarySection
            title="分享引荐收益汇总"
            data={rewardTypeSummaries?.shareReferralSummary}
            loading={rewardTypeSummariesLoading}
            onRefresh={loadRewardTypeSummaries}
          />
        )}
        {activeTab === 'community' && (
          <RewardTypeSummarySection
            title="社区收益汇总"
            data={rewardTypeSummaries?.communitySummary}
            loading={rewardTypeSummariesLoading}
            onRefresh={loadRewardTypeSummaries}
          />
        )}
      </div>

      {/* 报表生成时间 */}
      <div className={styles.footer}>
        报表生成时间: {new Date(reportData.generatedAt).toLocaleString('zh-CN')}
      </div>
    </div>
  );
}

/**
 * 固定系统账户区域
 * [2026-01-05] 更新：根据业务需求调整显示名称，USDT改为绿积分
 * [2026-01-07] 更新：添加查看分类账明细按钮，在卡片下方公共区域显示明细
 */
function FixedAccountsSection({ data }: { data: SystemAccountReportResponse['fixedAccounts'] }) {
  // [2026-01-07] 所有 hooks 必须在条件返回之前调用
  const [selectedAccount, setSelectedAccount] = useState<string | null>(null);
  const [allLedgerData, setAllLedgerData] = useState<AllSystemAccountsLedgerResponse | null>(null);
  const [ledgerLoading, setLedgerLoading] = useState(false);

  // 加载所有固定账户的分类账明细（useCallback 必须在条件返回之前）
  const loadAllLedger = useCallback(async () => {
    if (allLedgerData) return; // 已加载过，不重复加载

    setLedgerLoading(true);
    try {
      const response = await systemAccountReportService.getAllLedger({ pageSize: 100 });
      if (response.data) {
        setAllLedgerData(response.data);
      }
    } catch (err) {
      console.error('Failed to load ledger data:', err);
    } finally {
      setLedgerLoading(false);
    }
  }, [allLedgerData]);

  // 获取指定账户的分类账数据
  const getAccountLedger = useCallback((accountSequence: string): LedgerEntryDTO[] => {
    if (!allLedgerData?.fixedAccountsLedger) return [];
    const accountLedger = allLedgerData.fixedAccountsLedger.find(
      (item) => item.accountSequence === accountSequence
    );
    return accountLedger?.ledger || [];
  }, [allLedgerData]);

  // [2026-01-07] 修复：添加空值检查，防止 data 为 undefined 时报错
  if (!data) {
    return <div className={styles.empty}>固定账户数据加载中...</div>;
  }

  // [2026-01-07] 修复：从后端返回数据中读取真实的 accountSequence，过滤掉不存在的账户
  // 后端映射：S0000000001=HQ_COMMUNITY, S0000000002=COST_ACCOUNT, S0000000003=OPERATION_ACCOUNT
  const accounts = [
    { key: 'costAccount', data: data.costAccount },
    { key: 'operationAccount', data: data.operationAccount },
    { key: 'hqCommunity', data: data.hqCommunity },
    { key: 'rwadPoolPending', data: data.rwadPoolPending },
    { key: 'platformFee', data: data.platformFee },
  ]
    .filter(item => item.data !== null && item.data !== undefined) // 过滤掉不存在的账户
    .map(item => ({
      ...item,
      sequence: item.data?.accountSequence || '',
    }));

  // 选择账户查看明细
  const handleSelectAccount = async (accountSequence: string) => {
    if (selectedAccount === accountSequence) {
      setSelectedAccount(null);
      return;
    }

    // 如果还没有加载数据，先加载
    if (!allLedgerData) {
      await loadAllLedger();
    }
    setSelectedAccount(accountSequence);
  };

  // 当前选中账户的明细数据
  const currentLedger = selectedAccount ? getAccountLedger(selectedAccount) : [];

  return (
    <div className={styles.section}>
      <h3 className={styles.sectionTitle}>固定系统账户</h3>
      <div className={styles.cardGrid}>
        {accounts.map(({ key, sequence, data: accountData }) => {
          const isSelected = selectedAccount === sequence;

          return (
            <div key={key} className={`${styles.accountCard} ${isSelected ? styles.accountCardSelected : ''}`}>
              <div className={styles.cardHeader}>
                <span className={styles.accountLabel}>{getAccountDisplayName(sequence)}</span>
              </div>
              <div className={styles.cardBody}>
                <div className={styles.statRow}>
                  <span className={styles.statLabel}>账户余额</span>
                  <span className={styles.statValue}>
                    {accountData ? formatAmount(accountData.usdtBalance) : '0.00'} 绿积分
                  </span>
                </div>
                <div className={styles.statRow}>
                  <span className={styles.statLabel}>累计收入</span>
                  <span className={styles.statValue}>
                    {accountData ? formatAmount(accountData.totalReceived) : '0.00'} 绿积分
                  </span>
                </div>
                <div className={styles.statRow}>
                  <span className={styles.statLabel}>累计转出</span>
                  <span className={styles.statValue}>
                    {accountData ? formatAmount(accountData.totalTransferred) : '0.00'} 绿积分
                  </span>
                </div>
              </div>
              {/* [2026-01-07] 新增：查看明细按钮 */}
              <div className={styles.cardFooter}>
                <button
                  className={`${styles.viewLedgerButton} ${isSelected ? styles.viewLedgerButtonActive : ''}`}
                  onClick={() => handleSelectAccount(sequence)}
                  disabled={ledgerLoading}
                >
                  {ledgerLoading && !allLedgerData ? '加载中...' : isSelected ? '收起明细' : '查看明细'}
                </button>
              </div>
            </div>
          );
        })}
      </div>

      {/* [2026-01-07] 新增：在卡片下方的公共区域显示选中账户的完整明细 */}
      {selectedAccount && (
        <div className={styles.sharedLedgerSection}>
          <div className={styles.sharedLedgerHeader}>
            <h4 className={styles.sharedLedgerTitle}>
              {getAccountDisplayName(selectedAccount)} - 分类账明细
            </h4>
            <button
              className={styles.closeLedgerButton}
              onClick={() => setSelectedAccount(null)}
            >
              关闭
            </button>
          </div>
          {ledgerLoading ? (
            <div className={styles.loading}>
              <div className={styles.spinner} />
              <span>加载明细中...</span>
            </div>
          ) : currentLedger.length > 0 ? (
            <div className={styles.tableWrapper}>
              <table className={styles.table}>
                <thead>
                  <tr>
                    <th>时间</th>
                    <th>类型</th>
                    <th>金额</th>
                    <th>余额</th>
                    <th>来源账户</th>
                    <th>来源备注</th>
                    <th>备注</th>
                  </tr>
                </thead>
                <tbody>
                  {currentLedger.map((entry) => (
                    <tr key={entry.id}>
                      <td>{new Date(entry.createdAt).toLocaleString('zh-CN')}</td>
                      <td>
                        <span className={styles.entryTypeBadge}>
                          {ENTRY_TYPE_LABELS[entry.entryType] || entry.entryType}
                        </span>
                      </td>
                      <td className={entry.amount >= 0 ? styles.amountPositive : styles.amountNegative}>
                        {entry.amount >= 0 ? '+' : ''}{formatAmount(entry.amount)} {getAssetTypeLabel(entry.assetType)}
                      </td>
                      <td>{entry.balanceAfter !== null ? formatAmount(entry.balanceAfter) : '-'}</td>
                      <td className={styles.sourceAccount}>{entry.sourceAccountSequence || '-'}</td>
                      <td className={styles.memo}>{entry.sourceMemo || '-'}</td>
                      <td className={styles.memo}>{entry.memo || entry.allocationType || '-'}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          ) : (
            <div className={styles.emptyLedger}>暂无流水记录</div>
          )}
        </div>
      )}
    </div>
  );
}

/**
 * 区域账户汇总区域
 * [2026-01-05] 更新：USDT改为绿积分
 * [2026-01-07] 更新：增加累计转出显示
 * [2026-02-28] 更新：添加点击账户行展开分类账明细，显示来源账户和来源备注
 */
function RegionAccountsSection({ data, type }: { data: RegionAccountsSummary; type: 'province' | 'city' }) {
  const typeLabel = type === 'province' ? '省' : '市';

  // [2026-02-28] 新增：账户明细展开相关状态
  const [selectedAccount, setSelectedAccount] = useState<string | null>(null);
  const [allLedgerData, setAllLedgerData] = useState<AllSystemAccountsLedgerResponse | null>(null);
  const [ledgerLoading, setLedgerLoading] = useState(false);

  // 加载所有系统账户分类账数据
  const loadAllLedger = useCallback(async () => {
    if (allLedgerData) return;
    setLedgerLoading(true);
    try {
      const response = await systemAccountReportService.getAllLedger({ pageSize: 100 });
      if (response.data) {
        setAllLedgerData(response.data);
      }
    } catch (err) {
      console.error('Failed to load ledger data:', err);
    } finally {
      setLedgerLoading(false);
    }
  }, [allLedgerData]);

  // 获取指定区域账户的分类账数据
  const getAccountLedger = useCallback((accountSequence: string): LedgerEntryDTO[] => {
    const ledgerKey = type === 'province' ? 'provinceAccountsLedger' : 'cityAccountsLedger';
    const regionLedgers = allLedgerData?.[ledgerKey];
    if (!regionLedgers) return [];
    const accountLedger = regionLedgers.find(
      (item) => item.accountSequence === accountSequence
    );
    return accountLedger?.ledger || [];
  }, [allLedgerData, type]);

  // 点击账户行展开/收起明细
  const handleSelectAccount = async (accountSequence: string) => {
    if (selectedAccount === accountSequence) {
      setSelectedAccount(null);
      return;
    }
    if (!allLedgerData) {
      await loadAllLedger();
    }
    setSelectedAccount(accountSequence);
  };

  const currentLedger = selectedAccount ? getAccountLedger(selectedAccount) : [];

  return (
    <div className={styles.section}>
      <h3 className={styles.sectionTitle}>{typeLabel}区域账户汇总</h3>

      {/* 汇总卡片 */}
      <div className={styles.summaryCards}>
        <div className={styles.summaryCard}>
          <span className={styles.summaryLabel}>账户数量</span>
          <span className={styles.summaryValue}>{data.summary.count}</span>
        </div>
        <div className={styles.summaryCard}>
          <span className={styles.summaryLabel}>总余额</span>
          <span className={styles.summaryValue}>{formatAmount(data.summary.totalBalance)} 绿积分</span>
        </div>
        <div className={styles.summaryCard}>
          <span className={styles.summaryLabel}>累计收入</span>
          <span className={styles.summaryValue}>{formatAmount(data.summary.totalReceived)} 绿积分</span>
        </div>
        {/* [2026-01-07] 新增：累计转出 */}
        <div className={styles.summaryCard}>
          <span className={styles.summaryLabel}>累计转出</span>
          <span className={styles.summaryValue}>{formatAmount(data.summary.totalTransferred || '0')} 绿积分</span>
        </div>
      </div>

      {/* 账户列表 */}
      {data.accounts.length > 0 ? (
        <div className={styles.tableWrapper}>
          <table className={styles.table}>
            <thead>
              <tr>
                <th>区域</th>
                <th>余额 (绿积分)</th>
                <th>累计收入 (绿积分)</th>
                <th>累计转出 (绿积分)</th>
                <th>状态</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              {data.accounts.map((account) => (
                <tr
                  key={account.id}
                  className={selectedAccount === account.accountSequence ? styles.selectedRow : styles.clickableRow}
                  onClick={() => handleSelectAccount(account.accountSequence)}
                >
                  {/* [2026-01-07] 更新：使用 getAccountDisplayName 解析区域代码为省市名称 */}
                  <td>{account.regionCode ? getAccountDisplayName(account.regionCode) : '-'}</td>
                  <td>{formatAmount(account.usdtBalance)}</td>
                  <td>{formatAmount(account.totalReceived)}</td>
                  <td>{formatAmount(account.totalTransferred || '0')}</td>
                  <td>
                    <span className={`${styles.statusBadge} ${account.status === 'ACTIVE' ? styles.active : ''}`}>
                      {account.status === 'ACTIVE' ? '正常' : account.status}
                    </span>
                  </td>
                  <td>
                    <button
                      className={`${styles.viewLedgerButton} ${selectedAccount === account.accountSequence ? styles.viewLedgerButtonActive : ''}`}
                      onClick={(e) => { e.stopPropagation(); handleSelectAccount(account.accountSequence); }}
                      disabled={ledgerLoading}
                    >
                      {ledgerLoading && !allLedgerData ? '加载中...' : selectedAccount === account.accountSequence ? '收起明细' : '查看明细'}
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      ) : (
        <div className={styles.emptyTable}>暂无{typeLabel}区域账户数据</div>
      )}

      {/* [2026-02-28] 新增：选中账户的分类账明细展开区域 */}
      {selectedAccount && (
        <div className={styles.sharedLedgerSection}>
          <div className={styles.sharedLedgerHeader}>
            <h4 className={styles.sharedLedgerTitle}>
              {getAccountDisplayName(selectedAccount)} - 分类账明细
            </h4>
            <button
              className={styles.closeLedgerButton}
              onClick={() => setSelectedAccount(null)}
            >
              关闭
            </button>
          </div>
          {ledgerLoading ? (
            <div className={styles.loading}>
              <div className={styles.spinner} />
              <span>加载明细中...</span>
            </div>
          ) : currentLedger.length > 0 ? (
            <div className={styles.tableWrapper}>
              <table className={styles.table}>
                <thead>
                  <tr>
                    <th>时间</th>
                    <th>类型</th>
                    <th>金额</th>
                    <th>余额</th>
                    <th>来源账户</th>
                    <th>来源备注</th>
                    <th>备注</th>
                  </tr>
                </thead>
                <tbody>
                  {currentLedger.map((entry) => (
                    <tr key={entry.id}>
                      <td>{new Date(entry.createdAt).toLocaleString('zh-CN')}</td>
                      <td>
                        <span className={styles.entryTypeBadge}>
                          {ENTRY_TYPE_LABELS[entry.entryType] || entry.entryType}
                        </span>
                      </td>
                      <td className={entry.amount >= 0 ? styles.amountPositive : styles.amountNegative}>
                        {entry.amount >= 0 ? '+' : ''}{formatAmount(entry.amount)} {getAssetTypeLabel(entry.assetType)}
                      </td>
                      <td>{entry.balanceAfter !== null ? formatAmount(entry.balanceAfter) : '-'}</td>
                      <td className={styles.sourceAccount}>{entry.sourceAccountSequence || '-'}</td>
                      <td className={styles.memo}>{entry.sourceMemo || '-'}</td>
                      <td className={styles.memo}>{entry.memo || entry.allocationType || '-'}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          ) : (
            <div className={styles.emptyLedger}>暂无流水记录</div>
          )}
        </div>
      )}
    </div>
  );
}

/**
 * 面对面结算统计区域
 * [2026-01-05] 更新：USDT改为绿积分，添加空值检查
 * [2026-01-07] 更新：添加明细列表显示
 */
function OfflineSettlementSection({ data }: { data: SystemAccountReportResponse['offlineSettlement'] | null | undefined }) {
  const [entriesData, setEntriesData] = useState<OfflineSettlementEntriesResponse | null>(null);
  const [entriesLoading, setEntriesLoading] = useState(false);
  const [showEntries, setShowEntries] = useState(false);

  // 加载明细列表
  const loadEntries = useCallback(async () => {
    setEntriesLoading(true);
    try {
      const response = await systemAccountReportService.getOfflineSettlementEntries({ pageSize: 100 });
      if (response.data) {
        setEntriesData(response.data);
      }
    } catch (err) {
      console.error('Failed to load offline settlement entries:', err);
    } finally {
      setEntriesLoading(false);
    }
  }, []);

  // 切换显示明细时加载数据
  useEffect(() => {
    if (showEntries && !entriesData && !entriesLoading) {
      loadEntries();
    }
  }, [showEntries, entriesData, entriesLoading, loadEntries]);

  if (!data) {
    return (
      <div className={styles.section}>
        <h3 className={styles.sectionTitle}>面对面结算统计</h3>
        <div className={styles.emptyTable}>暂无面对面结算数据</div>
      </div>
    );
  }

  return (
    <div className={styles.section}>
      <h3 className={styles.sectionTitle}>面对面结算统计</h3>

      {/* 汇总卡片 */}
      <div className={styles.summaryCards}>
        <div className={styles.summaryCard}>
          <span className={styles.summaryLabel}>总笔数</span>
          <span className={styles.summaryValue}>{data.totalCount ?? 0}</span>
        </div>
        <div className={styles.summaryCard}>
          <span className={styles.summaryLabel}>总金额</span>
          <span className={styles.summaryValue}>{formatAmount(data.totalAmount)} 绿积分</span>
        </div>
      </div>

      {/* 按月统计 */}
      {data.byMonth && data.byMonth.length > 0 && (
        <>
          <h4 className={styles.subTitle}>按月统计</h4>
          <div className={styles.tableWrapper}>
            <table className={styles.table}>
              <thead>
                <tr>
                  <th>月份</th>
                  <th>笔数</th>
                  <th>金额 (绿积分)</th>
                </tr>
              </thead>
              <tbody>
                {data.byMonth.map((item) => (
                  <tr key={item.month}>
                    <td>{item.month}</td>
                    <td>{item.count}</td>
                    <td>{formatAmount(item.amount)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </>
      )}

      {/* 明细列表切换按钮 */}
      <div className={styles.toggleSection}>
        <button
          className={styles.toggleButton}
          onClick={() => setShowEntries(!showEntries)}
        >
          {showEntries ? '收起明细' : '查看明细列表'}
        </button>
      </div>

      {/* 明细列表 */}
      {showEntries && (
        <div className={styles.entriesSection}>
          <h4 className={styles.subTitle}>明细列表</h4>
          {entriesLoading ? (
            <div className={styles.loading}>加载中...</div>
          ) : entriesData && entriesData.entries.length > 0 ? (
            <div className={styles.tableWrapper}>
              <table className={styles.table}>
                <thead>
                  <tr>
                    <th>账户</th>
                    <th>金额 (绿积分)</th>
                    <th>备注</th>
                    <th>时间</th>
                  </tr>
                </thead>
                <tbody>
                  {entriesData.entries.map((entry) => (
                    <tr key={entry.id}>
                      {/* [2026-01-07] 更新：使用 getAccountDisplayName 显示账户名称和编码 */}
                      <td>{getAccountDisplayName(entry.accountSequence)}</td>
                      <td>{formatAmount(entry.amount)}</td>
                      <td>{entry.memo || '-'}</td>
                      <td>{new Date(entry.createdAt).toLocaleString('zh-CN')}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
              {entriesData.total > entriesData.entries.length && (
                <div className={styles.paginationInfo}>
                  显示 {entriesData.entries.length} / {entriesData.total} 条
                </div>
              )}
            </div>
          ) : (
            <div className={styles.emptyTable}>暂无明细数据</div>
          )}
        </div>
      )}

      {(!data.byMonth || data.byMonth.length === 0) && !showEntries && (
        <div className={styles.emptyTable}>暂无面对面结算数据</div>
      )}
    </div>
  );
}

/**
 * 过期收益统计区域
 * [2026-01-05] 更新：USDT改为绿积分，添加空值检查
 * [2026-01-07] 更新：添加明细列表显示功能
 */
function ExpiredRewardsSection({ data }: { data: SystemAccountReportResponse['expiredRewards'] | null | undefined }) {
  const [showEntries, setShowEntries] = useState(false);
  const [entriesData, setEntriesData] = useState<ExpiredRewardsEntriesResponse | null>(null);
  const [entriesLoading, setEntriesLoading] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [selectedRightType, setSelectedRightType] = useState<string>('');
  const pageSize = 20;

  // 加载明细数据
  const loadEntries = useCallback(async (page: number, rightType?: string) => {
    setEntriesLoading(true);
    try {
      const response = await systemAccountReportService.getExpiredRewardsEntries({
        page,
        pageSize,
        rightType: rightType || undefined,
      });
      if (response.data) {
        setEntriesData(response.data);
      }
    } catch (error) {
      console.error('加载过期收益明细失败:', error);
    } finally {
      setEntriesLoading(false);
    }
  }, [pageSize]);

  // 切换显示明细
  const toggleEntries = () => {
    if (!showEntries && !entriesData) {
      loadEntries(1, selectedRightType);
    }
    setShowEntries(!showEntries);
  };

  // 切换权益类型筛选
  const handleRightTypeChange = (rightType: string) => {
    setSelectedRightType(rightType);
    setCurrentPage(1);
    if (showEntries) {
      loadEntries(1, rightType);
    }
  };

  // 分页
  const handlePageChange = (page: number) => {
    setCurrentPage(page);
    loadEntries(page, selectedRightType);
  };

  if (!data) {
    return (
      <div className={styles.section}>
        <h3 className={styles.sectionTitle}>过期收益统计</h3>
        <div className={styles.emptyTable}>暂无过期收益数据</div>
      </div>
    );
  }

  return (
    <div className={styles.section}>
      <div className={styles.sectionHeader}>
        <h3 className={styles.sectionTitle}>过期收益统计</h3>
        <button
          onClick={toggleEntries}
          className={styles.toggleButton}
        >
          {showEntries ? '收起明细' : '查看明细'}
        </button>
      </div>

      {/* 汇总卡片 */}
      <div className={styles.summaryCards}>
        <div className={styles.summaryCard}>
          <span className={styles.summaryLabel}>总笔数</span>
          <span className={styles.summaryValue}>{data.totalCount ?? 0}</span>
        </div>
        <div className={styles.summaryCard}>
          <span className={styles.summaryLabel}>总金额</span>
          <span className={styles.summaryValue}>{formatAmount(data.totalAmount)} 绿积分</span>
        </div>
      </div>

      {/* 按权益类型统计 */}
      {data.byRightType && data.byRightType.length > 0 && (
        <>
          <h4 className={styles.subTitle}>按权益类型统计</h4>
          <div className={styles.tableWrapper}>
            <table className={styles.table}>
              <thead>
                <tr>
                  <th>权益类型</th>
                  <th>笔数</th>
                  <th>金额 (绿积分)</th>
                </tr>
              </thead>
              <tbody>
                {data.byRightType.map((item) => (
                  <tr key={item.rightType}>
                    <td>{getRightTypeName(item.rightType)}</td>
                    <td>{item.count}</td>
                    <td>{formatAmount(item.amount)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </>
      )}

      {/* 按月统计 */}
      {data.byMonth && data.byMonth.length > 0 && (
        <>
          <h4 className={styles.subTitle}>按月统计</h4>
          <div className={styles.tableWrapper}>
            <table className={styles.table}>
              <thead>
                <tr>
                  <th>月份</th>
                  <th>笔数</th>
                  <th>金额 (绿积分)</th>
                </tr>
              </thead>
              <tbody>
                {data.byMonth.map((item) => (
                  <tr key={item.month}>
                    <td>{item.month}</td>
                    <td>{item.count}</td>
                    <td>{formatAmount(item.amount)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </>
      )}

      {/* [2026-01-07] 新增：明细列表 */}
      {showEntries && (
        <div className={styles.entriesSection}>
          <div className={styles.entriesHeader}>
            <h4 className={styles.subTitle}>过期收益明细</h4>
            <div className={styles.filterGroup}>
              <label>权益类型:</label>
              <select
                value={selectedRightType}
                onChange={(e) => handleRightTypeChange(e.target.value)}
                className={styles.filterSelect}
              >
                <option value="">全部</option>
                {data.byRightType?.map((item) => (
                  <option key={item.rightType} value={item.rightType}>
                    {getRightTypeName(item.rightType)}
                  </option>
                ))}
              </select>
            </div>
          </div>

          {entriesLoading ? (
            <div className={styles.loading}>
              <div className={styles.spinner} />
              <span>加载明细中...</span>
            </div>
          ) : entriesData && entriesData.entries.length > 0 ? (
            <>
              <div className={styles.tableWrapper}>
                <table className={styles.table}>
                  <thead>
                    <tr>
                      <th>过期时间</th>
                      <th>用户ID</th>
                      <th>账户</th>
                      <th>权益类型</th>
                      <th>金额 (绿积分)</th>
                      <th>订单号</th>
                    </tr>
                  </thead>
                  <tbody>
                    {entriesData.entries.map((entry) => (
                      <tr key={entry.id}>
                        <td>{entry.expiredAt ? new Date(entry.expiredAt).toLocaleString('zh-CN') : '-'}</td>
                        <td>{entry.userId}</td>
                        <td>{getAccountDisplayName(entry.accountSequence)}</td>
                        <td>{getRightTypeName(entry.rightType)}</td>
                        <td>{formatAmount(entry.usdtAmount)}</td>
                        <td className={styles.orderId}>{entry.sourceOrderId}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
              {/* 分页 */}
              {entriesData.totalPages > 1 && (
                <div className={styles.pagination}>
                  <button
                    onClick={() => handlePageChange(currentPage - 1)}
                    disabled={currentPage <= 1}
                    className={styles.pageButton}
                  >
                    上一页
                  </button>
                  <span className={styles.pageInfo}>
                    第 {currentPage} 页 / 共 {entriesData.totalPages} 页 (共 {entriesData.total} 条)
                  </span>
                  <button
                    onClick={() => handlePageChange(currentPage + 1)}
                    disabled={currentPage >= entriesData.totalPages}
                    className={styles.pageButton}
                  >
                    下一页
                  </button>
                </div>
              )}
            </>
          ) : (
            <div className={styles.emptyTable}>暂无过期收益明细数据</div>
          )}
        </div>
      )}

      {(!data.byRightType || data.byRightType.length === 0) && (!data.byMonth || data.byMonth.length === 0) && !showEntries && (
        <div className={styles.emptyTable}>暂无过期收益数据</div>
      )}
    </div>
  );
}

// [2026-01-05] 新增：分类账明细组件
/**
 * 分类账明细区域
 */
function LedgerSection({
  data,
  loading,
  onRefresh,
}: {
  data: AllSystemAccountsLedgerResponse | null;
  loading: boolean;
  onRefresh: () => void;
}) {
  const [expandedAccounts, setExpandedAccounts] = useState<Set<string>>(new Set());

  const toggleExpand = (accountKey: string) => {
    setExpandedAccounts((prev) => {
      const newSet = new Set(prev);
      if (newSet.has(accountKey)) {
        newSet.delete(accountKey);
      } else {
        newSet.add(accountKey);
      }
      return newSet;
    });
  };

  if (loading) {
    return (
      <div className={styles.loading}>
        <div className={styles.spinner} />
        <span>加载分类账明细中...</span>
      </div>
    );
  }

  if (!data) {
    return (
      <div className={styles.section}>
        <div className={styles.emptyTable}>
          <span>暂无分类账数据</span>
          <button onClick={onRefresh} className={styles.retryButton}>
            加载数据
          </button>
        </div>
      </div>
    );
  }

  const getEntryTypeLabel = (type: string): string => {
    return ENTRY_TYPE_LABELS[type] || type;
  };

  const getAccountTypeLabel = (type: string): string => {
    return ACCOUNT_TYPE_LABELS[type] || type;
  };

  return (
    <div className={styles.section}>
      <div className={styles.sectionHeader}>
        <h3 className={styles.sectionTitle}>分类账明细</h3>
        <button onClick={onRefresh} className={styles.refreshButton}>
          刷新
        </button>
      </div>

      {/* 固定系统账户分类账 */}
      {/* [2026-01-07] 更新：使用 getAccountDisplayName 显示账户名称和编码 */}
      {data.fixedAccountsLedger && data.fixedAccountsLedger.length > 0 && (
        <div className={styles.ledgerGroup}>
          <h4 className={styles.subTitle}>固定系统账户</h4>
          {data.fixedAccountsLedger.map((account) => (
            <LedgerAccountCard
              key={account.accountSequence}
              title={getAccountDisplayName(account.accountSequence)}
              subtitle=""
              ledger={account.ledger}
              total={account.total}
              expanded={expandedAccounts.has(account.accountSequence)}
              onToggle={() => toggleExpand(account.accountSequence)}
              getEntryTypeLabel={getEntryTypeLabel}
            />
          ))}
        </div>
      )}

      {/* 省区域账户分类账 */}
      {data.provinceAccountsLedger && data.provinceAccountsLedger.length > 0 && (
        <div className={styles.ledgerGroup}>
          <h4 className={styles.subTitle}>省区域账户 ({data.provinceAccountsLedger.length}个)</h4>
          {data.provinceAccountsLedger.map((account) => (
            <LedgerAccountCard
              key={account.accountSequence}
              title={account.regionName ? `${account.regionName} (${account.accountSequence})` : getAccountDisplayName(account.accountSequence)}
              subtitle=""
              ledger={account.ledger}
              total={account.total}
              expanded={expandedAccounts.has(account.accountSequence)}
              onToggle={() => toggleExpand(account.accountSequence)}
              getEntryTypeLabel={getEntryTypeLabel}
            />
          ))}
        </div>
      )}

      {/* 市区域账户分类账 */}
      {data.cityAccountsLedger && data.cityAccountsLedger.length > 0 && (
        <div className={styles.ledgerGroup}>
          <h4 className={styles.subTitle}>市区域账户 ({data.cityAccountsLedger.length}个)</h4>
          {data.cityAccountsLedger.map((account) => (
            <LedgerAccountCard
              key={account.accountSequence}
              title={account.regionName ? `${account.regionName} (${account.accountSequence})` : getAccountDisplayName(account.accountSequence)}
              subtitle=""
              ledger={account.ledger}
              total={account.total}
              expanded={expandedAccounts.has(account.accountSequence)}
              onToggle={() => toggleExpand(account.accountSequence)}
              getEntryTypeLabel={getEntryTypeLabel}
            />
          ))}
        </div>
      )}

      {(!data.fixedAccountsLedger || data.fixedAccountsLedger.length === 0) &&
        (!data.provinceAccountsLedger || data.provinceAccountsLedger.length === 0) &&
        (!data.cityAccountsLedger || data.cityAccountsLedger.length === 0) && (
          <div className={styles.emptyTable}>暂无分类账明细数据</div>
        )}
    </div>
  );
}

/**
 * 资产类型显示名称映射
 * [2026-01-05] 新增：USDT改为绿积分
 */
const getAssetTypeLabel = (assetType: string): string => {
  const labels: Record<string, string> = {
    USDT: '绿积分',
    usdt: '绿积分',
  };
  return labels[assetType] || assetType;
};

/**
 * 单个账户的分类账卡片
 * [2026-01-05] 更新：资产类型显示改用中文
 */
function LedgerAccountCard({
  title,
  subtitle,
  ledger,
  total,
  expanded,
  onToggle,
  getEntryTypeLabel,
}: {
  title: string;
  subtitle: string;
  ledger: LedgerEntryDTO[];
  total: number;
  expanded: boolean;
  onToggle: () => void;
  getEntryTypeLabel: (type: string) => string;
}) {
  return (
    <div className={styles.ledgerCard}>
      <div className={styles.ledgerCardHeader} onClick={onToggle}>
        <div className={styles.ledgerCardTitle}>
          <span className={styles.accountName}>{title}</span>
          {/* [2026-01-07] 更新：subtitle 为空时不显示 */}
          {subtitle && <span className={styles.accountSequence}>{subtitle}</span>}
        </div>
        <div className={styles.ledgerCardInfo}>
          <span className={styles.ledgerCount}>{total} 条记录</span>
          <span className={styles.expandIcon}>{expanded ? '▼' : '▶'}</span>
        </div>
      </div>
      {expanded && (
        <div className={styles.ledgerCardBody}>
          {ledger.length > 0 ? (
            <div className={styles.tableWrapper}>
              <table className={styles.table}>
                <thead>
                  <tr>
                    <th>时间</th>
                    <th>类型</th>
                    <th>金额</th>
                    <th>余额</th>
                    <th>来源账户</th>
                    <th>来源备注</th>
                    <th>备注</th>
                  </tr>
                </thead>
                <tbody>
                  {ledger.map((entry) => (
                    <tr key={entry.id}>
                      <td>{new Date(entry.createdAt).toLocaleString('zh-CN')}</td>
                      <td>
                        <span className={styles.entryTypeBadge}>
                          {getEntryTypeLabel(entry.entryType)}
                        </span>
                      </td>
                      <td className={entry.amount >= 0 ? styles.amountPositive : styles.amountNegative}>
                        {entry.amount >= 0 ? '+' : ''}{formatAmount(entry.amount)} {getAssetTypeLabel(entry.assetType)}
                      </td>
                      <td>{entry.balanceAfter !== null ? formatAmount(entry.balanceAfter) : '-'}</td>
                      <td className={styles.sourceAccount}>{entry.sourceAccountSequence || '-'}</td>
                      <td className={styles.memo}>{entry.sourceMemo || '-'}</td>
                      <td className={styles.memo}>{entry.memo || entry.allocationType || '-'}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          ) : (
            <div className={styles.emptyLedger}>暂无流水记录</div>
          )}
        </div>
      )}
    </div>
  );
}

// [2026-01-06] 更新：手续费账户汇总组件 - 使用真正的提现手续费归集数据
// 数据来源: wallet-service 的 S0000000006 账户 FEE_COLLECTION 类型流水
// 而非 reward-service 的系统费用（成本费、运营费等）
/**
 * 手续费账户汇总区域
 */
function FeeAccountSection({
  onRefresh,
}: {
  onRefresh: () => void;
}) {
  const [loading, setLoading] = useState(true);
  const [data, setData] = useState<FeeCollectionSummaryResponse | null>(null);
  const [showDetails, setShowDetails] = useState(false);
  const [detailsLoading, setDetailsLoading] = useState(false);
  const [detailsData, setDetailsData] = useState<FeeCollectionEntriesResponse | null>(null);
  const [currentPage, setCurrentPage] = useState(1);

  // 加载手续费归集汇总数据
  const loadSummary = useCallback(async () => {
    setLoading(true);
    try {
      const response = await systemAccountReportService.getFeeCollectionSummary();
      if (response.data) {
        setData(response.data);
      }
    } catch (err) {
      console.error('Failed to load fee collection summary:', err);
    } finally {
      setLoading(false);
    }
  }, []);

  // 加载详细流水
  const loadDetails = useCallback(async (page: number = 1) => {
    setDetailsLoading(true);
    try {
      const response = await systemAccountReportService.getFeeCollectionEntries({ page, pageSize: 20 });
      if (response.data) {
        setDetailsData(response.data);
        setCurrentPage(page);
      }
    } catch (err) {
      console.error('Failed to load fee collection entries:', err);
    } finally {
      setDetailsLoading(false);
    }
  }, []);

  // 初始加载
  useEffect(() => {
    loadSummary();
  }, [loadSummary]);

  const handleRefresh = () => {
    loadSummary();
    if (showDetails) {
      loadDetails(currentPage);
    }
    onRefresh();
  };

  const handleToggleDetails = () => {
    if (!showDetails && !detailsData) {
      loadDetails(1);
    }
    setShowDetails(!showDetails);
  };

  if (loading) {
    return (
      <div className={styles.loading}>
        <div className={styles.spinner} />
        <span>加载手续费账户汇总中...</span>
      </div>
    );
  }

  if (!data) {
    return (
      <div className={styles.section}>
        <div className={styles.emptyTable}>
          <span>暂无手续费账户数据</span>
          <button onClick={handleRefresh} className={styles.retryButton}>
            加载数据
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className={styles.section}>
      <div className={styles.sectionHeader}>
        <h3 className={styles.sectionTitle}>手续费账户汇总</h3>
        <button onClick={handleRefresh} className={styles.refreshButton}>
          刷新
        </button>
      </div>

      {/* 账户信息 */}
      {/* [2026-01-07] 更新：使用 getAccountDisplayName 显示账户名称和编码 */}
      <div className={styles.accountInfo}>
        <span className={styles.accountLabel}>手续费归集账户: </span>
        <span className={styles.accountValue}>{getAccountDisplayName(data.accountSequence)}</span>
      </div>

      {/* 汇总卡片 */}
      <div className={styles.summaryCards}>
        <div className={styles.summaryCard}>
          <span className={styles.summaryLabel}>当前余额</span>
          <span className={styles.summaryValue}>{formatAmount(data.accountBalance)} 绿积分</span>
        </div>
        <div className={styles.summaryCard}>
          <span className={styles.summaryLabel}>累计收取</span>
          <span className={styles.summaryValue}>{formatAmount(data.totalAmount)} 绿积分</span>
        </div>
        <div className={styles.summaryCard}>
          <span className={styles.summaryLabel}>总笔数</span>
          <span className={styles.summaryValue}>{data.totalCount}</span>
        </div>
      </div>

      {/* 按手续费类型明细 */}
      {data.breakdown && data.breakdown.length > 0 ? (
        <>
          <h4 className={styles.subTitle}>按手续费类型明细</h4>
          <div className={styles.tableWrapper}>
            <table className={styles.table}>
              <thead>
                <tr>
                  <th>手续费类型</th>
                  <th>金额 (绿积分)</th>
                  <th>笔数</th>
                </tr>
              </thead>
              <tbody>
                {data.breakdown.map((item) => (
                  <tr key={item.feeType}>
                    <td>{FEE_COLLECTION_TYPE_LABELS[item.feeType] || item.feeType}</td>
                    <td>{formatAmount(item.amount)}</td>
                    <td>{item.count}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </>
      ) : (
        <div className={styles.emptyTable}>暂无手续费数据</div>
      )}

      {/* 按月统计 */}
      {data.byMonth && data.byMonth.length > 0 && (
        <>
          <h4 className={styles.subTitle}>月度统计</h4>
          <div className={styles.tableWrapper}>
            <table className={styles.table}>
              <thead>
                <tr>
                  <th>月份</th>
                  <th>金额 (绿积分)</th>
                  <th>笔数</th>
                </tr>
              </thead>
              <tbody>
                {data.byMonth.map((item) => (
                  <tr key={item.month}>
                    <td>{item.month}</td>
                    <td>{formatAmount(item.amount)}</td>
                    <td>{item.count}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </>
      )}

      {/* 详细明细列表 */}
      <div className={styles.detailsSection}>
        <button onClick={handleToggleDetails} className={styles.toggleDetailsButton}>
          {showDetails ? '收起详细明细 ▲' : '查看详细明细 ▼'}
        </button>

        {showDetails && (
          <div className={styles.detailsContent}>
            {detailsLoading ? (
              <div className={styles.loading}>
                <div className={styles.spinner} />
                <span>加载详细明细中...</span>
              </div>
            ) : detailsData && detailsData.entries.length > 0 ? (
              <>
                <div className={styles.tableWrapper}>
                  <table className={styles.table}>
                    <thead>
                      <tr>
                        <th>时间</th>
                        <th>手续费类型</th>
                        <th>关联订单号</th>
                        <th>金额 (绿积分)</th>
                        <th>备注</th>
                      </tr>
                    </thead>
                    <tbody>
                      {detailsData.entries.map((entry) => (
                        <tr key={entry.id}>
                          <td>{new Date(entry.createdAt).toLocaleString('zh-CN')}</td>
                          <td>{FEE_COLLECTION_TYPE_LABELS[entry.feeType] || entry.feeType}</td>
                          <td className={styles.orderId}>{entry.refOrderId || '-'}</td>
                          <td>{formatAmount(entry.amount)}</td>
                          <td>{entry.memo || '-'}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
                {/* 分页 */}
                <div className={styles.pagination}>
                  <button
                    onClick={() => loadDetails(currentPage - 1)}
                    disabled={currentPage <= 1}
                    className={styles.pageButton}
                  >
                    上一页
                  </button>
                  <span className={styles.pageInfo}>
                    第 {currentPage} / {detailsData.totalPages} 页 (共 {detailsData.total} 条)
                  </span>
                  <button
                    onClick={() => loadDetails(currentPage + 1)}
                    disabled={currentPage >= detailsData.totalPages}
                    className={styles.pageButton}
                  >
                    下一页
                  </button>
                </div>
              </>
            ) : (
              <div className={styles.emptyTable}>暂无详细明细数据</div>
            )}
          </div>
        )}
      </div>
    </div>
  );
}

// [2026-01-06] 新增：收益类型汇总组件
// 收益类型映射到 API 使用的 rightType 值
const REWARD_TYPE_MAP: Record<string, string> = {
  '省团队收益汇总': 'PROVINCE_TEAM_RIGHT',
  '市团队收益汇总': 'CITY_TEAM_RIGHT',
  '分享引荐收益汇总': 'SHARE_RIGHT',
  '社区收益汇总': 'COMMUNITY_RIGHT',
};

/**
 * 收益类型汇总区域（省团队、市团队、分享引荐、社区）
 */
function RewardTypeSummarySection({
  title,
  data,
  loading,
  onRefresh,
}: {
  title: string;
  data: RewardTypeSummary | undefined;
  loading: boolean;
  onRefresh: () => void;
}) {
  const [showDetails, setShowDetails] = useState(false);
  const [detailsLoading, setDetailsLoading] = useState(false);
  const [detailsData, setDetailsData] = useState<RewardEntriesResponse | null>(null);
  const [currentPage, setCurrentPage] = useState(1);

  const rightType = REWARD_TYPE_MAP[title] || '';

  const loadDetails = useCallback(async (page: number = 1) => {
    if (!rightType) return;
    setDetailsLoading(true);
    try {
      const response = await systemAccountReportService.getRewardEntriesByType({
        rightType,
        page,
        pageSize: 20,
      });
      if (response.data) {
        setDetailsData(response.data);
        setCurrentPage(page);
      }
    } catch (err) {
      console.error('Failed to load reward entries details:', err);
    } finally {
      setDetailsLoading(false);
    }
  }, [rightType]);

  const handleToggleDetails = () => {
    if (!showDetails && !detailsData && rightType) {
      loadDetails(1);
    }
    setShowDetails(!showDetails);
  };

  if (loading) {
    return (
      <div className={styles.loading}>
        <div className={styles.spinner} />
        <span>加载{title}中...</span>
      </div>
    );
  }

  if (!data) {
    return (
      <div className={styles.section}>
        <div className={styles.emptyTable}>
          <span>暂无数据</span>
          <button onClick={onRefresh} className={styles.retryButton}>
            加载数据
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className={styles.section}>
      <div className={styles.sectionHeader}>
        <h3 className={styles.sectionTitle}>{title}</h3>
        <button onClick={onRefresh} className={styles.refreshButton}>
          刷新
        </button>
      </div>

      {/* [2026-01-06] 更新：全量汇总卡片（所有状态） */}
      <div className={styles.summaryCards}>
        <div className={styles.summaryCard}>
          <span className={styles.summaryLabel}>全部总金额</span>
          <span className={styles.summaryValue}>{formatAmount(data.allStatusTotalAmount ?? data.totalAmount)} 绿积分</span>
        </div>
        <div className={styles.summaryCard}>
          <span className={styles.summaryLabel}>全部总笔数</span>
          <span className={styles.summaryValue}>{data.allStatusTotalCount ?? data.totalCount}</span>
        </div>
        <div className={styles.summaryCard}>
          <span className={styles.summaryLabel}>有效收益金额</span>
          <span className={styles.summaryValue}>{formatAmount(data.totalAmount)} 绿积分</span>
        </div>
        <div className={styles.summaryCard}>
          <span className={styles.summaryLabel}>有效收益笔数</span>
          <span className={styles.summaryValue}>{data.totalCount}</span>
        </div>
      </div>

      {/* [2026-01-06] 新增：按状态分组统计 */}
      {data.byStatus && data.byStatus.length > 0 && (
        <>
          <h4 className={styles.subTitle}>按状态统计</h4>
          <div className={styles.tableWrapper}>
            <table className={styles.table}>
              <thead>
                <tr>
                  <th>状态</th>
                  <th>金额 (绿积分)</th>
                  <th>笔数</th>
                </tr>
              </thead>
              <tbody>
                {data.byStatus.map((item) => (
                  <tr key={item.status}>
                    <td>
                      <span className={`${styles.statusBadge} ${item.status === 'SETTLED' ? styles.settled : ''} ${item.status === 'EXPIRED' ? styles.expired : ''} ${item.status === 'PENDING' ? styles.pending : ''}`}>
                        {REWARD_STATUS_LABELS[item.status] || item.status}
                      </span>
                    </td>
                    <td>{formatAmount(item.amount)}</td>
                    <td>{item.count}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </>
      )}

      {/* 详细分类卡片 */}
      <h4 className={styles.subTitle}>详细分类</h4>
      <div className={styles.summaryCards}>
        <div className={styles.summaryCard}>
          <span className={styles.summaryLabel}>待领取</span>
          <span className={styles.summaryValue}>{formatAmount(data.pendingAmount ?? 0)} ({data.pendingCount ?? 0}笔)</span>
        </div>
        <div className={styles.summaryCard}>
          <span className={styles.summaryLabel}>可结算</span>
          <span className={styles.summaryValue}>{formatAmount(data.totalSettleableAmount)} ({(data.byStatus?.find(s => s.status === 'SETTLEABLE')?.count) ?? 0}笔)</span>
        </div>
        <div className={styles.summaryCard}>
          <span className={styles.summaryLabel}>已结算</span>
          <span className={styles.summaryValue}>{formatAmount(data.totalSettledAmount)} ({(data.byStatus?.find(s => s.status === 'SETTLED')?.count) ?? 0}笔)</span>
        </div>
        <div className={styles.summaryCard}>
          <span className={styles.summaryLabel}>已过期</span>
          <span className={styles.summaryValue}>{formatAmount(data.expiredAmount ?? 0)} ({data.expiredCount ?? 0}笔)</span>
        </div>
      </div>

      {/* 按月统计 */}
      {data.byMonth && data.byMonth.length > 0 ? (
        <>
          <h4 className={styles.subTitle}>按月统计（全部状态）</h4>
          <div className={styles.tableWrapper}>
            <table className={styles.table}>
              <thead>
                <tr>
                  <th>月份</th>
                  <th>金额 (绿积分)</th>
                  <th>笔数</th>
                </tr>
              </thead>
              <tbody>
                {data.byMonth.map((item) => (
                  <tr key={item.month}>
                    <td>{item.month}</td>
                    <td>{formatAmount(item.amount)}</td>
                    <td>{item.count}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </>
      ) : (
        <div className={styles.emptyTable}>暂无月度数据</div>
      )}

      {/* 详细明细列表 */}
      <div className={styles.detailsSection}>
        <button onClick={handleToggleDetails} className={styles.toggleDetailsButton}>
          {showDetails ? '收起详细明细 ▲' : '查看详细明细 ▼'}
        </button>

        {showDetails && (
          <div className={styles.detailsContent}>
            {detailsLoading ? (
              <div className={styles.loading}>
                <div className={styles.spinner} />
                <span>加载详细明细中...</span>
              </div>
            ) : detailsData && detailsData.entries.length > 0 ? (
              <>
                <div className={styles.tableWrapper}>
                  <table className={styles.table}>
                    <thead>
                      <tr>
                        <th>时间</th>
                        <th>账户</th>
                        {/* [2026-02-05] 新增：来源用户列，显示收益来自哪个用户的认种 */}
                        <th>来源用户</th>
                        <th>订单号</th>
                        <th>金额 (绿积分)</th>
                        <th>状态</th>
                      </tr>
                    </thead>
                    <tbody>
                      {detailsData.entries.map((entry) => (
                        <tr key={entry.id}>
                          <td>{new Date(entry.createdAt).toLocaleString('zh-CN')}</td>
                          {/* [2026-01-07] 更新：使用 getAccountDisplayName 显示账户名称和编码 */}
                          <td>{getAccountDisplayName(entry.accountSequence)}</td>
                          {/* [2026-02-05] 新增：显示来源用户账户序列号 */}
                          <td>{entry.sourceAccountSequence ?? '-'}</td>
                          <td className={styles.orderId}>{entry.sourceOrderId}</td>
                          <td>{formatAmount(entry.usdtAmount)}</td>
                          <td>
                            <span className={`${styles.statusBadge} ${entry.rewardStatus === 'SETTLED' ? styles.settled : ''}`}>
                              {REWARD_STATUS_LABELS[entry.rewardStatus] || entry.rewardStatus}
                            </span>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
                {/* 分页 */}
                <div className={styles.pagination}>
                  <button
                    onClick={() => loadDetails(currentPage - 1)}
                    disabled={currentPage <= 1}
                    className={styles.pageButton}
                  >
                    上一页
                  </button>
                  <span className={styles.pageInfo}>
                    第 {currentPage} / {detailsData.totalPages} 页 (共 {detailsData.total} 条)
                  </span>
                  <button
                    onClick={() => loadDetails(currentPage + 1)}
                    disabled={currentPage >= detailsData.totalPages}
                    className={styles.pageButton}
                  >
                    下一页
                  </button>
                </div>
              </>
            ) : (
              <div className={styles.emptyTable}>暂无详细明细数据</div>
            )}
          </div>
        )}
      </div>
    </div>
  );
}
