import { Injectable, Logger } from '@nestjs/common';
import { Decimal } from '@prisma/client/runtime/library';
import { PrismaService } from '../prisma/prisma.service';
import {
  IUserDetailQueryRepository,
  ReferralInfo,
  ReferralNode,
  PlantingSummary,
  PlantingLedgerItem,
  PlantingLedgerResult,
  WalletSummary,
  WalletLedgerItem,
  WalletLedgerResult,
  WalletLedgerFilters,
  AuthorizationRole,
  MonthlyAssessment,
  SystemAccountLedger,
  BenefitAssessment,
} from '../../../domain/repositories/user-detail-query.repository';

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

  constructor(private readonly prisma: PrismaService) {}

  // ============================================================================
  // 推荐关系相关
  // ============================================================================

  async getReferralInfo(accountSequence: string): Promise<ReferralInfo | null> {
    const referral = await this.prisma.referralQueryView.findUnique({
      where: { accountSequence },
    });

    if (!referral) return null;

    return {
      userId: referral.userId,
      accountSequence: referral.accountSequence,
      myReferralCode: referral.myReferralCode,
      usedReferralCode: referral.usedReferralCode,
      referrerId: referral.referrerId,
      ancestorPath: referral.ancestorPath,
      depth: referral.depth,
      directReferralCount: referral.directReferralCount,
      activeDirectCount: referral.activeDirectCount,
    };
  }

  async getAncestors(accountSequence: string, depth: number): Promise<ReferralNode[]> {
    const referral = await this.prisma.referralQueryView.findUnique({
      where: { accountSequence },
    });

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

    // 获取祖先列表（从直接推荐人开始，最多 depth 层）
    const ancestorIds = referral.ancestorPath.slice(0, depth);
    if (ancestorIds.length === 0) return [];

    // 获取祖先用户信息和引荐关系
    const [users, referrals] = await Promise.all([
      this.prisma.userQueryView.findMany({
        where: { userId: { in: ancestorIds } },
        select: {
          userId: true,
          accountSequence: true,
          nickname: true,
          avatarUrl: true,
        },
      }),
      this.prisma.referralQueryView.findMany({
        where: { userId: { in: ancestorIds } },
        select: {
          userId: true,
          accountSequence: true,
          depth: true,
        },
      }),
    ]);

    // 实时统计：获取每个祖先的认种数量、团队认种量和直推数量
    // 注意：优先从 referrals 获取 accountSequences，因为用户可能不存在于 user_query_view
    const referralAccountSequences = referrals.map(r => r.accountSequence);
    const [adoptionCounts, directReferralCounts, teamStats] = await Promise.all([
      // 统计每个用户的认种棵数（状态为 MINING_ENABLED）
      // 注意：使用 _sum.treeCount 而非 _count.id，因为一笔订单可以认种多棵，
      // 显示的是棵数（认种数量），不是订单条数。
      this.prisma.plantingOrderQueryView.groupBy({
        by: ['accountSequence'],
        where: {
          accountSequence: { in: referralAccountSequences },
          status: 'MINING_ENABLED',
        },
        _sum: { treeCount: true },
      }),
      // 统计每个用户的直推数量
      this.prisma.referralQueryView.groupBy({
        by: ['referrerId'],
        where: { referrerId: { in: ancestorIds } },
        _count: { userId: true },
      }),
      // 获取团队认种量
      this.getBatchUserStats(referralAccountSequences),
    ]);

    const adoptionCountMap = new Map(adoptionCounts.map(a => [a.accountSequence, a._sum.treeCount ?? 0]));
    const directCountMap = new Map(
      directReferralCounts
        .filter(d => d.referrerId !== null)
        .map(d => [d.referrerId!.toString(), d._count.userId])
    );

    // 合并数据
    const referralMap = new Map(referrals.map((r) => [r.userId.toString(), r]));
    const userMap = new Map(users.map((u) => [u.userId.toString(), u]));

    return ancestorIds.map((id, index) => {
      const user = userMap.get(id.toString());
      const ref = referralMap.get(id.toString());
      // 优先从 referralQueryView 获取 accountSequence（更可靠）
      const accountSeq = ref?.accountSequence || user?.accountSequence || '';
      const stats = teamStats.get(accountSeq);
      return {
        userId: id,
        accountSequence: accountSeq,
        nickname: user?.nickname || null,
        avatarUrl: user?.avatarUrl || null,
        personalAdoptionCount: adoptionCountMap.get(accountSeq) || 0,
        teamAdoptionCount: stats?.teamAdoptionCount || 0,
        depth: ref?.depth || index,
        directReferralCount: directCountMap.get(id.toString()) || 0,
      };
    });
  }

  async getDirectReferrals(accountSequence: string): Promise<ReferralNode[]> {
    const referral = await this.prisma.referralQueryView.findUnique({
      where: { accountSequence },
    });

    if (!referral) return [];

    // 查找直接推荐的用户（referrerId = 当前用户的 userId）
    const directReferrals = await this.prisma.referralQueryView.findMany({
      where: { referrerId: referral.userId },
      select: {
        userId: true,
        accountSequence: true,
        depth: true,
      },
    });

    if (directReferrals.length === 0) return [];

    // 获取用户信息
    const userIds = directReferrals.map((r) => r.userId);
    const users = await this.prisma.userQueryView.findMany({
      where: { userId: { in: userIds } },
      select: {
        userId: true,
        accountSequence: true,
        nickname: true,
        avatarUrl: true,
      },
    });

    // 实时统计：获取每个用户的认种数量、团队认种量和直推数量
    const userAccountSequences = directReferrals.map(r => r.accountSequence);
    const [adoptionCounts, directReferralCounts, teamStats] = await Promise.all([
      // 统计每个用户的认种棵数（状态为 MINING_ENABLED）
      // 注意：使用 _sum.treeCount 而非 _count.id，因为一笔订单可以认种多棵，
      // 显示的是棵数（认种数量），不是订单条数。
      this.prisma.plantingOrderQueryView.groupBy({
        by: ['accountSequence'],
        where: {
          accountSequence: { in: userAccountSequences },
          status: 'MINING_ENABLED',
        },
        _sum: { treeCount: true },
      }),
      // 统计每个用户的直推数量
      this.prisma.referralQueryView.groupBy({
        by: ['referrerId'],
        where: { referrerId: { in: userIds } },
        _count: { userId: true },
      }),
      // 获取团队认种量
      this.getBatchUserStats(userAccountSequences),
    ]);

    const adoptionCountMap = new Map(adoptionCounts.map(a => [a.accountSequence, a._sum.treeCount ?? 0]));
    const directCountMap = new Map(
      directReferralCounts
        .filter(d => d.referrerId !== null)
        .map(d => [d.referrerId!.toString(), d._count.userId])
    );
    const userMap = new Map(users.map((u) => [u.userId.toString(), u]));

    return directReferrals.map((ref) => {
      const user = userMap.get(ref.userId.toString());
      const stats = teamStats.get(ref.accountSequence);
      return {
        userId: ref.userId,
        accountSequence: ref.accountSequence,
        nickname: user?.nickname || null,
        avatarUrl: user?.avatarUrl || null,
        personalAdoptionCount: adoptionCountMap.get(ref.accountSequence) || 0,
        teamAdoptionCount: stats?.teamAdoptionCount || 0,
        depth: ref.depth,
        directReferralCount: directCountMap.get(ref.userId.toString()) || 0,
      };
    });
  }

  async getReferrerNickname(referrerId: bigint): Promise<string | null> {
    const user = await this.prisma.userQueryView.findUnique({
      where: { userId: referrerId },
      select: { nickname: true },
    });
    return user?.nickname || null;
  }

  // ============================================================================
  // 认种相关
  // ============================================================================

  async getPlantingSummary(accountSequence: string): Promise<PlantingSummary | null> {
    this.logger.log(`[getPlantingSummary] 查询认种汇总, accountSequence=${accountSequence}`);

    // 先获取用户的 userId 用于查询持仓
    const user = await this.prisma.userQueryView.findUnique({
      where: { accountSequence },
      select: { userId: true },
    });

    this.logger.log(`[getPlantingSummary] 用户查询结果: ${user ? `userId=${user.userId}` : 'null'}`);

    if (!user) return null;

    // 获取持仓信息
    const position = await this.prisma.plantingPositionQueryView.findUnique({
      where: { userId: user.userId },
    });

    this.logger.log(`[getPlantingSummary] 持仓查询结果: ${position ? `effectiveTreeCount=${position.effectiveTreeCount}` : 'null'}`);

    // 已支付及之后的状态（不包括 CREATED, PROVINCE_CITY_CONFIRMED, CANCELLED）
    const paidStatuses = ['PAID', 'FUND_ALLOCATED', 'POOL_SCHEDULED', 'POOL_INJECTED', 'MINING_ENABLED'];

    // 获取订单统计 - 只统计已支付的订单
    const [orderStats, firstOrder, lastOrder] = await Promise.all([
      this.prisma.plantingOrderQueryView.aggregate({
        where: { accountSequence, status: { in: paidStatuses } },
        _count: true,
        _sum: {
          treeCount: true,
          totalAmount: true,
        },
      }),
      this.prisma.plantingOrderQueryView.findFirst({
        where: { accountSequence, paidAt: { not: null } },
        orderBy: { paidAt: 'asc' },
        select: { paidAt: true },
      }),
      this.prisma.plantingOrderQueryView.findFirst({
        where: { accountSequence, paidAt: { not: null } },
        orderBy: { paidAt: 'desc' },
        select: { paidAt: true },
      }),
    ]);

    this.logger.log(`[getPlantingSummary] 订单统计: count=${orderStats._count}, treeCount=${orderStats._sum.treeCount}, totalAmount=${orderStats._sum.totalAmount}`);

    return {
      totalOrders: orderStats._count,
      totalTreeCount: orderStats._sum.treeCount || 0,
      totalAmount: this.decimalToString(orderStats._sum.totalAmount),
      effectiveTreeCount: position?.effectiveTreeCount || 0,
      pendingTreeCount: position?.pendingTreeCount || 0,
      firstPlantingAt: firstOrder?.paidAt || null,
      lastPlantingAt: lastOrder?.paidAt || null,
    };
  }

  async getPlantingLedger(
    accountSequence: string,
    page: number,
    pageSize: number,
    startDate?: Date,
    endDate?: Date,
  ): Promise<PlantingLedgerResult> {
    // 已支付及之后的状态（不包括 CREATED, PROVINCE_CITY_CONFIRMED, CANCELLED）
    const paidStatuses = ['PAID', 'FUND_ALLOCATED', 'POOL_SCHEDULED', 'POOL_INJECTED', 'MINING_ENABLED'];

    const where: any = { accountSequence, status: { in: paidStatuses } };

    if (startDate || endDate) {
      where.createdAt = {};
      if (startDate) where.createdAt.gte = startDate;
      if (endDate) where.createdAt.lte = endDate;
    }

    const [total, items] = await Promise.all([
      this.prisma.plantingOrderQueryView.count({ where }),
      this.prisma.plantingOrderQueryView.findMany({
        where,
        skip: (page - 1) * pageSize,
        take: pageSize,
        orderBy: { createdAt: 'desc' },
      }),
    ]);

    return {
      items: items.map((item) => ({
        orderId: item.id,
        orderNo: item.orderNo,
        treeCount: item.treeCount,
        totalAmount: this.decimalToString(item.totalAmount),
        status: item.status,
        selectedProvince: item.selectedProvince,
        selectedCity: item.selectedCity,
        createdAt: item.createdAt,
        paidAt: item.paidAt,
        fundAllocatedAt: item.fundAllocatedAt,
        miningEnabledAt: item.miningEnabledAt,
      })),
      total,
      page,
      pageSize,
      totalPages: Math.ceil(total / pageSize),
    };
  }

  // ============================================================================
  // 钱包相关
  // ============================================================================

  async getWalletSummary(accountSequence: string): Promise<WalletSummary | null> {
    this.logger.log(`[getWalletSummary] 查询钱包, accountSequence=${accountSequence}`);

    const wallet = await this.prisma.walletAccountQueryView.findUnique({
      where: { accountSequence },
    });

    this.logger.log(`[getWalletSummary] 查询结果: ${wallet ? `id=${wallet.id}, userId=${wallet.userId}, usdtAvailable=${wallet.usdtAvailable}` : 'null'}`);

    if (!wallet) return null;

    return {
      usdtAvailable: this.decimalToString(wallet.usdtAvailable),
      usdtFrozen: this.decimalToString(wallet.usdtFrozen),
      dstAvailable: this.decimalToString(wallet.dstAvailable),
      dstFrozen: this.decimalToString(wallet.dstFrozen),
      bnbAvailable: this.decimalToString(wallet.bnbAvailable),
      bnbFrozen: this.decimalToString(wallet.bnbFrozen),
      ogAvailable: this.decimalToString(wallet.ogAvailable),
      ogFrozen: this.decimalToString(wallet.ogFrozen),
      rwadAvailable: this.decimalToString(wallet.rwadAvailable),
      rwadFrozen: this.decimalToString(wallet.rwadFrozen),
      hashpower: this.decimalToString(wallet.hashpower),
      pendingUsdt: this.decimalToString(wallet.pendingUsdt),
      pendingHashpower: this.decimalToString(wallet.pendingHashpower),
      settleableUsdt: this.decimalToString(wallet.settleableUsdt),
      settleableHashpower: this.decimalToString(wallet.settleableHashpower),
      settledTotalUsdt: this.decimalToString(wallet.settledTotalUsdt),
      settledTotalHashpower: this.decimalToString(wallet.settledTotalHashpower),
      expiredTotalUsdt: this.decimalToString(wallet.expiredTotalUsdt),
      expiredTotalHashpower: this.decimalToString(wallet.expiredTotalHashpower),
    };
  }

  async getWalletLedger(
    accountSequence: string,
    page: number,
    pageSize: number,
    filters?: WalletLedgerFilters,
  ): Promise<WalletLedgerResult> {
    this.logger.log(`[getWalletLedger] 查询钱包流水, accountSequence=${accountSequence}, page=${page}`);

    const where: any = { accountSequence };

    if (filters?.assetType) {
      where.assetType = filters.assetType;
    }
    if (filters?.entryType) {
      where.entryType = filters.entryType;
    }
    if (filters?.startDate || filters?.endDate) {
      where.createdAt = {};
      if (filters.startDate) where.createdAt.gte = filters.startDate;
      if (filters.endDate) where.createdAt.lte = filters.endDate;
    }

    const [total, items] = await Promise.all([
      this.prisma.walletLedgerEntryView.count({ where }),
      this.prisma.walletLedgerEntryView.findMany({
        where,
        skip: (page - 1) * pageSize,
        take: pageSize,
        orderBy: { createdAt: 'desc' },
      }),
    ]);

    return {
      items: items.map((item) => ({
        entryId: item.id,
        entryType: item.entryType,
        assetType: item.assetType,
        amount: this.decimalToString(item.amount),
        balanceAfter: item.balanceAfter ? this.decimalToString(item.balanceAfter) : null,
        refOrderId: item.refOrderId,
        refTxHash: item.refTxHash,
        memo: item.memo,
        createdAt: item.createdAt,
      })),
      total,
      page,
      pageSize,
      totalPages: Math.ceil(total / pageSize),
    };
  }

  // ============================================================================
  // 授权相关
  // ============================================================================

  async getAuthorizationRoles(accountSequence: string): Promise<AuthorizationRole[]> {
    const roles = await this.prisma.authorizationRoleQueryView.findMany({
      where: {
        accountSequence,
        deletedAt: null,
      },
      orderBy: { createdAt: 'desc' },
    });

    return roles.map((role) => ({
      id: role.id,
      roleType: role.roleType,
      regionCode: role.regionCode,
      regionName: role.regionName,
      displayTitle: role.displayTitle,
      status: role.status,
      benefitActive: role.benefitActive,
      benefitActivatedAt: role.benefitActivatedAt,
      authorizedAt: role.authorizedAt,
      authorizedBy: role.authorizedBy,
      initialTargetTreeCount: role.initialTargetTreeCount,
      monthlyTargetType: role.monthlyTargetType,
      lastAssessmentMonth: role.lastAssessmentMonth,
      monthlyTreesAdded: role.monthlyTreesAdded,
      officePhotoUrls: role.officePhotoUrls ?? [],
      createdAt: role.createdAt,
    }));
  }

  async getMonthlyAssessments(accountSequence: string): Promise<MonthlyAssessment[]> {
    const assessments = await this.prisma.monthlyAssessmentQueryView.findMany({
      where: { accountSequence },
      orderBy: [{ assessmentMonth: 'desc' }, { createdAt: 'desc' }],
    });

    return assessments.map((assessment) => ({
      id: assessment.id,
      authorizationId: assessment.authorizationId,
      roleType: assessment.roleType,
      regionCode: assessment.regionCode,
      assessmentMonth: assessment.assessmentMonth,
      monthIndex: assessment.monthIndex,
      monthlyTarget: assessment.monthlyTarget,
      monthlyCompleted: assessment.monthlyCompleted,
      cumulativeTarget: assessment.cumulativeTarget,
      cumulativeCompleted: assessment.cumulativeCompleted,
      result: assessment.result,
      rankingInRegion: assessment.rankingInRegion,
      isFirstPlace: assessment.isFirstPlace,
      isBypassed: assessment.isBypassed,
      completedAt: assessment.completedAt,
      assessedAt: assessment.assessedAt,
    }));
  }

  async getSystemAccountLedger(accountSequence: string): Promise<SystemAccountLedger[]> {
    // 先获取用户的授权角色
    const roles = await this.prisma.authorizationRoleQueryView.findMany({
      where: {
        accountSequence,
        deletedAt: null,
      },
      select: { id: true },
    });

    if (roles.length === 0) return [];

    // 注：SystemAccountLedgerView 不直接关联用户，这里暂时返回空
    // 实际业务中可能需要根据授权角色ID或区域来查询相关流水
    // 这里简化处理，如果需要可以通过其他方式关联
    return [];
  }

  // [2026-01-08] 新增：获取权益考核记录
  async getBenefitAssessments(accountSequence: string): Promise<BenefitAssessment[]> {
    const assessments = await this.prisma.benefitAssessmentQueryView.findMany({
      where: { accountSequence },
      orderBy: [{ assessmentMonth: 'desc' }, { createdAt: 'desc' }],
    });

    return assessments.map((assessment) => ({
      id: assessment.id,
      authorizationId: assessment.authorizationId,
      roleType: assessment.roleType,
      regionCode: assessment.regionCode,
      regionName: assessment.regionName,
      assessmentMonth: assessment.assessmentMonth,
      monthIndex: assessment.monthIndex,
      monthlyTarget: assessment.monthlyTarget,
      cumulativeTarget: assessment.cumulativeTarget,
      treesCompleted: assessment.treesCompleted,
      treesRequired: assessment.treesRequired,
      benefitActionTaken: assessment.benefitActionTaken,
      previousBenefitStatus: assessment.previousBenefitStatus,
      newBenefitStatus: assessment.newBenefitStatus,
      newValidUntil: assessment.newValidUntil,
      result: assessment.result,
      remarks: assessment.remarks,
      assessedAt: assessment.assessedAt,
      createdAt: assessment.createdAt,
    }));
  }

  async getPersonalAdoptionCount(accountSequence: string): Promise<number> {
    // 统计用户的认种棵数（状态为 MINING_ENABLED）
    // 注意：使用 aggregate._sum.treeCount 而非 count()，因为一笔订单可以认种多棵，
    // 返回的是总棵数（认种数量），不是订单条数。
    const result = await this.prisma.plantingOrderQueryView.aggregate({
      where: {
        accountSequence,
        status: 'MINING_ENABLED',
      },
      _sum: { treeCount: true },
    });

    return result._sum.treeCount ?? 0;
  }

  async getDirectReferralCount(accountSequence: string): Promise<number> {
    // 先获取用户的 userId
    const referral = await this.prisma.referralQueryView.findUnique({
      where: { accountSequence },
      select: { userId: true },
    });

    if (!referral) return 0;

    // 统计以该用户为 referrerId 的用户数量
    const count = await this.prisma.referralQueryView.count({
      where: { referrerId: referral.userId },
    });

    return count;
  }

  async getTeamStats(accountSequence: string): Promise<{ teamAddressCount: number; teamAdoptionCount: number }> {
    // 从 referralQueryView 获取用户的 userId（而不是 userQueryView，因为两边的 userId 可能不一致）
    const referral = await this.prisma.referralQueryView.findUnique({
      where: { accountSequence },
      select: { userId: true },
    });

    if (!referral) return { teamAddressCount: 0, teamAdoptionCount: 0 };

    // 1. 获取团队地址数：递归查找所有以当前用户为祖先的推荐关系
    // ancestorPath 包含所有祖先 userId，如果当前用户的 userId 在某用户的 ancestorPath 中，说明该用户是当前用户的下级
    const teamMembers = await this.prisma.referralQueryView.findMany({
      where: {
        ancestorPath: {
          has: referral.userId,
        },
      },
      select: { accountSequence: true },
    });

    const teamAddressCount = teamMembers.length;

    // 2. 获取团队认种量：汇总所有团队成员的有效认种棵数
    // 注意：使用 aggregate._sum.treeCount 而非 count()，因为一笔订单可以认种多棵。
    let teamAdoptionCount = 0;
    if (teamMembers.length > 0) {
      const result = await this.prisma.plantingOrderQueryView.aggregate({
        where: {
          accountSequence: { in: teamMembers.map((m) => m.accountSequence) },
          status: 'MINING_ENABLED',
        },
        _sum: { treeCount: true },
      });

      teamAdoptionCount = result._sum.treeCount ?? 0;
    }

    return { teamAddressCount, teamAdoptionCount };
  }

  async getBatchUserStats(accountSequences: string[]): Promise<Map<string, {
    personalAdoptionCount: number;
    teamAddressCount: number;
    teamAdoptionCount: number;
    provinceAdoptionCount: number;
    cityAdoptionCount: number;
  }>> {
    const result = new Map<string, {
      personalAdoptionCount: number;
      teamAddressCount: number;
      teamAdoptionCount: number;
      provinceAdoptionCount: number;
      cityAdoptionCount: number;
    }>();

    if (accountSequences.length === 0) return result;

    // 1. 批量获取个人认种棵数
    // 注意：使用 _sum.treeCount 而非 _count.id，因为一笔订单可以认种多棵，
    // 显示的是棵数（认种数量），不是订单条数。
    const personalAdoptionCounts = await this.prisma.plantingOrderQueryView.groupBy({
      by: ['accountSequence'],
      where: {
        accountSequence: { in: accountSequences },
        status: 'MINING_ENABLED',
      },
      _sum: { treeCount: true },
    });
    const personalAdoptionMap = new Map(
      personalAdoptionCounts.map(p => [p.accountSequence, p._sum.treeCount ?? 0])
    );

    // 2. 批量获取用户的省市信息（从认种订单中获取第一个订单的省市）
    const userProvinceCity = await this.prisma.plantingOrderQueryView.findMany({
      where: {
        accountSequence: { in: accountSequences },
        status: 'MINING_ENABLED',
        selectedProvince: { not: null },
      },
      select: {
        accountSequence: true,
        selectedProvince: true,
        selectedCity: true,
      },
      distinct: ['accountSequence'],
      orderBy: { createdAt: 'asc' },
    });
    const userProvinceCityMap = new Map(
      userProvinceCity.map(u => [u.accountSequence, { province: u.selectedProvince, city: u.selectedCity }])
    );

    // 3. 批量获取 userId 用于团队统计
    const referrals = await this.prisma.referralQueryView.findMany({
      where: { accountSequence: { in: accountSequences } },
      select: { accountSequence: true, userId: true },
    });
    const userIdMap = new Map(referrals.map(r => [r.accountSequence, r.userId]));

    // 4. 对每个用户计算团队统计
    for (const accountSequence of accountSequences) {
      const userId = userIdMap.get(accountSequence);
      const userLocation = userProvinceCityMap.get(accountSequence);
      let teamAddressCount = 0;
      let teamAdoptionCount = 0;
      let provinceAdoptionCount = 0;
      let cityAdoptionCount = 0;

      if (userId) {
        // 获取团队成员
        const teamMembers = await this.prisma.referralQueryView.findMany({
          where: {
            ancestorPath: { has: userId },
          },
          select: { accountSequence: true },
        });

        teamAddressCount = teamMembers.length;

        // 获取团队认种量及省市统计
        if (teamMembers.length > 0) {
          const teamAccountSequences = teamMembers.map(m => m.accountSequence);

          // 团队总认种棵数（使用 sum treeCount，不是 count orders）
          const teamResult = await this.prisma.plantingOrderQueryView.aggregate({
            where: {
              accountSequence: { in: teamAccountSequences },
              status: 'MINING_ENABLED',
            },
            _sum: { treeCount: true },
          });
          teamAdoptionCount = teamResult._sum.treeCount ?? 0;

          // 如果用户有省市信息，统计同省同市的认种棵数
          if (userLocation?.province) {
            // 同省认种棵数
            const provinceResult = await this.prisma.plantingOrderQueryView.aggregate({
              where: {
                accountSequence: { in: teamAccountSequences },
                status: 'MINING_ENABLED',
                selectedProvince: userLocation.province,
              },
              _sum: { treeCount: true },
            });
            provinceAdoptionCount = provinceResult._sum.treeCount ?? 0;

            // 同市认种棵数
            if (userLocation.city) {
              const cityResult = await this.prisma.plantingOrderQueryView.aggregate({
                where: {
                  accountSequence: { in: teamAccountSequences },
                  status: 'MINING_ENABLED',
                  selectedProvince: userLocation.province,
                  selectedCity: userLocation.city,
                },
                _sum: { treeCount: true },
              });
              cityAdoptionCount = cityResult._sum.treeCount ?? 0;
            }
          }
        }
      }

      result.set(accountSequence, {
        personalAdoptionCount: personalAdoptionMap.get(accountSequence) || 0,
        teamAddressCount,
        teamAdoptionCount,
        provinceAdoptionCount,
        cityAdoptionCount,
      });
    }

    return result;
  }

  // ============================================================================
  // 辅助方法
  // ============================================================================

  /**
   * 将 Decimal 转为字符串，保留合理精度
   * 使用 toString() 避免 Prisma Decimal 的 toFixed 精度问题
   */
  private decimalToString(decimal: Decimal | null | undefined): string {
    if (!decimal) return '0';
    // 使用 toString() 获取原始值，去掉尾部多余的 0
    const str = decimal.toString();
    // 如果有小数点，去掉尾部的 0
    if (str.includes('.')) {
      return str.replace(/\.?0+$/, '');
    }
    return str;
  }
}
